Skip to main content

teksilo_core/
widget_builder.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! WidgetBuilder trait — blanket-implemented for all Widget types.
5//!
6//! Provides attached event handler methods and framework-level properties.
7//! Each method wraps the widget in a `WidgetWithHandlers<W>` that stores
8//! the handlers and metadata alongside the widget. When the widget is
9//! inserted into the arena, the handler set is extracted and applied to
10//! the `WidgetNode`.
11//!
12//! The four click-style handlers (`on_tap` / `on_double_tap` /
13//! `on_triple_tap` / `on_long_press`) all receive a borrowed
14//! [`crate::gesture::TapEvent`] (position + button + modifiers) and
15//! default to [`crate::event::ButtonMask::PRIMARY`] acceptance. Widen
16//! that filter via the matching `accept_*_buttons(...)` knob — see the
17//! "Event System" section in `docs/events-and-gestures.md` for the
18//! full contract and examples.
19
20use teksilo_canvas::Point;
21
22use crate::event::{ButtonMask, EventResponse, WidgetEvent};
23use crate::event_handlers::EventHandlers;
24use crate::gesture::MultiContact;
25use crate::gesture::{DragPhase, PinchPhase, SwipeDirection, TapEvent};
26use crate::pointer::touch_action::{PanAxes, PanClaim, TouchAction};
27use crate::signal::Prop;
28use crate::widget::{CursorIcon, EventContext, Widget};
29use crate::widget_id::WidgetId;
30
31// ---------------------------------------------------------------------------
32// Accessibility overrides
33// ---------------------------------------------------------------------------
34
35/// Subtree visibility / merge mode applied by the accessibility tree walker.
36///
37/// Set via `WidgetBuilder::access_exclude_subtree()` /
38/// `access_merge_subtree()`. The walker honors the mode after the parent
39/// node has been emitted, before recursing into descendants.
40#[derive(Default, Clone, Copy, PartialEq, Eq, Debug)]
41pub enum AccessSubtreeMode {
42    /// Normal walk — descendants emitted as their own AT nodes.
43    #[default]
44    Inherit,
45    /// Descendants pruned from the AT tree entirely. Parent node still
46    /// emitted normally. Equivalent to Flutter's `excludeSemantics: true`.
47    Exclude,
48    /// Descendants' labels / descriptions / values / actions are
49    /// concatenated into the parent's emitted node, then descendants are
50    /// pruned. The parent reads as a single AT element. Equivalent to
51    /// Flutter's `mergeAllDescendants: true` and SwiftUI's
52    /// `.accessibilityElement(children: .combine)`.
53    Merge,
54}
55
56/// Builder-level accessibility overrides.
57///
58/// Carried on `HandlerSet` during builder-chain construction, mirrored
59/// onto `WidgetNode::access_overrides` at arena insertion (parallel to
60/// `clips_children` / `cursor` / `focus_within_signal`), then applied by
61/// the accessibility tree walker after the inner widget's
62/// `accessibility(&self, builder)` runs.
63///
64/// User-visible string fields store a `Prop<String>` rather than a
65/// resolved `String`, so they stay reactive to locale changes.
66/// `teksilo-core` can't name `LocalizedString` (that lives in the
67/// downstream `teksilo-i18n` crate), but `Prop<String>` is a core type
68/// and `impl From<LocalizedString> for Prop<String>` in `teksilo-i18n`
69/// yields a `Prop::Bound` over a locale-observing `Signal<String>`. So
70/// `.access_label(tr!(save()))` stores a bound prop; the accessibility
71/// walker reads `.get()` at AT-build time, and `sync_accessibility`
72/// re-walks on locale change so the announced value follows the locale.
73/// The `_literal` builder variants store `Prop::Static` and are the
74/// `#[doc(hidden)]` grep markers for explicitly untranslated call sites
75/// (the only literal path reachable from within `teksilo-core`).
76#[derive(Default)]
77pub struct AccessibilityOverrides {
78    // -- Tier 1: labeling / state -----------------------------------------
79    pub label: Option<Prop<String>>,
80    pub description: Option<Prop<String>>,
81    pub value: Option<Prop<String>>,
82    pub role: Option<accesskit::Role>,
83    /// Reactive hidden-from-AT flag. `Some(prop)` where the prop reads
84    /// `true` hides the node and its whole subtree from assistive
85    /// technologies; `false` un-sets a
86    /// hidden state the inner widget emitted unconditionally. Bound props are
87    /// registered at `AccessibilityOnly` so the AT tree re-walks when they
88    /// flip (see the insertion paths in `widget_tree.rs`).
89    pub hidden: Option<Prop<bool>>,
90    pub disabled: Option<bool>,
91
92    // -- Tier 2: relationships / live / identity --------------------------
93    pub identifier: Option<String>,
94    pub controls: Vec<WidgetId>,
95    pub described_by: Vec<WidgetId>,
96    pub labelled_by: Vec<WidgetId>,
97    pub live: Option<accesskit::Live>,
98    pub aria_current: Option<accesskit::AriaCurrent>,
99    /// Pre-formatted shortcut announcement string (e.g. `"Ctrl+S"`).
100    /// Used by `access_shortcut_literal`. For chords routed through a
101    /// `Shortcut` registration, prefer `access_shortcut_id` (stored
102    /// in `shortcut_id`) so the announcement tracks rebinds.
103    pub shortcut: Option<String>,
104    /// Registered shortcut id (e.g. `"app.save"`). The accessibility
105    /// walker resolves the current keystroke from
106    /// `WidgetTree::shortcut_registry()` at AT-build time and writes
107    /// the formatted string to `Node::keyboard_shortcut`. Refreshes
108    /// automatically when the user rebinds (the registry's `version`
109    /// signal triggers a re-sync).
110    pub shortcut_id: Option<String>,
111    pub has_popup: Option<accesskit::HasPopup>,
112    pub orientation: Option<accesskit::Orientation>,
113
114    // -- Tier 3: numeric / actions / escape hatch -------------------------
115    pub numeric_value: Option<f64>,
116    pub min_numeric_value: Option<f64>,
117    pub max_numeric_value: Option<f64>,
118    pub numeric_step: Option<f64>,
119
120    /// Standard `accesskit::Action` advertisements with their handlers.
121    /// Dispatched by `pointer_router.rs` when handling
122    /// `WidgetEvent::AccessAction`, layered on top of any
123    /// user-installed `on_access_action` / `on_access_action_request`
124    /// handlers (both fire for the same dispatched event).
125    pub actions: Vec<(accesskit::Action, Box<dyn FnMut(&mut EventContext)>)>,
126
127    /// Actions to remove from the widget-emitted action list (called
128    /// after the widget's `accessibility()` runs, before custom-action
129    /// emission).
130    pub removed_actions: Vec<accesskit::Action>,
131
132    /// Custom-named actions (SwiftUI `.accessibilityAction(named:_:)`).
133    /// Each entry pairs a (reactive) description prop with a handler.
134    /// Index in the vec is the stable `i32` `CustomAction::id` exposed
135    /// to AT software.
136    pub custom_actions: Vec<(Prop<String>, Box<dyn FnMut(&mut EventContext)>)>,
137
138    /// Final escape hatch — invoked **last** in `apply()` with full
139    /// `&mut AccessNodeBuilder` access (including `inner_mut()`). Used
140    /// for sub-node surgery (synthetic children) and for cases the
141    /// typed surface doesn't cover.
142    pub customize: Option<Box<dyn Fn(&mut crate::accessibility::AccessNodeBuilder)>>,
143}
144
145impl AccessibilityOverrides {
146    /// Fold `other` into `self`: later scalars win, lists append.
147    ///
148    /// Needed because overrides reach a node from **two** directions — a builder
149    /// chain at construction (`WidgetWithHandlers::access_*`) and a later
150    /// [`BuildContext::apply_handlers`](crate::build_context::BuildContext::apply_handlers)
151    /// on the same id, which is how a widget gives a node it already built one
152    /// more action. Assigning the second block over the first silently dropped
153    /// everything in the first, and nothing else reads an override block, so the
154    /// loss was invisible: a `TreeTableView` row lost `ScrollIntoView` and its
155    /// `Expand` / `Collapse` pair the moment it also gained a move command.
156    ///
157    /// The merge rules are the ones
158    /// [the overrides page](https://github.com/ferntech-eu/teksilo/blob/main/docs/accessibility-overrides.md)
159    /// already documents for a single block: scalars replace when set, lists
160    /// append. `customize` is the exception — it is an escape hatch and both
161    /// halves may matter, so two are **chained** in application order rather
162    /// than one winning.
163    pub(crate) fn merge_from(&mut self, other: Self) {
164        macro_rules! scalar {
165            ($($field:ident),+ $(,)?) => {
166                $(if other.$field.is_some() { self.$field = other.$field; })+
167            };
168        }
169        scalar!(
170            label,
171            description,
172            value,
173            role,
174            hidden,
175            disabled,
176            identifier,
177            live,
178            aria_current,
179            shortcut,
180            shortcut_id,
181            has_popup,
182            orientation,
183            numeric_value,
184            min_numeric_value,
185            max_numeric_value,
186            numeric_step,
187        );
188        self.controls.extend(other.controls);
189        self.described_by.extend(other.described_by);
190        self.labelled_by.extend(other.labelled_by);
191        self.actions.extend(other.actions);
192        self.removed_actions.extend(other.removed_actions);
193        // Appended, so the ids already published for the existing entries keep
194        // pointing at the same handlers.
195        self.custom_actions.extend(other.custom_actions);
196        self.customize = match (self.customize.take(), other.customize) {
197            (Some(first), Some(second)) => Some(Box::new(move |builder| {
198                first(builder);
199                second(builder);
200            })),
201            (first, second) => second.or(first),
202        };
203    }
204}
205
206impl std::fmt::Debug for AccessibilityOverrides {
207    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208        f.debug_struct("AccessibilityOverrides")
209            .field("label", &self.label)
210            .field("description", &self.description)
211            .field("value", &self.value)
212            .field("role", &self.role)
213            .field("hidden", &self.hidden)
214            .field("disabled", &self.disabled)
215            .field("identifier", &self.identifier)
216            .field("shortcut", &self.shortcut)
217            .field("shortcut_id", &self.shortcut_id)
218            .field("controls_len", &self.controls.len())
219            .field("described_by_len", &self.described_by.len())
220            .field("labelled_by_len", &self.labelled_by.len())
221            .field("actions_len", &self.actions.len())
222            .field("removed_actions", &self.removed_actions)
223            .field("custom_actions_len", &self.custom_actions.len())
224            .finish()
225    }
226}
227
228impl AccessibilityOverrides {
229    /// Apply the override scalar / list fields onto a builder. Called by
230    /// the accessibility tree walker after the inner widget's
231    /// `accessibility(&self, builder)` runs and before the framework
232    /// finalizes the node.
233    pub(crate) fn apply(&self, b: &mut crate::accessibility::AccessNodeBuilder) {
234        use crate::accessibility::widget_id_to_node_id;
235
236        if let Some(ref p) = self.label {
237            b.set_name(p.get());
238        }
239        if let Some(ref p) = self.description {
240            b.set_description(p.get());
241        }
242        if let Some(ref p) = self.value {
243            b.set_value(p.get());
244        }
245        if let Some(role) = self.role {
246            b.set_role(role);
247        }
248        match self.hidden.as_ref().map(|p| p.get()) {
249            Some(true) => b.set_hidden(),
250            Some(false) => b.clear_hidden(),
251            None => {}
252        }
253        match self.disabled {
254            Some(true) => b.set_disabled(),
255            Some(false) => b.clear_disabled(),
256            None => {}
257        }
258        if let Some(ref s) = self.identifier {
259            b.set_author_id(s.clone());
260        }
261        for &id in &self.controls {
262            b.push_controlled(widget_id_to_node_id(id));
263        }
264        for &id in &self.described_by {
265            b.push_described_by(widget_id_to_node_id(id));
266        }
267        for &id in &self.labelled_by {
268            b.push_labelled_by(widget_id_to_node_id(id));
269        }
270        if let Some(live) = self.live {
271            b.set_live(live);
272        }
273        if let Some(c) = self.aria_current {
274            b.set_aria_current(c);
275        }
276        if let Some(ref s) = self.shortcut {
277            b.set_keyboard_shortcut(s.clone());
278        }
279        // `shortcut_id` resolution happens in the accessibility tree
280        // walker (where the `ShortcutRegistry` is reachable) — see
281        // `accessibility_emit_impl::build_accessibility_recursive`.
282        if let Some(p) = self.has_popup {
283            b.set_has_popup(p);
284        }
285        if let Some(o) = self.orientation {
286            b.set_orientation(o);
287        }
288        if let Some(v) = self.numeric_value {
289            b.set_numeric_value(v);
290        }
291        if let Some(v) = self.min_numeric_value {
292            b.set_min_numeric_value(v);
293        }
294        if let Some(v) = self.max_numeric_value {
295            b.set_max_numeric_value(v);
296        }
297        if let Some(v) = self.numeric_step {
298            b.set_numeric_value_step(v);
299        }
300        // Suppression first, then advertisement — so `access_remove_action`
301        // can prune what the widget emitted, but a subsequent
302        // `access_action(same_action, ...)` re-advertises with the
303        // override-installed handler.
304        for &a in &self.removed_actions {
305            b.remove_action(a);
306        }
307        for (action, _) in &self.actions {
308            b.add_action(*action);
309        }
310        if !self.custom_actions.is_empty() {
311            // Appended after the widget's own, which is the list rule every
312            // other override list follows: replacing it took a slider's "Reset
313            // to default" away the moment an application added an action of
314            // its own. The override entries keep their positional ids, which is
315            // what the dispatcher routes them by, so a widget publishing
316            // actions of its own numbers them clear of the low ones.
317            let mut custom: Vec<accesskit::CustomAction> = b.inner_mut().custom_actions().to_vec();
318            custom.extend(
319                self.custom_actions
320                    .iter()
321                    .enumerate()
322                    .map(|(i, (label, _))| accesskit::CustomAction {
323                        id: i as i32,
324                        description: label.get(),
325                    }),
326            );
327            b.set_custom_actions(custom);
328            // A node's custom actions are only reachable when it also
329            // advertises `Action::CustomAction`: an adapter reports the list
330            // through the supported-action gate, not through the list's
331            // emptiness (`accesskit_ios-0.2.0/src/node.rs:109` is the one that
332            // says so in code). Without this the whole vector is decoration.
333            b.add_action(accesskit::Action::CustomAction);
334        }
335        if let Some(ref f) = self.customize {
336            f(b);
337        }
338    }
339}
340
341// ---------------------------------------------------------------------------
342// HandlerSet — temporary storage before arena insertion
343// ---------------------------------------------------------------------------
344
345/// Type alias for a context-menu content factory.
346///
347/// The factory is invoked on every right-click that lands on a widget
348/// owning the factory (or on a descendant whose nearest ancestor with
349/// a factory is this one). It receives:
350///
351/// - `position`: pointer position in **window** coordinates — the factory
352///   runs straight off the right-click `PointerDown`, before the localizing
353///   handler dispatch, and the same point reaches every factory the walk
354///   tries, so subtract the widget's own origin before hit-testing. Useful
355///   when the menu's contents depend on *what* was right-clicked (a row in a
356///   list, a node in a tree, an item under a hit-test, …).
357/// - `ctx`: a full [`EventContext`], so the factory can read window
358///   state, query app state, send intents (e.g. for analytics), or
359///   update Signals before the menu mounts.
360///
361/// The same factory also answers the keyboard
362/// ([`ContextMenuTrigger::Keyboard`]) and an assistive technology's
363/// `ShowContextMenu` action. Neither carries a point, so `position` is then an
364/// anchor the framework picked on the widget the menu is about, not a place
365/// the user chose. [`ctx.context_menu_trigger()`](EventContext::context_menu_trigger)
366/// says which it is: act on the point (move a caret to it, pick the item under
367/// it) only for [`ContextMenuTrigger::Pointer`].
368///
369/// The factory returns:
370///
371/// - `Some(widget)` to mount `widget` as the menu overlay anchored at
372///   the factory-owning widget, placed at `position`.
373/// - `None` to **decline this right-click**. The framework continues
374///   walking up the parent chain looking for the next ancestor with a
375///   factory. This lets a widget conditionally suppress its own menu
376///   without uninstalling the factory.
377pub type ContextMenuFactory = Box<dyn Fn(Point, &mut EventContext) -> Option<Box<dyn Widget>>>;
378
379/// What asked for a context menu, as a [`ContextMenuFactory`] reads it from
380/// [`EventContext::context_menu_trigger`].
381///
382/// A factory is handed a point whatever opened the menu, and only a
383/// pointer's point is one the user chose. For the keyboard and for assistive
384/// technology the point is where the menu is drawn: a factory that treated it
385/// as a click moved the caret of a text field to the middle of the field, and
386/// the menu's Paste then wrote where the user had never been.
387#[non_exhaustive]
388#[derive(Debug, Clone, Copy, PartialEq, Eq)]
389pub enum ContextMenuTrigger {
390    /// A secondary click, or a hold with a finger or a pen: the point is
391    /// where the user pointed.
392    Pointer,
393    /// The Menu key, Shift+F10, or on macOS Ctrl+Shift+M, on the focused
394    /// widget.
395    Keyboard,
396    /// An assistive technology's
397    /// [`ShowContextMenu`](accesskit::Action::ShowContextMenu) action.
398    Accessibility,
399}
400
401impl ContextMenuTrigger {
402    /// Whether the factory's point is one the user pointed at.
403    pub const fn is_pointer(self) -> bool {
404        matches!(self, Self::Pointer)
405    }
406}
407
408/// Temporary storage for handlers and metadata accumulated via builder
409/// methods. Transferred to the `WidgetNode` during arena insertion.
410pub struct HandlerSet {
411    pub(crate) handlers: EventHandlers,
412    pub(crate) focusable: Option<bool>,
413    pub(crate) tab_index: Option<i32>,
414    pub(crate) cursor: Option<CursorIcon>,
415    pub(crate) clips_children: Option<bool>,
416    /// When `Some(..)`, declares the node a text-input surface and the OS
417    /// input method is enabled (with this purpose) while it is focused.
418    /// `None` leaves the node default (no OS IME). The platform reads the
419    /// focused node's descriptor at focus-change time. See [`crate::ime`].
420    pub(crate) ime: Option<crate::ime::ImeContext>,
421    /// When `Some(true)`, the widget node is invisible to pointer
422    /// hit-testing — events fall through to whatever sits behind it.
423    /// Used by the debug inspector's overlay widgets.
424    pub(crate) event_pass_through: Option<bool>,
425    /// When `Some(true)`, a press in this node's subtree must not arm a
426    /// drag/swipe on any ancestor above it (a *gesture dead zone*). See
427    /// [`super::arena::WidgetNode::gesture_dead_zone`].
428    pub(crate) gesture_dead_zone: Option<bool>,
429    /// When `Some(..)`, selects what a **hold** on this node's subtree means for
430    /// the tree-owned long-press route. See
431    /// [`super::arena::WidgetNode::long_press_role`].
432    pub(crate) long_press_role: Option<crate::widget_tree::touch_route::LongPressRole>,
433    /// When `Some(..)`, overrides what a direct pointer may do to this
434    /// node's subtree. See [`super::arena::WidgetNode::touch_action`].
435    pub(crate) touch_action: Option<TouchAction>,
436    /// When `Some(..)`, declares this node a pan surface. See
437    /// [`super::arena::WidgetNode::pan_claim`].
438    pub(crate) pan_claim: Option<PanClaim>,
439    pub(crate) overscroll_behavior: Option<crate::OverscrollBehavior>,
440    /// When `Some(..)`, overrides when a drag on this node may begin. See
441    /// [`super::arena::WidgetNode::drag_activation`].
442    pub(crate) drag_activation: Option<teksilo_tokens::DragActivation>,
443
444    /// How many simultaneous contacts this node's recognizers serve. See
445    /// [`super::arena::WidgetNode::multi_contact`].
446    pub(crate) multi_contact: Option<MultiContact>,
447    /// When `Some(true)` and this node holds keyboard focus, a `KeyDown`
448    /// bypasses shortcut resolution and is delivered straight to it (a
449    /// *keyboard capture* surface — terminals, game viewports). See
450    /// [`super::arena::WidgetNode::keyboard_capture`].
451    pub(crate) keyboard_capture: Option<bool>,
452    /// When `Some(true)`, this node and its WHOLE subtree are invisible
453    /// to pointer hit-testing (decorative overlays — count badges,
454    /// watermarks). See [`super::arena::WidgetNode::hit_transparent`].
455    pub(crate) hit_transparent: Option<bool>,
456    /// Per-node override of the *miss-only* slop this node may earn. Second
457    /// link of the precedence chain. See [`HandlerSet::hit_slop`].
458    pub(crate) hit_slop: Option<crate::pointer::hit_slop::HitSlop>,
459    /// When `Some(true)`, this node is excluded from BOTH hit-widening
460    /// mechanisms. Head of the precedence chain. See
461    /// [`HandlerSet::no_hit_slop`].
462    pub(crate) no_hit_slop: Option<bool>,
463    pub(crate) context_menu_factory: Option<ContextMenuFactory>,
464    /// User-bound signal that the framework writes whenever the
465    /// focused widget is a strict descendant of this node. See
466    /// [`HandlerSet::focus_within`].
467    pub(crate) focus_within: Option<crate::signal::Signal<bool>>,
468    /// User-bound signal that the framework writes whenever the
469    /// hovered widget is a strict descendant of this node. See
470    /// [`HandlerSet::hover_within`].
471    pub(crate) hover_within: Option<crate::signal::Signal<bool>>,
472    /// User-bound visibility binding (`bool` / `Signal<bool>` / `Prop<bool>`).
473    /// Applied at insertion via `WidgetTree::visible_when`, exactly like the
474    /// `ctx.visible_when(id, ..)` form, so `teksu!` can write `visible_when: sig`
475    /// as a plain widget property. See [`HandlerSet::visible_when`].
476    pub(crate) visible_when: Option<Prop<bool>>,
477    /// Builder-level accessibility overrides. Mirrored to
478    /// `WidgetNode::access_overrides` at insertion. Action callbacks
479    /// (`actions`, `custom_actions`) are dispatched by
480    /// `pointer_router.rs` when handling
481    /// `WidgetEvent::AccessAction`, in addition to the user's
482    /// `on_access_action` / `on_access_action_request` handlers — so
483    /// builder order doesn't matter.
484    pub(crate) access: Option<Box<AccessibilityOverrides>>,
485    /// Subtree visibility / merge mode. Mirrored to
486    /// `WidgetNode::access_subtree`.
487    pub(crate) access_subtree: Option<AccessSubtreeMode>,
488}
489
490impl HandlerSet {
491    /// Absorb `base`'s declarations wherever `self` is silent.
492    ///
493    /// `self` is the **later** declaration and wins on conflict, so this reads
494    /// left to right like the builder chain that produced the two sets. It is
495    /// Compose's `Modifier.then`, expressed on the value Teksilo already has.
496    ///
497    /// The accessibility block is **merged, not assigned**: an overrides block
498    /// carries lists (`controls`, `described_by`, `custom_actions`, ...) that a
499    /// plain assignment would drop. `WidgetArena` makes the same point at its
500    /// own merge site.
501    pub fn merge_under(&mut self, mut base: HandlerSet) {
502        macro_rules! take_if_empty {
503            ($($field:ident),* $(,)?) => {
504                $( if self.$field.is_none() { self.$field = base.$field.take(); } )*
505            };
506        }
507        take_if_empty!(
508            focusable,
509            tab_index,
510            cursor,
511            clips_children,
512            ime,
513            event_pass_through,
514            gesture_dead_zone,
515            long_press_role,
516            touch_action,
517            pan_claim,
518            overscroll_behavior,
519            drag_activation,
520            multi_contact,
521            keyboard_capture,
522            hit_transparent,
523            hit_slop,
524            no_hit_slop,
525            context_menu_factory,
526            focus_within,
527            hover_within,
528            visible_when,
529        );
530        if self.access_subtree.is_none() {
531            self.access_subtree = base.access_subtree.take();
532        }
533        // `base` is the earlier block, `self` the later one, and
534        // `merge_from` lets its argument win — so fold self INTO base and
535        // keep the result.
536        match (base.access.take(), self.access.take()) {
537            (Some(mut earlier), Some(later)) => {
538                earlier.merge_from(*later);
539                self.access = Some(earlier);
540            }
541            (earlier, later) => self.access = later.or(earlier),
542        }
543        self.handlers
544            .merge_under(std::mem::take(&mut base.handlers));
545    }
546
547    /// Create an empty handler set for use in `BuildContext::apply_self_handlers()`.
548    pub fn new() -> Self {
549        Self {
550            handlers: EventHandlers::new(),
551            focusable: None,
552            tab_index: None,
553            cursor: None,
554            clips_children: None,
555            ime: None,
556            event_pass_through: None,
557            gesture_dead_zone: None,
558            long_press_role: None,
559            drag_activation: None,
560            touch_action: None,
561            pan_claim: None,
562            overscroll_behavior: None,
563            multi_contact: None,
564            keyboard_capture: None,
565            hit_transparent: None,
566            hit_slop: None,
567            no_hit_slop: None,
568            context_menu_factory: None,
569            focus_within: None,
570            hover_within: None,
571            visible_when: None,
572            access: None,
573            access_subtree: None,
574        }
575    }
576
577    /// Get a `&mut` to the override block, lazily allocating it on first
578    /// access. Used by all `access_*` builder methods.
579    pub(crate) fn access_mut(&mut self) -> &mut AccessibilityOverrides {
580        self.access
581            .get_or_insert_with(|| Box::new(AccessibilityOverrides::default()))
582    }
583
584    // -- Builder methods (mirror WidgetWithHandlers) --
585
586    /// Set the on_tap handler. The closure receives a borrowed
587    /// [`TapEvent`] carrying the position in
588    /// widget-local coordinates, the finalising mouse button, and the
589    /// modifier state at that moment.
590    ///
591    /// Default acceptance is [`ButtonMask::PRIMARY`] — left-click only.
592    /// Use [`accept_tap_buttons`](Self::accept_tap_buttons) to widen
593    /// the set if you need right-click, middle-click, or auxiliary
594    /// buttons to fire this handler.
595    pub fn on_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
596        self.handlers.on_tap = Some(Box::new(f));
597        self
598    }
599
600    /// Set the on_double_tap handler. See [`on_tap`](Self::on_tap) for
601    /// the callback contract.
602    pub fn on_double_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
603        self.handlers.on_double_tap = Some(Box::new(f));
604        self
605    }
606
607    /// Set the on_triple_tap handler — fires on the third click within the
608    /// recognizer's window (the same `multi_tap_interval` / `multi_tap_slop`
609    /// the pointer's gesture profile gives double tap).
610    /// Runs independently of `on_double_tap` via cooperative gesture
611    /// recognizers (`GestureRecognizer::resets_on_peer_recognition`).
612    pub fn on_triple_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
613        self.handlers.on_triple_tap = Some(Box::new(f));
614        self
615    }
616
617    /// Set the on_long_press handler. The callback receives a borrowed
618    /// [`TapEvent`] whose modifiers are
619    /// captured from the held `Down` (since long-press recognises on a
620    /// timer before any `Up`).
621    pub fn on_long_press(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
622        self.handlers.on_long_press = Some(Box::new(f));
623        self
624    }
625
626    /// Restrict (or extend) the set of pointer buttons that fire
627    /// [`on_tap`](Self::on_tap). Default is [`ButtonMask::PRIMARY`]
628    /// (left-click only). Pass `ButtonMask::ALL` or
629    /// `ButtonMask::PRIMARY | ButtonMask::SECONDARY`, etc.
630    ///
631    /// The mask belongs to the `on_tap` set beside it. A node carries two
632    /// handler sets, the widget's own (from its `build`) and the one this
633    /// builder chain attaches, and each fires only on the buttons in its own
634    /// mask: widening the app's `on_tap` to the secondary button does not make
635    /// a right click run the widget's built-in click (a `Slider` jumping to
636    /// it, say). A mask set where no `on_tap` is attached beside it reaches
637    /// the widget's own instead, unless that one declared a mask of its own:
638    /// `Button::new(..).accept_tap_buttons(PRIMARY | SECONDARY)` is how a
639    /// right click activates a button.
640    pub fn accept_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
641        self.handlers.tap_buttons = Some(mask.into());
642        self
643    }
644
645    /// Restrict (or extend) the set of pointer buttons that fire
646    /// [`on_double_tap`](Self::on_double_tap). Default
647    /// [`ButtonMask::PRIMARY`].
648    ///
649    /// Scoped to the handler set it is attached with, the way
650    /// [`accept_tap_buttons`](Self::accept_tap_buttons) is.
651    pub fn accept_double_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
652        self.handlers.double_tap_buttons = Some(mask.into());
653        self
654    }
655
656    /// Restrict (or extend) the set of pointer buttons that fire
657    /// [`on_triple_tap`](Self::on_triple_tap). Default
658    /// [`ButtonMask::PRIMARY`].
659    ///
660    /// Scoped to the handler set it is attached with, the way
661    /// [`accept_tap_buttons`](Self::accept_tap_buttons) is.
662    pub fn accept_triple_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
663        self.handlers.triple_tap_buttons = Some(mask.into());
664        self
665    }
666
667    /// Restrict (or extend) the set of pointer buttons that fire
668    /// [`on_long_press`](Self::on_long_press). Default
669    /// [`ButtonMask::PRIMARY`].
670    ///
671    /// Scoped to the handler set it is attached with, the way
672    /// [`accept_tap_buttons`](Self::accept_tap_buttons) is.
673    pub fn accept_long_press_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
674        self.handlers.long_press_buttons = Some(mask.into());
675        self
676    }
677
678    /// Set the on_hover handler.
679    pub fn on_hover(mut self, f: impl FnMut(bool, &mut EventContext) + 'static) -> Self {
680        self.handlers.on_hover = Some(Box::new(f));
681        self
682    }
683
684    /// Set the on_key handler.
685    pub fn on_key(
686        mut self,
687        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
688    ) -> Self {
689        self.handlers.on_key = Some(Box::new(f));
690        self
691    }
692
693    /// Set the strict-ancestor key preview handler. Fires on every
694    /// ancestor of the focused widget (root → parent-of-target)
695    /// before the focused widget's `on_key` runs. Return
696    /// `EventResponse::Handled` to consume the event.
697    pub fn on_key_preview(
698        mut self,
699        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
700    ) -> Self {
701        self.handlers.on_key_preview = Some(Box::new(f));
702        self
703    }
704
705    /// Set the on_drag handler (gesture-based drag). The closure receives
706    /// a [`DragPhase`] — `Started`, then zero or more `Moved`, then
707    /// `Ended`.
708    pub fn on_drag(mut self, f: impl FnMut(DragPhase, &mut EventContext) + 'static) -> Self {
709        self.handlers.on_drag = Some(Box::new(f));
710        self
711    }
712
713    /// Set the on_swipe handler. Fires once per swipe with the direction
714    /// and velocity (pixels/second).
715    pub fn on_swipe(
716        mut self,
717        f: impl FnMut(SwipeDirection, f32, &mut EventContext) + 'static,
718    ) -> Self {
719        self.handlers.on_swipe = Some(Box::new(f));
720        self
721    }
722
723    /// Set the on_pinch handler. On desktop the phases are produced from
724    /// OS trackpad gestures (winit `PinchGesture` / `RotationGesture`).
725    pub fn on_pinch(mut self, f: impl FnMut(PinchPhase, &mut EventContext) + 'static) -> Self {
726        self.handlers.on_pinch = Some(Box::new(f));
727        self
728    }
729
730    /// Set the on_focus handler. `f` is called with `true` on focus gain and
731    /// `false` on focus loss.
732    ///
733    /// **WCAG 3.2.1 (On Focus).** Use this only to update *local* visual or
734    /// reactive state. Do NOT open a window, navigate, submit, or otherwise
735    /// change context from here: a context change triggered merely by a control
736    /// receiving focus is a Success Criterion 3.2.1 failure — keyboard users
737    /// tabbing through the UI would trigger it unexpectedly. (A debug-only guard
738    /// warns if `ctx.open_window(...)` / `ctx.focus_window(...)` is called from
739    /// inside focus dispatch.)
740    pub fn on_focus(mut self, f: impl FnMut(bool, &mut EventContext) + 'static) -> Self {
741        self.handlers.on_focus = Some(Box::new(f));
742        self
743    }
744
745    /// Set the on_pointer_event handler (low-level escape hatch).
746    pub fn on_pointer_event(
747        mut self,
748        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
749    ) -> Self {
750        self.handlers.on_pointer_event = Some(Box::new(f));
751        self
752    }
753
754    /// Set the on_scroll handler.
755    pub fn on_scroll(
756        mut self,
757        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
758    ) -> Self {
759        self.handlers.on_scroll = Some(Box::new(f));
760        self
761    }
762
763    /// Set the on_access_action handler.
764    pub fn on_access_action(
765        mut self,
766        f: impl FnMut(accesskit::Action, &mut EventContext) -> EventResponse + 'static,
767    ) -> Self {
768        self.handlers.on_access_action = Some(Box::new(f));
769        self
770    }
771
772    /// Set the full AccessKit action-request handler. Receives the
773    /// action, target NodeId (may be a synthetic widget-emitted
774    /// child), and optional `ActionData` payload (e.g.
775    /// `SetTextSelection(TextSelection)` or `Value(Box<str>)`).
776    ///
777    /// Layered with [`on_access_action`](Self::on_access_action) rather than
778    /// replacing it: both fire for the same dispatched action, and it counts as
779    /// handled if either says so.
780    pub fn on_access_action_request(
781        mut self,
782        f: impl FnMut(
783            accesskit::Action,
784            accesskit::NodeId,
785            Option<accesskit::ActionData>,
786            &mut EventContext,
787        ) -> EventResponse
788        + 'static,
789    ) -> Self {
790        self.handlers.on_access_action_request = Some(Box::new(f));
791        self
792    }
793
794    /// Set the focusable flag.
795    pub fn focusable(mut self, focusable: bool) -> Self {
796        self.focusable = Some(focusable);
797        self
798    }
799
800    /// Set the cursor icon.
801    pub fn cursor(mut self, cursor: CursorIcon) -> Self {
802        self.cursor = Some(cursor);
803        self
804    }
805
806    /// Set the clips_children flag.
807    pub fn clips_children(mut self, clips: bool) -> Self {
808        self.clips_children = Some(clips);
809        self
810    }
811
812    /// Declare this node a text-input surface, enabling the OS input method
813    /// (with `ctx`'s purpose) while it is focused. Leaving it unset (the
814    /// default) means no OS IME. The platform reads the focused node's
815    /// descriptor at focus-change time. See [`crate::ime`].
816    pub fn ime_input(mut self, ctx: crate::ime::ImeContext) -> Self {
817        self.ime = Some(ctx);
818        self
819    }
820
821    /// Make the widget invisible to pointer hit-testing. With
822    /// `pass_through = true`, pointer events traverse this node as if
823    /// it were not there — useful for purely decorative overlays that
824    /// must not absorb clicks (the debug inspector's `HighlightLayer`
825    /// and `HoverProbe` use this).
826    pub fn event_pass_through(mut self, pass_through: bool) -> Self {
827        self.event_pass_through = Some(pass_through);
828        self
829    }
830
831    /// Mark this widget's subtree a **gesture dead zone**: a pointer press
832    /// inside it must not arm a drag/swipe recognizer on any ancestor above
833    /// it. Use to let interactive controls (buttons, a `⋮` menu) sit inside a
834    /// draggable / swipeable container (a dock-panel header, a card, a list
835    /// row) without a few px of click jitter starting the ancestor's drag.
836    /// The container's own drag still works everywhere else. Honored by
837    /// `PointerSequence` member enrolment; see the `DeadZone` wrapper widget.
838    pub fn gesture_dead_zone(mut self, dead_zone: bool) -> Self {
839        self.gesture_dead_zone = Some(dead_zone);
840        self
841    }
842
843    /// Select what a **hold** on this widget's subtree means, for the
844    /// tree-owned long-press route.
845    ///
846    /// Only ever consulted for a pointer that cannot hover, and only where the
847    /// widget installs no `on_long_press` of its own — that always wins. See
848    /// [`crate::widget_tree::touch_route`] for the precedence and for what each
849    /// variant selects.
850    pub fn long_press_role(mut self, role: crate::widget_tree::touch_route::LongPressRole) -> Self {
851        self.long_press_role = Some(role);
852        self
853    }
854
855    /// Override what a direct pointer (touch, pen) is permitted to do to
856    /// this widget's subtree — the CSS `touch-action` model. Intersected
857    /// with every ancestor's declaration on the way down; a mouse never
858    /// consults this. See [`super::arena::WidgetNode::touch_action`].
859    pub fn touch_action(mut self, action: TouchAction) -> Self {
860        self.touch_action = Some(action);
861        self
862    }
863
864    /// Declare this widget a **pan surface** on `axes` for direct pointers,
865    /// with kinetic (fling/settle) hand-off on release. Sugar for
866    /// `.pan_claim(PanClaim { axes, devices: PointerKindMask::DIRECT, kinetic: true })`
867    /// — the shape every scrollable declares. See
868    /// [`super::arena::WidgetNode::pan_claim`].
869    pub fn scroll_container(mut self, axes: PanAxes) -> Self {
870        self.pan_claim = Some(PanClaim {
871            axes,
872            devices: teksilo_tokens::PointerKindMask::DIRECT,
873            kinetic: true,
874        });
875        self
876    }
877
878    /// Declare this widget a pan surface with an explicit [`PanClaim`] —
879    /// the escape hatch behind [`scroll_container`](Self::scroll_container)
880    /// for a claim that isn't kinetic, or that widens/narrows the device
881    /// mask. See [`super::arena::WidgetNode::pan_claim`].
882    pub fn pan_claim(mut self, claim: PanClaim) -> Self {
883        self.pan_claim = Some(claim);
884        self
885    }
886
887    /// Whether this widget absorbs a scroll it cannot use
888    /// ([`Contain`](crate::OverscrollBehavior::Contain)) or lets it chain
889    /// outward at its boundary ([`Chain`](crate::OverscrollBehavior::Chain),
890    /// the default). The CSS `overscroll-behavior` model, read by the pan
891    /// claimant chain. See [`super::arena::WidgetNode::overscroll_behavior`].
892    pub fn overscroll_behavior(mut self, behavior: crate::OverscrollBehavior) -> Self {
893        self.overscroll_behavior = Some(behavior);
894        self
895    }
896
897    /// When a drag on this widget may begin relative to the press that starts
898    /// it.
899    ///
900    /// [`DragActivation::Auto`](teksilo_tokens::DragActivation::Auto) — the
901    /// default — is `Immediate` for a precise pointer, which is exactly
902    /// today's behaviour, and `AfterLongPress` for a coarse pointer whose axis
903    /// a pan surface has already claimed. Declare
904    /// [`Immediate`](teksilo_tokens::DragActivation::Immediate) for a control
905    /// whose drag *is* the interaction (a slider thumb, a splitter handle) and
906    /// [`AfterLongPress`](teksilo_tokens::DragActivation::AfterLongPress) for
907    /// one that must not steal a scroll (a reorderable list row). See
908    /// [`super::arena::WidgetNode::drag_activation`].
909    pub fn drag_activation(mut self, activation: teksilo_tokens::DragActivation) -> Self {
910        self.drag_activation = Some(activation);
911        self
912    }
913
914    /// How many simultaneous contacts this node serves. Default
915    /// [`MultiContact::First`]. See
916    /// [`super::arena::WidgetNode::multi_contact`].
917    pub fn multi_contact(mut self, policy: MultiContact) -> Self {
918        self.multi_contact = Some(policy);
919        self
920    }
921
922    /// Mark this widget a **keyboard capture** surface: while it holds
923    /// focus, every `KeyDown` is delivered straight to its `on_key`
924    /// handler, bypassing shortcut → intent → action resolution. Use for
925    /// a terminal emulator that must forward `Ctrl+C` / `Ctrl+W` /
926    /// `Alt+<letter>` to a child process instead of triggering the host
927    /// app's shortcuts, a game viewport, or a modal text surface.
928    ///
929    /// # The escape contract
930    ///
931    /// **`Ctrl+Tab` / `Ctrl+Shift+Tab` are reserved and always move focus
932    /// out.** The dispatcher cycles focus on that chord before the capture
933    /// node is consulted, so a capture surface cannot become a keyboard trap
934    /// (WCAG 2.1.2) however greedily its `on_key` behaves. Do not bind them.
935    ///
936    /// Nothing else is reserved. In particular Escape is **not**: overlay
937    /// back-navigation runs first only while an overlay is actually open, so
938    /// a focused capture surface with no overlay above it does receive
939    /// Escape and may consume it. See
940    /// [`super::arena::WidgetNode::keyboard_capture`].
941    pub fn keyboard_capture(mut self, capture: bool) -> Self {
942        self.keyboard_capture = Some(capture);
943        self
944    }
945
946    /// Make this widget AND its whole subtree invisible to pointer
947    /// hit-testing. Stronger than [`event_pass_through`](Self::event_pass_through):
948    /// that one keeps descendants hittable, this one excludes them too.
949    /// For purely decorative composite overlays (a count badge over a
950    /// button, a watermark) whose own children would otherwise swallow
951    /// the click meant for the control underneath.
952    pub fn hit_transparent(mut self, transparent: bool) -> Self {
953        self.hit_transparent = Some(transparent);
954        self
955    }
956
957    /// Override how far a *missed* press may be re-attributed to this node, and
958    /// up to what size it is topped up.
959    ///
960    /// Second link of the precedence chain: `no_hit_slop` beats this, this
961    /// beats the widget's own `Widget::hit_slop`, and that beats the density
962    /// default. Use it for a control the framework cannot recognise as small —
963    /// a hand-drawn handle, a custom mark in a chart — or to raise `up_to`
964    /// beyond the density's `target_size` for one especially fiddly target.
965    ///
966    /// Hit-only: no layout moves and nothing repaints differently.
967    pub fn hit_slop(mut self, slop: crate::pointer::hit_slop::HitSlop) -> Self {
968        self.hit_slop = Some(slop);
969        self
970    }
971
972    /// Take this node out of **both** hit-widening mechanisms: it earns no slop
973    /// outset, and its `Widget::hit_outset` is ignored.
974    ///
975    /// Head of the precedence chain, and the right switch for a node whose
976    /// exact rectangle is the contract — a surface hosting foreign content
977    /// (a `WebView`, an embedded engine) that must receive precisely the
978    /// presses that land on it and no others, or a modal scrim, which must
979    /// never re-attribute a press to something under it.
980    ///
981    /// Per-node, not per-subtree: descendants may still widen. To take a whole
982    /// subtree out of hit-testing use
983    /// [`hit_transparent`](Self::hit_transparent).
984    pub fn no_hit_slop(mut self) -> Self {
985        self.no_hit_slop = Some(true);
986        self
987    }
988
989    /// Bind a user-owned `Signal<bool>` that the framework will set
990    /// to `true` whenever the focused widget is a *strict descendant*
991    /// of this node, and `false` otherwise. Useful for unified focus
992    /// halos around composite widgets (a chat composer that highlights
993    /// when its `RichTextEditor` or "Send" button is focused, a
994    /// `Panel` wrapping a `SpinBox`, etc).
995    ///
996    /// Strict-ancestors only — a widget that *is* itself focused does
997    /// not also see its own `focus_within` signal flipped to `true`.
998    /// Combine with `on_focus` if you want both behaviours.
999    pub fn focus_within(mut self, signal: crate::signal::Signal<bool>) -> Self {
1000        self.focus_within = Some(signal);
1001        self
1002    }
1003
1004    /// Bind a user-owned `Signal<bool>` that the framework will set
1005    /// to `true` whenever the hovered widget is a *strict descendant*
1006    /// of this node. Symmetric to [`focus_within`](Self::focus_within).
1007    pub fn hover_within(mut self, signal: crate::signal::Signal<bool>) -> Self {
1008        self.hover_within = Some(signal);
1009        self
1010    }
1011
1012    /// Bind this node's visibility to a `bool` / `Signal<bool>` / `Prop<bool>`.
1013    /// A bound value shows/hides the node reactively (registered at
1014    /// `Relayout`). Equivalent to `ctx.visible_when(id, ..)`; exposed as a
1015    /// builder method so `teksu!` can write `visible_when: sig` as a property.
1016    pub fn visible_when(mut self, state: impl Into<Prop<bool>>) -> Self {
1017        self.visible_when = Some(state.into());
1018        self
1019    }
1020
1021    /// Set a context-menu factory. See [`ContextMenuFactory`] for the
1022    /// full contract: the closure receives the click position
1023    /// (window-local) and a full [`EventContext`], and returns
1024    /// `Some(menu)` to mount or `None` to decline (falling through to
1025    /// the nearest ancestor with a factory).
1026    pub fn context_menu(
1027        mut self,
1028        factory: impl Fn(Point, &mut EventContext) -> Option<Box<dyn Widget>> + 'static,
1029    ) -> Self {
1030        self.context_menu_factory = Some(Box::new(factory));
1031        self
1032    }
1033
1034    /// Set the drag hover handler. Called when a drag payload hovers over this widget.
1035    /// Return `DropFeedback` to indicate acceptance and visual feedback.
1036    pub fn on_drag_hover(
1037        mut self,
1038        f: impl FnMut(
1039            &crate::drag_payload::DragPayload,
1040            teksilo_canvas::Point,
1041            &mut EventContext,
1042        ) -> crate::drag_state::DropFeedback
1043        + 'static,
1044    ) -> Self {
1045        self.handlers.on_drag_hover = Some(Box::new(f));
1046        self
1047    }
1048
1049    /// Set the drag-leave handler. Fires when a drag that was over this
1050    /// widget moves to another target, completes (drop on any target), or
1051    /// is cancelled. Widgets that stash transient feedback state in
1052    /// `on_drag_hover` must clear it here.
1053    pub fn on_drag_leave(mut self, f: impl FnMut(&mut EventContext) + 'static) -> Self {
1054        self.handlers.on_drag_leave = Some(Box::new(f));
1055        self
1056    }
1057
1058    /// Set the pointer-cancel handler. Fires when a pointer interaction on
1059    /// this widget is taken away — the window lost focus, a modal opened, the
1060    /// subtree was parked, a peer won the arbitration.
1061    ///
1062    /// **Terminal**: no `PointerUp` follows. Release anything the press
1063    /// latched; the framework releases its own state but never widget-owned
1064    /// state.
1065    pub fn on_pointer_cancel(
1066        mut self,
1067        f: impl FnMut(&crate::pointer::PointerInfo, crate::pointer::CancelReason, &mut EventContext)
1068        + 'static,
1069    ) -> Self {
1070        self.handlers.on_pointer_cancel = Some(Box::new(f));
1071        self
1072    }
1073
1074    /// Set the per-frame drag-tick handler. Fires once per frame while a
1075    /// drag is active and this widget is the current drop target. The
1076    /// closure receives the current pointer position in widget-local
1077    /// coordinates. Use for behaviours that must keep running even when
1078    /// the pointer is stationary — viewport-edge auto-scroll and
1079    /// spring-loaded folders.
1080    pub fn on_drag_tick(
1081        mut self,
1082        f: impl FnMut(teksilo_canvas::Point, &mut EventContext) + 'static,
1083    ) -> Self {
1084        self.handlers.on_drag_tick = Some(Box::new(f));
1085        self
1086    }
1087
1088    /// Set the drop handler. Called when a payload is dropped on this widget.
1089    /// Return `true` if the drop was accepted.
1090    pub fn on_drop(
1091        mut self,
1092        f: impl FnMut(
1093            crate::drag_payload::DragPayload,
1094            teksilo_canvas::Point,
1095            &mut EventContext,
1096        ) -> bool
1097        + 'static,
1098    ) -> Self {
1099        self.handlers.on_drop = Some(Box::new(f));
1100        self
1101    }
1102
1103    /// Set the drag-ended handler on a drag **source**. Fires when a drag
1104    /// this widget started ends — dropped on an in-app target, exported to
1105    /// another application via the OS (copy / move), or cancelled. Use it to
1106    /// react to the outcome, e.g. remove the dragged item on a
1107    /// [`DropOutcome::OsMove`](crate::drag_payload::DropOutcome::OsMove).
1108    pub fn on_drag_ended(
1109        mut self,
1110        f: impl FnMut(crate::drag_payload::DropOutcome, &mut EventContext) + 'static,
1111    ) -> Self {
1112        self.handlers.on_drag_ended = Some(Box::new(f));
1113        self
1114    }
1115
1116    /// Advertise a named custom action on this node and register its callback.
1117    ///
1118    /// The [`WidgetWithHandlers`] twin
1119    /// ([`access_custom_action`](WidgetWithHandlers::access_custom_action)) is
1120    /// how an *application* adds one from outside. This is how a **widget**
1121    /// adds one to a node it builds itself — a virtualized row, a rail item,
1122    /// a header cell — where there is no builder chain to hang it on because
1123    /// the node is reached through
1124    /// [`BuildContext::apply_handlers`](crate::build_context::BuildContext::apply_handlers).
1125    ///
1126    /// Actions are dispatched by declaration order, so a node's callbacks and
1127    /// its advertised list cannot drift apart.
1128    pub fn access_custom_action<F>(mut self, label: impl Into<Prop<String>>, handler: F) -> Self
1129    where
1130        F: FnMut(&mut EventContext) + 'static,
1131    {
1132        self.access_mut()
1133            .custom_actions
1134            .push((label.into(), Box::new(handler)));
1135        self
1136    }
1137
1138    /// Finish this node's accessibility with full access to its builder, after
1139    /// the widget's own `accessibility()` and every typed override.
1140    ///
1141    /// The [`WidgetWithHandlers`] twin
1142    /// ([`access_customize`](WidgetWithHandlers::access_customize)) is the
1143    /// application's; this one is for a **widget** writing onto a node it
1144    /// reaches through
1145    /// [`BuildContext::apply_handlers`](crate::build_context::BuildContext::apply_handlers),
1146    /// such as a wrapper handing its popup state to the control it wraps.
1147    /// Chained after any customization the node already carries.
1148    pub fn access_customize<F>(mut self, f: F) -> Self
1149    where
1150        F: Fn(&mut crate::accessibility::AccessNodeBuilder) + 'static,
1151    {
1152        self.access_mut().customize = Some(Box::new(f));
1153        self
1154    }
1155}
1156
1157impl Default for HandlerSet {
1158    fn default() -> Self {
1159        Self::new()
1160    }
1161}
1162
1163impl std::fmt::Debug for HandlerSet {
1164    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1165        f.debug_struct("HandlerSet")
1166            .field("handlers", &self.handlers)
1167            .field("focusable", &self.focusable)
1168            .field("tab_index", &self.tab_index)
1169            .field("cursor", &self.cursor)
1170            .finish()
1171    }
1172}
1173
1174// ---------------------------------------------------------------------------
1175// WidgetWithHandlers<W> — wrapper storing widget + accumulated handlers
1176// ---------------------------------------------------------------------------
1177
1178/// A widget wrapped with attached event handlers and framework metadata.
1179/// Created by calling builder methods from `WidgetBuilder` on any widget.
1180pub struct WidgetWithHandlers<W: Widget> {
1181    pub(crate) widget: W,
1182    pub(crate) handler_set: HandlerSet,
1183    /// Whether [`take_handler_set`](Self::take_handler_set) has run: the
1184    /// handlers (and cursor, focusability, ...) now live on the arena node,
1185    /// and `handler_set` is the empty default left behind. Only `Debug` reads
1186    /// it, so a mounted wrapper does not print an empty set as if it were the
1187    /// widget's declaration.
1188    handlers_taken: bool,
1189}
1190
1191impl<W: Widget> WidgetWithHandlers<W> {
1192    fn new(widget: W) -> Self {
1193        Self {
1194            widget,
1195            handler_set: HandlerSet::new(),
1196            handlers_taken: false,
1197        }
1198    }
1199
1200    /// Take the handler set out, leaving defaults.
1201    pub(crate) fn take_handler_set(&mut self) -> HandlerSet {
1202        self.handlers_taken = true;
1203        std::mem::take(&mut self.handler_set)
1204    }
1205
1206    // -- Gesture handlers --
1207
1208    pub fn on_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
1209        self.handler_set.handlers.on_tap = Some(Box::new(f));
1210        self
1211    }
1212
1213    pub fn on_double_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
1214        self.handler_set.handlers.on_double_tap = Some(Box::new(f));
1215        self
1216    }
1217
1218    pub fn on_triple_tap(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
1219        self.handler_set.handlers.on_triple_tap = Some(Box::new(f));
1220        self
1221    }
1222
1223    pub fn on_long_press(mut self, f: impl FnMut(&TapEvent, &mut EventContext) + 'static) -> Self {
1224        self.handler_set.handlers.on_long_press = Some(Box::new(f));
1225        self
1226    }
1227
1228    /// Restrict (or extend) the set of pointer buttons that fire
1229    /// `on_tap`. Default is [`ButtonMask::PRIMARY`].
1230    ///
1231    /// The mask belongs to the `on_tap` set beside it. A node carries two
1232    /// handler sets, the widget's own (from its `build`) and the one this
1233    /// builder chain attaches, and each fires only on the buttons in its own
1234    /// mask: widening the app's `on_tap` to the secondary button does not make
1235    /// a right click run the widget's built-in click (a `Slider` jumping to
1236    /// it, say). A mask set where no `on_tap` is attached beside it reaches
1237    /// the widget's own instead, unless that one declared a mask of its own:
1238    /// `Button::new(..).accept_tap_buttons(PRIMARY | SECONDARY)` is how a
1239    /// right click activates a button.
1240    pub fn accept_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
1241        self.handler_set.handlers.tap_buttons = Some(mask.into());
1242        self
1243    }
1244
1245    /// Restrict (or extend) the set of pointer buttons that fire
1246    /// `on_double_tap`. Default [`ButtonMask::PRIMARY`].
1247    ///
1248    /// Scoped to the handler set it is attached with, the way
1249    /// [`accept_tap_buttons`](Self::accept_tap_buttons) is.
1250    pub fn accept_double_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
1251        self.handler_set.handlers.double_tap_buttons = Some(mask.into());
1252        self
1253    }
1254
1255    /// Restrict (or extend) the set of pointer buttons that fire
1256    /// `on_triple_tap`. Default [`ButtonMask::PRIMARY`].
1257    ///
1258    /// Scoped to the handler set it is attached with, the way
1259    /// [`accept_tap_buttons`](Self::accept_tap_buttons) is.
1260    pub fn accept_triple_tap_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
1261        self.handler_set.handlers.triple_tap_buttons = Some(mask.into());
1262        self
1263    }
1264
1265    /// Restrict (or extend) the set of pointer buttons that fire
1266    /// `on_long_press`. Default [`ButtonMask::PRIMARY`].
1267    ///
1268    /// Scoped to the handler set it is attached with, the way
1269    /// [`accept_tap_buttons`](Self::accept_tap_buttons) is.
1270    pub fn accept_long_press_buttons(mut self, mask: impl Into<ButtonMask>) -> Self {
1271        self.handler_set.handlers.long_press_buttons = Some(mask.into());
1272        self
1273    }
1274
1275    pub fn on_drag(mut self, f: impl FnMut(DragPhase, &mut EventContext) + 'static) -> Self {
1276        self.handler_set.handlers.on_drag = Some(Box::new(f));
1277        self
1278    }
1279
1280    pub fn on_swipe(
1281        mut self,
1282        f: impl FnMut(SwipeDirection, f32, &mut EventContext) + 'static,
1283    ) -> Self {
1284        self.handler_set.handlers.on_swipe = Some(Box::new(f));
1285        self
1286    }
1287
1288    pub fn on_pinch(mut self, f: impl FnMut(PinchPhase, &mut EventContext) + 'static) -> Self {
1289        self.handler_set.handlers.on_pinch = Some(Box::new(f));
1290        self
1291    }
1292
1293    // -- Focus and keyboard --
1294
1295    pub fn on_focus(mut self, f: impl FnMut(bool, &mut EventContext) + 'static) -> Self {
1296        self.handler_set.handlers.on_focus = Some(Box::new(f));
1297        self
1298    }
1299
1300    pub fn on_key(
1301        mut self,
1302        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
1303    ) -> Self {
1304        self.handler_set.handlers.on_key = Some(Box::new(f));
1305        self
1306    }
1307
1308    /// Set the strict-ancestor key preview handler. See
1309    /// [`HandlerSet::on_key_preview`].
1310    pub fn on_key_preview(
1311        mut self,
1312        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
1313    ) -> Self {
1314        self.handler_set.handlers.on_key_preview = Some(Box::new(f));
1315        self
1316    }
1317
1318    pub fn focusable(mut self, focusable: bool) -> Self {
1319        self.handler_set.focusable = Some(focusable);
1320        self
1321    }
1322
1323    pub fn tab_index(mut self, index: i32) -> Self {
1324        self.handler_set.tab_index = Some(index);
1325        self
1326    }
1327
1328    // -- Pointer (low-level escape hatch) --
1329
1330    pub fn on_pointer_event(
1331        mut self,
1332        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
1333    ) -> Self {
1334        self.handler_set.handlers.on_pointer_event = Some(Box::new(f));
1335        self
1336    }
1337
1338    pub fn on_hover(mut self, f: impl FnMut(bool, &mut EventContext) + 'static) -> Self {
1339        self.handler_set.handlers.on_hover = Some(Box::new(f));
1340        self
1341    }
1342
1343    pub fn cursor(mut self, cursor: CursorIcon) -> Self {
1344        self.handler_set.cursor = Some(cursor);
1345        self
1346    }
1347
1348    // -- Scroll --
1349
1350    pub fn on_scroll(
1351        mut self,
1352        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
1353    ) -> Self {
1354        self.handler_set.handlers.on_scroll = Some(Box::new(f));
1355        self
1356    }
1357
1358    // -- Accessibility actions --
1359
1360    pub fn on_access_action(
1361        mut self,
1362        f: impl FnMut(accesskit::Action, &mut EventContext) -> EventResponse + 'static,
1363    ) -> Self {
1364        self.handler_set.handlers.on_access_action = Some(Box::new(f));
1365        self
1366    }
1367
1368    pub fn on_access_action_request(
1369        mut self,
1370        f: impl FnMut(
1371            accesskit::Action,
1372            accesskit::NodeId,
1373            Option<accesskit::ActionData>,
1374            &mut EventContext,
1375        ) -> EventResponse
1376        + 'static,
1377    ) -> Self {
1378        self.handler_set.handlers.on_access_action_request = Some(Box::new(f));
1379        self
1380    }
1381
1382    // -- Framework-level properties --
1383
1384    pub fn clips_children(mut self, clips: bool) -> Self {
1385        self.handler_set.clips_children = Some(clips);
1386        self
1387    }
1388
1389    /// `WidgetBuilder::clips_children_on`'s inherent twin.
1390    ///
1391    /// The trait spells it `clips_children_on` because `clips_children` is
1392    /// already taken on `Widget` as a `&self` query. Without this twin the
1393    /// trait method applies to an already-wrapped widget and wraps it a second
1394    /// time; `Widget::take_handler_set` now merges through that, so it is a
1395    /// wasted node rather than lost behaviour, but the twin avoids both.
1396    pub fn clips_children_on(self, clips: bool) -> Self {
1397        self.clips_children(clips)
1398    }
1399
1400    /// Declare this node a text-input surface, enabling the OS input method
1401    /// (with `ctx`'s purpose) while it is focused. See [`crate::ime`].
1402    pub fn ime_input(mut self, ctx: crate::ime::ImeContext) -> Self {
1403        self.handler_set.ime = Some(ctx);
1404        self
1405    }
1406
1407    /// Make the widget invisible to pointer hit-testing. See
1408    /// [`HandlerSet::event_pass_through`].
1409    pub fn event_pass_through(mut self, pass_through: bool) -> Self {
1410        self.handler_set.event_pass_through = Some(pass_through);
1411        self
1412    }
1413
1414    /// Mark this widget's subtree a gesture dead zone. See
1415    /// [`HandlerSet::gesture_dead_zone`].
1416    pub fn gesture_dead_zone(mut self, dead_zone: bool) -> Self {
1417        self.handler_set.gesture_dead_zone = Some(dead_zone);
1418        self
1419    }
1420
1421    /// Select what a hold on this widget's subtree means. See
1422    /// [`HandlerSet::long_press_role`].
1423    pub fn long_press_role(mut self, role: crate::widget_tree::touch_route::LongPressRole) -> Self {
1424        self.handler_set.long_press_role = Some(role);
1425        self
1426    }
1427
1428    /// Override what a direct pointer may do to this widget's subtree. See
1429    /// [`HandlerSet::touch_action`].
1430    pub fn touch_action(mut self, action: TouchAction) -> Self {
1431        self.handler_set.touch_action = Some(action);
1432        self
1433    }
1434
1435    /// Declare this widget a pan surface on `axes`, kinetic, direct pointers
1436    /// only. See [`HandlerSet::scroll_container`].
1437    pub fn scroll_container(mut self, axes: PanAxes) -> Self {
1438        self.handler_set.pan_claim = Some(PanClaim {
1439            axes,
1440            devices: teksilo_tokens::PointerKindMask::DIRECT,
1441            kinetic: true,
1442        });
1443        self
1444    }
1445
1446    /// Declare this widget a pan surface with an explicit [`PanClaim`]. See
1447    /// [`HandlerSet::pan_claim`].
1448    pub fn pan_claim(mut self, claim: PanClaim) -> Self {
1449        self.handler_set.pan_claim = Some(claim);
1450        self
1451    }
1452
1453    /// Whether this widget absorbs a boundary scroll or chains it outward. See
1454    /// [`HandlerSet::overscroll_behavior`].
1455    pub fn overscroll_behavior(mut self, behavior: crate::OverscrollBehavior) -> Self {
1456        self.handler_set.overscroll_behavior = Some(behavior);
1457        self
1458    }
1459
1460    /// When a drag on this widget may begin. See
1461    /// [`HandlerSet::drag_activation`].
1462    pub fn drag_activation(mut self, activation: teksilo_tokens::DragActivation) -> Self {
1463        self.handler_set.drag_activation = Some(activation);
1464        self
1465    }
1466
1467    /// [`HandlerSet::multi_contact`].
1468    pub fn multi_contact(mut self, policy: MultiContact) -> Self {
1469        self.handler_set.multi_contact = Some(policy);
1470        self
1471    }
1472
1473    /// Mark this widget a keyboard capture surface: while focused, every
1474    /// `KeyDown` bypasses shortcut resolution and reaches its `on_key`
1475    /// handler (terminals, game viewports). See
1476    /// [`HandlerSet::keyboard_capture`].
1477    pub fn keyboard_capture(mut self, capture: bool) -> Self {
1478        self.handler_set.keyboard_capture = Some(capture);
1479        self
1480    }
1481
1482    /// Make this widget and its whole subtree invisible to pointer
1483    /// hit-testing. See [`HandlerSet::hit_transparent`].
1484    pub fn hit_transparent(mut self, transparent: bool) -> Self {
1485        self.handler_set.hit_transparent = Some(transparent);
1486        self
1487    }
1488
1489    /// Override the miss-only hit slop for this node. See
1490    /// [`HandlerSet::hit_slop`].
1491    pub fn hit_slop(mut self, slop: crate::pointer::hit_slop::HitSlop) -> Self {
1492        self.handler_set.hit_slop = Some(slop);
1493        self
1494    }
1495
1496    /// Take this node out of both hit-widening mechanisms. See
1497    /// [`HandlerSet::no_hit_slop`].
1498    pub fn no_hit_slop(mut self) -> Self {
1499        self.handler_set.no_hit_slop = Some(true);
1500        self
1501    }
1502
1503    /// Set a context-menu factory. See
1504    /// [`HandlerSet::context_menu`] for the full contract.
1505    pub fn context_menu(
1506        mut self,
1507        factory: impl Fn(Point, &mut EventContext) -> Option<Box<dyn Widget>> + 'static,
1508    ) -> Self {
1509        self.handler_set.context_menu_factory = Some(Box::new(factory));
1510        self
1511    }
1512
1513    /// Bind a `Signal<bool>` the framework writes when a strict
1514    /// descendant has focus. See [`HandlerSet::focus_within`].
1515    pub fn focus_within(mut self, signal: crate::signal::Signal<bool>) -> Self {
1516        self.handler_set.focus_within = Some(signal);
1517        self
1518    }
1519
1520    /// Bind a `Signal<bool>` the framework writes when a strict
1521    /// descendant is hovered. See [`HandlerSet::hover_within`].
1522    pub fn hover_within(mut self, signal: crate::signal::Signal<bool>) -> Self {
1523        self.handler_set.hover_within = Some(signal);
1524        self
1525    }
1526
1527    /// Bind this node's visibility. See [`HandlerSet::visible_when`].
1528    pub fn visible_when(mut self, state: impl Into<Prop<bool>>) -> Self {
1529        self.handler_set.visible_when = Some(state.into());
1530        self
1531    }
1532
1533    /// Set the drag hover handler. Called when a drag payload hovers over this widget.
1534    pub fn on_drag_hover(
1535        mut self,
1536        f: impl FnMut(
1537            &crate::drag_payload::DragPayload,
1538            teksilo_canvas::Point,
1539            &mut EventContext,
1540        ) -> crate::drag_state::DropFeedback
1541        + 'static,
1542    ) -> Self {
1543        self.handler_set.handlers.on_drag_hover = Some(Box::new(f));
1544        self
1545    }
1546
1547    /// Set the drag-leave handler. See [`HandlerSet::on_drag_leave`].
1548    pub fn on_drag_leave(mut self, f: impl FnMut(&mut EventContext) + 'static) -> Self {
1549        self.handler_set.handlers.on_drag_leave = Some(Box::new(f));
1550        self
1551    }
1552
1553    /// Set the pointer-cancel handler. See
1554    /// [`HandlerSet::on_pointer_cancel`].
1555    pub fn on_pointer_cancel(
1556        mut self,
1557        f: impl FnMut(&crate::pointer::PointerInfo, crate::pointer::CancelReason, &mut EventContext)
1558        + 'static,
1559    ) -> Self {
1560        self.handler_set.handlers.on_pointer_cancel = Some(Box::new(f));
1561        self
1562    }
1563
1564    /// Set the per-frame drag-tick handler. See [`HandlerSet::on_drag_tick`].
1565    pub fn on_drag_tick(
1566        mut self,
1567        f: impl FnMut(teksilo_canvas::Point, &mut EventContext) + 'static,
1568    ) -> Self {
1569        self.handler_set.handlers.on_drag_tick = Some(Box::new(f));
1570        self
1571    }
1572
1573    /// Set the drop handler. Called when a payload is dropped on this widget.
1574    pub fn on_drop(
1575        mut self,
1576        f: impl FnMut(
1577            crate::drag_payload::DragPayload,
1578            teksilo_canvas::Point,
1579            &mut EventContext,
1580        ) -> bool
1581        + 'static,
1582    ) -> Self {
1583        self.handler_set.handlers.on_drop = Some(Box::new(f));
1584        self
1585    }
1586
1587    /// Set the drag-ended handler on a drag source. See
1588    /// [`HandlerSet::on_drag_ended`].
1589    pub fn on_drag_ended(
1590        mut self,
1591        f: impl FnMut(crate::drag_payload::DropOutcome, &mut EventContext) + 'static,
1592    ) -> Self {
1593        self.handler_set.handlers.on_drag_ended = Some(Box::new(f));
1594        self
1595    }
1596
1597    // ── Accessibility overrides ────────────────────────────────────────
1598    //
1599    // The user-visible string methods take `impl Into<Prop<String>>` so
1600    // they stay reactive. With the `i18n` feature, `LocalizedString`
1601    // (produced by `tr!(...)`) provides `From<LocalizedString> for
1602    // Prop<String>`, which yields a locale-observing `Prop::Bound`, so
1603    // `.access_label(tr!(save()))` follows the locale. A bare `&str`
1604    // still converts (`impl From<&str> for Prop<String>` in `signal.rs`,
1605    // kept so call sites written against the older `impl Into<String>`
1606    // setters keep compiling), so routing untranslated literals through
1607    // `lit!(...)` (downstream crates) or the `_literal` twins (which
1608    // store `Prop::Static` — the only literal path reachable from within
1609    // `teksilo-core`) is a convention, not a compiler-enforced one. Do it
1610    // anyway: it is what makes an untranslated AT string greppable.
1611
1612    /// Override the accessibility label (`Node::label`) of this widget.
1613    /// Replaces whatever the inner widget emitted via `set_name`.
1614    ///
1615    /// Accepts any `impl Into<Prop<String>>`. With the `i18n` feature,
1616    /// `LocalizedString` (produced by `tr!(...)`)
1617    /// implements `From<LocalizedString> for Prop<String>`, so
1618    /// `.access_label(tr!(save()))` stays reactive — the announced
1619    /// value re-resolves on locale change (the accessibility tree
1620    /// re-walks via `sync_accessibility`).
1621    pub fn access_label(mut self, label: impl Into<Prop<String>>) -> Self {
1622        self.handler_set.access_mut().label = Some(label.into());
1623        self
1624    }
1625
1626    /// `#[doc(hidden)]` grep marker for explicitly-untranslated label
1627    /// strings — the same convention as the `lit!` macro downstream, which
1628    /// replaced the widgets' own `*_literal` constructors. Stores a
1629    /// `Prop::Static`. The distinct name makes untranslated call sites
1630    /// greppable as a one-pass audit, and it's the literal path
1631    /// reachable from within `teksilo-core` (where `lit!` isn't usable).
1632    #[doc(hidden)]
1633    pub fn access_label_literal(self, label: impl Into<String>) -> Self {
1634        self.access_label(Prop::Static(label.into()))
1635    }
1636
1637    /// Override the accessibility description (`Node::description`).
1638    /// Same conversion rules as `access_label`.
1639    pub fn access_description(mut self, description: impl Into<Prop<String>>) -> Self {
1640        self.handler_set.access_mut().description = Some(description.into());
1641        self
1642    }
1643
1644    #[doc(hidden)]
1645    pub fn access_description_literal(self, description: impl Into<String>) -> Self {
1646        self.access_description(Prop::Static(description.into()))
1647    }
1648
1649    /// Long-form context hint. Alias of `access_description` —
1650    /// AccessKit has no separate hint slot (SwiftUI's split is
1651    /// VoiceOver-specific). Provided for SwiftUI parity.
1652    pub fn access_hint(self, hint: impl Into<Prop<String>>) -> Self {
1653        self.access_description(hint)
1654    }
1655
1656    #[doc(hidden)]
1657    pub fn access_hint_literal(self, hint: impl Into<String>) -> Self {
1658        self.access_description(Prop::Static(hint.into()))
1659    }
1660
1661    /// Override the accessibility value (`Node::value`).
1662    /// Same conversion rules as `access_label`.
1663    pub fn access_value(mut self, value: impl Into<Prop<String>>) -> Self {
1664        self.handler_set.access_mut().value = Some(value.into());
1665        self
1666    }
1667
1668    #[doc(hidden)]
1669    pub fn access_value_literal(self, value: impl Into<String>) -> Self {
1670        self.access_value(Prop::Static(value.into()))
1671    }
1672
1673    /// Override the accessibility role.
1674    pub fn access_role(mut self, role: accesskit::Role) -> Self {
1675        self.handler_set.access_mut().role = Some(role);
1676        self
1677    }
1678
1679    /// Hide (or un-hide) this node, and everything under it, from assistive
1680    /// technologies. Accepts a plain `bool`, a `Signal<bool>`, or a
1681    /// `Prop<bool>`: a bound value makes the node appear/disappear from the
1682    /// AT tree reactively (the binding is registered at `AccessibilityOnly`,
1683    /// so the tree re-walks on change). `true` hides the whole subtree, as
1684    /// [`AccessNodeBuilder::set_hidden`](crate::accessibility::AccessNodeBuilder::set_hidden)
1685    /// explains; to drop only this node's own role and keep its content,
1686    /// use `access_role(Role::GenericContainer)` instead. `false` un-sets a
1687    /// hidden state the inner widget emitted on this node, and cannot reveal
1688    /// a node under a hidden ancestor.
1689    pub fn access_hidden(mut self, hidden: impl Into<Prop<bool>>) -> Self {
1690        self.handler_set.access_mut().hidden = Some(hidden.into());
1691        self
1692    }
1693
1694    /// Mark (or un-mark) this widget as disabled for AT. `false`
1695    /// clears both widget-emitted disabled state AND the framework's
1696    /// arena-driven disabled gate at
1697    /// `accessibility_emit_impl::build_accessibility_recursive`.
1698    pub fn access_disabled(mut self, disabled: bool) -> Self {
1699        self.handler_set.access_mut().disabled = Some(disabled);
1700        self
1701    }
1702
1703    /// Stable test/debug identifier (`Node::author_id`). Not
1704    /// user-visible — used by accessibility inspectors and UI tests.
1705    pub fn access_identifier(mut self, id: impl Into<String>) -> Self {
1706        self.handler_set.access_mut().identifier = Some(id.into());
1707        self
1708    }
1709
1710    /// Append a `controls` relationship. The target widget's NodeId
1711    /// is included in this node's `aria-controls`-equivalent list.
1712    pub fn access_controls(mut self, target: WidgetId) -> Self {
1713        self.handler_set.access_mut().controls.push(target);
1714        self
1715    }
1716
1717    /// Append a `described_by` relationship: `target`'s text describes this
1718    /// node, as `aria-describedby` does (WCAG 3.3.1 for a field and its error).
1719    ///
1720    /// AccessKit 0.25 passes the relation to no screen reader, so the tree
1721    /// also writes the target's text into this node's `description`, after
1722    /// any description of its own. That is what a reader says as focus
1723    /// arrives. The text follows the target, except around focus, where it
1724    /// would be said twice: while focus stays, and in the update focus leaves,
1725    /// a text that was not in the description waits (for the next arrival,
1726    /// or for the next update once focus has gone). On Windows a text a live
1727    /// region announces in the update focus arrives in is also left out of
1728    /// that arrival, since NVDA says the announcement; elsewhere the arrival
1729    /// keeps it, since Orca cuts an announcement to read the new focus.
1730    /// A message appearing is for a live region to say, the target itself or
1731    /// an announcement; the description is for coming back.
1732    pub fn access_described_by(mut self, target: WidgetId) -> Self {
1733        self.handler_set.access_mut().described_by.push(target);
1734        self
1735    }
1736
1737    /// Append a `labelled_by` relationship.
1738    pub fn access_labelled_by(mut self, target: WidgetId) -> Self {
1739        self.handler_set.access_mut().labelled_by.push(target);
1740        self
1741    }
1742
1743    /// Set the live-region politeness (`Node::live`).
1744    pub fn access_live(mut self, mode: accesskit::Live) -> Self {
1745        self.handler_set.access_mut().live = Some(mode);
1746        self
1747    }
1748
1749    /// Mark this node as the current item within its container
1750    /// (`aria-current`).
1751    pub fn access_current(mut self, current: accesskit::AriaCurrent) -> Self {
1752        self.handler_set.access_mut().aria_current = Some(current);
1753        self
1754    }
1755
1756    /// Pre-formatted shortcut announcement (e.g. `"Ctrl+S"`). Used for
1757    /// chords NOT routed through the `Shortcut` system — platform-native
1758    /// keys, app-internal hotkeys not exposed to user rebinding. For
1759    /// `Shortcut`-registered chords prefer
1760    /// [`access_shortcut_id`](Self::access_shortcut_id), which tracks
1761    /// rebinds automatically.
1762    pub fn access_shortcut_literal(mut self, shortcut: impl Into<String>) -> Self {
1763        self.handler_set.access_mut().shortcut = Some(shortcut.into());
1764        self
1765    }
1766
1767    /// Bind the announced shortcut to a registered `Shortcut` id (the
1768    /// same id you pass to `Shortcut::new("app.save")`). The
1769    /// accessibility tree walker resolves the current keystroke from
1770    /// `WidgetTree::shortcut_registry()` at AT-build time, formats it
1771    /// via `KeyStroke::Display` (`"Ctrl+S"`), and writes it to
1772    /// `Node::keyboard_shortcut`. Auto-refreshes on rebind.
1773    ///
1774    /// If the registry has no entry for `id` (no widget registered the
1775    /// shortcut yet), the announcement is omitted — same fallback as
1776    /// `MenuItem::for_shortcut(...)`.
1777    pub fn access_shortcut_id(mut self, id: impl Into<String>) -> Self {
1778        self.handler_set.access_mut().shortcut_id = Some(id.into());
1779        self
1780    }
1781
1782    /// Indicate that activating this widget pops up a menu / listbox /
1783    /// dialog (`aria-haspopup`).
1784    pub fn access_has_popup(mut self, kind: accesskit::HasPopup) -> Self {
1785        self.handler_set.access_mut().has_popup = Some(kind);
1786        self
1787    }
1788
1789    /// Override orientation (`Node::orientation`) — used on sliders,
1790    /// scrollbars, separators.
1791    pub fn access_orientation(mut self, orientation: accesskit::Orientation) -> Self {
1792        self.handler_set.access_mut().orientation = Some(orientation);
1793        self
1794    }
1795
1796    /// Prune all descendants from the accessibility tree. The widget's
1797    /// own AT node is still emitted; only children disappear. Use for
1798    /// purely decorative composites. Flutter's `excludeSemantics: true`.
1799    pub fn access_exclude_subtree(mut self) -> Self {
1800        self.handler_set.access_subtree = Some(AccessSubtreeMode::Exclude);
1801        self
1802    }
1803
1804    /// Lift descendants' labels / descriptions / values / actions into
1805    /// this widget's AT node, then prune the descendants. The whole
1806    /// composite reads as a single AT element. Flutter's
1807    /// `mergeAllDescendants: true` and SwiftUI's
1808    /// `.accessibilityElement(children: .combine)`.
1809    pub fn access_merge_subtree(mut self) -> Self {
1810        self.handler_set.access_subtree = Some(AccessSubtreeMode::Merge);
1811        self
1812    }
1813
1814    /// Set an explicit subtree mode.
1815    pub fn access_subtree(mut self, mode: AccessSubtreeMode) -> Self {
1816        self.handler_set.access_subtree = Some(mode);
1817        self
1818    }
1819
1820    /// Override `Node::numeric_value`.
1821    pub fn access_numeric_value(mut self, value: f64) -> Self {
1822        self.handler_set.access_mut().numeric_value = Some(value);
1823        self
1824    }
1825
1826    /// Override `Node::min_numeric_value` and `max_numeric_value`.
1827    pub fn access_numeric_range(mut self, min: f64, max: f64) -> Self {
1828        let access = self.handler_set.access_mut();
1829        access.min_numeric_value = Some(min);
1830        access.max_numeric_value = Some(max);
1831        self
1832    }
1833
1834    /// Override `Node::numeric_value_step`.
1835    pub fn access_numeric_step(mut self, step: f64) -> Self {
1836        self.handler_set.access_mut().numeric_step = Some(step);
1837        self
1838    }
1839
1840    /// Advertise an accessibility action and the callback that fires
1841    /// when AT software invokes it. Multiple `access_action` calls
1842    /// register separate callbacks for distinct actions; calling twice
1843    /// with the same action records both — they fire in order.
1844    pub fn access_action<F>(mut self, action: accesskit::Action, handler: F) -> Self
1845    where
1846        F: FnMut(&mut EventContext) + 'static,
1847    {
1848        self.handler_set
1849            .access_mut()
1850            .actions
1851            .push((action, Box::new(handler)));
1852        self
1853    }
1854
1855    /// Suppress an action the inner widget emitted (e.g. neutralize
1856    /// `Action::Click` on a Button used purely as a layout shim).
1857    /// Applied after the widget's `accessibility()` runs but before
1858    /// override-advertised actions, so a subsequent `access_action`
1859    /// for the same action re-advertises it with the override-installed
1860    /// callback.
1861    pub fn access_remove_action(mut self, action: accesskit::Action) -> Self {
1862        self.handler_set.access_mut().removed_actions.push(action);
1863        self
1864    }
1865
1866    /// Advertise a custom-named action (SwiftUI parity:
1867    /// `.accessibilityAction(named:_:)`). The label is exposed
1868    /// verbatim by AT software (e.g. VoiceOver's Actions rotor).
1869    /// Accepts `tr!(...)` via `From<LocalizedString> for Prop<String>`
1870    /// in `teksilo-i18n`, so the announced name follows the locale.
1871    pub fn access_custom_action<F>(mut self, label: impl Into<Prop<String>>, handler: F) -> Self
1872    where
1873        F: FnMut(&mut EventContext) + 'static,
1874    {
1875        self.handler_set
1876            .access_mut()
1877            .custom_actions
1878            .push((label.into(), Box::new(handler)));
1879        self
1880    }
1881
1882    #[doc(hidden)]
1883    pub fn access_custom_action_literal<F>(self, label: impl Into<String>, handler: F) -> Self
1884    where
1885        F: FnMut(&mut EventContext) + 'static,
1886    {
1887        self.access_custom_action(Prop::Static(label.into()), handler)
1888    }
1889
1890    /// Final escape hatch — invoked after all typed override setters,
1891    /// with full `&mut AccessNodeBuilder` access (including
1892    /// `inner_mut()`). Use for synthetic-child surgery (rich text
1893    /// paragraphs, text runs) or any AccessKit field the typed
1894    /// surface doesn't cover.
1895    pub fn access_customize<F>(mut self, f: F) -> Self
1896    where
1897        F: Fn(&mut crate::accessibility::AccessNodeBuilder) + 'static,
1898    {
1899        self.handler_set.access_mut().customize = Some(Box::new(f));
1900        self
1901    }
1902}
1903
1904// Delegate all Widget trait methods to the inner widget.
1905impl<W: Widget> std::fmt::Debug for WidgetWithHandlers<W> {
1906    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1907        let mut s = f.debug_struct("WidgetWithHandlers");
1908        s.field("widget", &self.widget);
1909        if self.handlers_taken {
1910            // Mounting moved the set to the node; what is left is the empty
1911            // default, which would read as "no cursor, no handlers".
1912            s.field("handlers", &format_args!("<moved to the tree>"));
1913        } else {
1914            s.field("handler_set", &self.handler_set);
1915        }
1916        s.finish()
1917    }
1918}
1919
1920/// Every method of [`Widget`], forwarded to the wrapped widget.
1921///
1922/// `WidgetWithHandlers<W>` **replaces** `W` at `W`'s own arena node — the tree
1923/// never sees `W` again. So a hook this impl does not forward is not overridden,
1924/// it is gone: the trait's default answers in its place, for every widget any
1925/// builder method has ever touched. Nothing warns, nothing fails to compile, and
1926/// the widget goes on building, painting and hit-testing; only the behaviour
1927/// behind the dropped hook stops, at a call site nowhere near the `.on_tap(..)`
1928/// that silenced it. A test that drives the hook on a bare widget cannot see
1929/// this, which is why every hook is also driven through a builder method in the
1930/// `wrapper_forwarding_tests` module below, and why `missing_trait_methods` is
1931/// denied here: a method added to `Widget` must fail this impl's lint before it
1932/// can quietly fail a user's app.
1933///
1934/// The methods appear in the order the trait declares them, so the two can be
1935/// read side by side.
1936#[deny(clippy::missing_trait_methods)]
1937impl<W: Widget + 'static> Widget for WidgetWithHandlers<W> {
1938    /// Forwarded so the name is the widget's. The wrapper's own name identifies
1939    /// the wrapper, which is never what a census bucket or an inspector row is
1940    /// asking about.
1941    fn type_name(&self) -> &'static str {
1942        self.widget.type_name()
1943    }
1944
1945    fn build(
1946        &mut self,
1947        ctx: &mut crate::build_context::BuildContext,
1948    ) -> Vec<crate::widget_id::WidgetId> {
1949        self.widget.build(ctx)
1950    }
1951
1952    fn layout_response(
1953        &self,
1954        proposal: teksilo_canvas::SizeProposal,
1955        ctx: &crate::widget::LayoutContext,
1956    ) -> crate::widget::LayoutResponse {
1957        self.widget.layout_response(proposal, ctx)
1958    }
1959
1960    /// Forwarded because the opt-out exists to protect a widget whose
1961    /// `layout_response` is not idempotent. Answering the default here caches
1962    /// such a widget anyway, and a memoized non-idempotent measure is wrong in a
1963    /// way no layout assertion localizes.
1964    fn cacheable_layout(&self) -> bool {
1965        self.widget.cacheable_layout()
1966    }
1967
1968    fn place_children(
1969        &self,
1970        bounds: teksilo_canvas::Rect,
1971        proposal: teksilo_canvas::SizeProposal,
1972        children: &mut [crate::widget::WidgetPlacement],
1973        ctx: &crate::widget::LayoutContext,
1974    ) {
1975        self.widget.place_children(bounds, proposal, children, ctx)
1976    }
1977
1978    fn paint(
1979        &self,
1980        bounds: teksilo_canvas::Rect,
1981        canvas: &mut teksilo_canvas::Canvas,
1982        ctx: &crate::widget::PaintContext,
1983    ) {
1984        self.widget.paint(bounds, canvas, ctx)
1985    }
1986
1987    /// The two paint hooks and their `wants_*` gates are forwarded as pairs: the
1988    /// walker consults the gate and skips the hook when it answers `false`, so a
1989    /// forwarded hook behind an unforwarded gate never runs, and the widget
1990    /// reads as having no hook at all rather than as having lost one.
1991    fn wants_after_paint(&self) -> bool {
1992        self.widget.wants_after_paint()
1993    }
1994
1995    fn after_paint(
1996        &self,
1997        view: &crate::widget::WidgetTreeView<'_>,
1998        ctx: &crate::widget::PaintContext,
1999    ) {
2000        self.widget.after_paint(view, ctx)
2001    }
2002
2003    fn wants_post_paint(&self) -> bool {
2004        self.widget.wants_post_paint()
2005    }
2006
2007    fn post_paint(
2008        &self,
2009        bounds: teksilo_canvas::Rect,
2010        canvas: &mut teksilo_canvas::Canvas,
2011        ctx: &crate::widget::PaintContext,
2012    ) {
2013        self.widget.post_paint(bounds, canvas, ctx)
2014    }
2015
2016    fn accessibility(&self, builder: &mut crate::accessibility::AccessNodeBuilder) {
2017        self.widget.accessibility(builder)
2018    }
2019
2020    fn culls_children(&self) -> bool {
2021        self.widget.culls_children()
2022    }
2023
2024    /// Gate and hook again — see [`Widget::wants_after_paint`].
2025    fn wants_descendant_redirects(&self) -> bool {
2026        self.widget.wants_descendant_redirects()
2027    }
2028
2029    fn a11y_redirect_descendant(
2030        &self,
2031        self_id: crate::widget_id::WidgetId,
2032        descendant: crate::widget_id::WidgetId,
2033    ) -> Option<accesskit::NodeId> {
2034        self.widget.a11y_redirect_descendant(self_id, descendant)
2035    }
2036
2037    fn accessible_title_hint(&self) -> Option<String> {
2038        self.widget.accessible_title_hint()
2039    }
2040
2041    fn accessible_title_node(&self) -> Option<crate::widget_id::WidgetId> {
2042        self.widget.accessible_title_node()
2043    }
2044
2045    fn initial_focus_hint(&self) -> Option<crate::widget_id::WidgetId> {
2046        self.widget.initial_focus_hint()
2047    }
2048
2049    fn accessibility_proxy(&self) -> Option<crate::widget_id::WidgetId> {
2050        self.widget.accessibility_proxy()
2051    }
2052
2053    fn context_menu_key_target(&self) -> Option<crate::widget_id::WidgetId> {
2054        self.widget.context_menu_key_target()
2055    }
2056
2057    fn children(&self) -> Vec<crate::widget_id::WidgetId> {
2058        self.widget.children()
2059    }
2060
2061    fn accessibility_children(&self) -> Option<Vec<crate::widget_id::WidgetId>> {
2062        self.widget.accessibility_children()
2063    }
2064
2065    fn as_any(&self) -> Option<&dyn std::any::Any> {
2066        self.widget.as_any()
2067    }
2068
2069    /// Mutable counterpart of [`as_any`](Widget::as_any), forwarded for the
2070    /// same reason it is.
2071    ///
2072    /// A composing container that reads a child's concrete type must see the
2073    /// same widget whether or not a builder method wrapped it. `MenuList` reads
2074    /// a `MenuItem` this way for its mnemonic, its type-ahead label, its radio
2075    /// group and its safe-triangle state; without this forward,
2076    /// `MenuItem::new(..).context_menu(..)` silently stops being a `MenuItem`
2077    /// to its parent — no error, just a row that lost all four.
2078    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
2079        self.widget.as_any_mut()
2080    }
2081
2082    fn clips_children(&self) -> bool {
2083        self.handler_set
2084            .clips_children
2085            .unwrap_or_else(|| self.widget.clips_children())
2086    }
2087
2088    fn focus_reveal_rect(&self, bounds: teksilo_canvas::Rect) -> Option<teksilo_canvas::Rect> {
2089        self.widget.focus_reveal_rect(bounds)
2090    }
2091
2092    /// The hit-shape family, forwarded for the same reason `as_any` is: a
2093    /// widget must not stop being itself to the hit test because a builder
2094    /// method wrapped it.
2095    ///
2096    /// A round control that answers `hit_shape` and `hit_distance` loses both
2097    /// the moment someone writes `.on_tap(..)` on it if these are not
2098    /// forwarded — and loses them silently, which is the worst way to lose a
2099    /// hit test. The node-level `.hit_slop(..)` / `.no_hit_slop()` overrides
2100    /// need no forwarding: they ride the `HandlerSet` onto the node.
2101    fn hit_shape(&self, local_point: teksilo_canvas::Point, bounds: teksilo_canvas::Rect) -> bool {
2102        self.widget.hit_shape(local_point, bounds)
2103    }
2104
2105    fn accepts_child_hit(&self, child: WidgetId, point: teksilo_canvas::Point) -> bool {
2106        self.widget.accepts_child_hit(child, point)
2107    }
2108
2109    fn hit_outset(
2110        &self,
2111        kind: teksilo_tokens::PointerKind,
2112        tokens: &teksilo_tokens::InputTokens,
2113    ) -> teksilo_canvas::EdgeInsets {
2114        self.widget.hit_outset(kind, tokens)
2115    }
2116
2117    fn hit_slop(
2118        &self,
2119        kind: teksilo_tokens::PointerKind,
2120        tokens: &teksilo_tokens::InputTokens,
2121    ) -> Option<crate::pointer::hit_slop::HitSlop> {
2122        // Disambiguated: `WidgetBuilder::hit_slop(self, HitSlop)` — the
2123        // consuming builder method — shares this name, exactly as
2124        // `clips_children` does on both traits.
2125        Widget::hit_slop(&self.widget, kind, tokens)
2126    }
2127
2128    fn hit_distance(
2129        &self,
2130        local_point: teksilo_canvas::Point,
2131        bounds: teksilo_canvas::Rect,
2132    ) -> Option<f32> {
2133        self.widget.hit_distance(local_point, bounds)
2134    }
2135
2136    fn target_regions(&self, bounds: teksilo_canvas::Rect) -> Vec<crate::partition::TargetRegion> {
2137        self.widget.target_regions(bounds)
2138    }
2139
2140    /// Forwarded because the default is the destructive answer. A container that
2141    /// keeps memoized panes across a rebuild loses them to a builder method
2142    /// otherwise, and the loss reads as content that vanishes on an unrelated
2143    /// state change rather than as a dropped forward.
2144    fn preserves_children_on_rebuild(&self) -> bool {
2145        self.widget.preserves_children_on_rebuild()
2146    }
2147
2148    /// Forwarded so tooltip content that knows itself to be empty can still say
2149    /// so. The default is `true`, which shows an empty bubble instead.
2150    fn tooltip_has_content(&self) -> bool {
2151        self.widget.tooltip_has_content()
2152    }
2153
2154    /// Forwarded because a declaration is how the registry and the rebinding UI
2155    /// learn a keystroke exists. Dropped, the shortcut is not overridden by
2156    /// anything — it is simply never registered.
2157    fn declare_shortcuts(&self) -> Vec<crate::shortcut::Shortcut> {
2158        self.widget.declare_shortcuts()
2159    }
2160
2161    /// The one method here that is **not** a forward, deliberately: it exists so
2162    /// the arena can lift off the handlers the builder chain just attached, and
2163    /// those live on the wrapper, not on the widget. Forwarding it would hand
2164    /// the arena the wrapped widget's set instead and the attached handlers
2165    /// would never reach the node — which is the whole point of the wrapper.
2166    ///
2167    /// The call is the inherent `WidgetWithHandlers::take_handler_set`, not this
2168    /// one.
2169    fn take_handler_set(&mut self) -> Option<HandlerSet> {
2170        // Recursive, because a `WidgetBuilder` method with no inherent twin on
2171        // this type wraps an already-wrapped widget. Lifting only the outer set
2172        // silently drops every handler attached before that call.
2173        let mut outer = WidgetWithHandlers::take_handler_set(self);
2174        if let Some(inner) = crate::widget::Widget::take_handler_set(&mut self.widget) {
2175            outer.merge_under(inner);
2176        }
2177        Some(outer)
2178    }
2179}
2180
2181// ---------------------------------------------------------------------------
2182// WidgetBuilder trait — the entry point
2183// ---------------------------------------------------------------------------
2184
2185/// Blanket trait providing attached handler methods for all Widget types.
2186/// The first builder method call wraps the widget in `WidgetWithHandlers`.
2187pub trait WidgetBuilder: Widget + Sized + 'static {
2188    fn on_tap(
2189        self,
2190        f: impl FnMut(&TapEvent, &mut EventContext) + 'static,
2191    ) -> WidgetWithHandlers<Self> {
2192        WidgetWithHandlers::new(self).on_tap(f)
2193    }
2194
2195    fn on_double_tap(
2196        self,
2197        f: impl FnMut(&TapEvent, &mut EventContext) + 'static,
2198    ) -> WidgetWithHandlers<Self> {
2199        WidgetWithHandlers::new(self).on_double_tap(f)
2200    }
2201
2202    fn on_triple_tap(
2203        self,
2204        f: impl FnMut(&TapEvent, &mut EventContext) + 'static,
2205    ) -> WidgetWithHandlers<Self> {
2206        WidgetWithHandlers::new(self).on_triple_tap(f)
2207    }
2208
2209    fn on_long_press(
2210        self,
2211        f: impl FnMut(&TapEvent, &mut EventContext) + 'static,
2212    ) -> WidgetWithHandlers<Self> {
2213        WidgetWithHandlers::new(self).on_long_press(f)
2214    }
2215
2216    /// Restrict (or extend) the set of pointer buttons that fire
2217    /// `on_tap`. Default is [`ButtonMask::PRIMARY`].
2218    ///
2219    /// The mask belongs to the `on_tap` set beside it. A node carries two
2220    /// handler sets, the widget's own (from its `build`) and the one this
2221    /// builder chain attaches, and each fires only on the buttons in its own
2222    /// mask: widening the app's `on_tap` to the secondary button does not make
2223    /// a right click run the widget's built-in click (a `Slider` jumping to
2224    /// it, say). A mask set where no `on_tap` is attached beside it reaches
2225    /// the widget's own instead, unless that one declared a mask of its own:
2226    /// `Button::new(..).accept_tap_buttons(PRIMARY | SECONDARY)` is how a
2227    /// right click activates a button.
2228    fn accept_tap_buttons(self, mask: impl Into<ButtonMask>) -> WidgetWithHandlers<Self> {
2229        WidgetWithHandlers::new(self).accept_tap_buttons(mask)
2230    }
2231
2232    /// Restrict (or extend) the set of pointer buttons that fire
2233    /// `on_double_tap`. Default [`ButtonMask::PRIMARY`].
2234    ///
2235    /// Scoped to the handler set it is attached with, the way
2236    /// [`accept_tap_buttons`](Self::accept_tap_buttons) is.
2237    fn accept_double_tap_buttons(self, mask: impl Into<ButtonMask>) -> WidgetWithHandlers<Self> {
2238        WidgetWithHandlers::new(self).accept_double_tap_buttons(mask)
2239    }
2240
2241    /// Restrict (or extend) the set of pointer buttons that fire
2242    /// `on_triple_tap`. Default [`ButtonMask::PRIMARY`].
2243    ///
2244    /// Scoped to the handler set it is attached with, the way
2245    /// [`accept_tap_buttons`](Self::accept_tap_buttons) is.
2246    fn accept_triple_tap_buttons(self, mask: impl Into<ButtonMask>) -> WidgetWithHandlers<Self> {
2247        WidgetWithHandlers::new(self).accept_triple_tap_buttons(mask)
2248    }
2249
2250    /// Restrict (or extend) the set of pointer buttons that fire
2251    /// `on_long_press`. Default [`ButtonMask::PRIMARY`].
2252    ///
2253    /// Scoped to the handler set it is attached with, the way
2254    /// [`accept_tap_buttons`](Self::accept_tap_buttons) is.
2255    fn accept_long_press_buttons(self, mask: impl Into<ButtonMask>) -> WidgetWithHandlers<Self> {
2256        WidgetWithHandlers::new(self).accept_long_press_buttons(mask)
2257    }
2258
2259    fn on_drag(
2260        self,
2261        f: impl FnMut(DragPhase, &mut EventContext) + 'static,
2262    ) -> WidgetWithHandlers<Self> {
2263        WidgetWithHandlers::new(self).on_drag(f)
2264    }
2265
2266    fn on_swipe(
2267        self,
2268        f: impl FnMut(SwipeDirection, f32, &mut EventContext) + 'static,
2269    ) -> WidgetWithHandlers<Self> {
2270        WidgetWithHandlers::new(self).on_swipe(f)
2271    }
2272
2273    fn on_pinch(
2274        self,
2275        f: impl FnMut(PinchPhase, &mut EventContext) + 'static,
2276    ) -> WidgetWithHandlers<Self> {
2277        WidgetWithHandlers::new(self).on_pinch(f)
2278    }
2279
2280    fn on_focus(
2281        self,
2282        f: impl FnMut(bool, &mut EventContext) + 'static,
2283    ) -> WidgetWithHandlers<Self> {
2284        WidgetWithHandlers::new(self).on_focus(f)
2285    }
2286
2287    fn on_key(
2288        self,
2289        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
2290    ) -> WidgetWithHandlers<Self> {
2291        WidgetWithHandlers::new(self).on_key(f)
2292    }
2293
2294    /// Strict-ancestor key preview. See [`HandlerSet::on_key_preview`].
2295    fn on_key_preview(
2296        self,
2297        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
2298    ) -> WidgetWithHandlers<Self> {
2299        WidgetWithHandlers::new(self).on_key_preview(f)
2300    }
2301
2302    fn on_pointer_event(
2303        self,
2304        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
2305    ) -> WidgetWithHandlers<Self> {
2306        WidgetWithHandlers::new(self).on_pointer_event(f)
2307    }
2308
2309    fn on_hover(
2310        self,
2311        f: impl FnMut(bool, &mut EventContext) + 'static,
2312    ) -> WidgetWithHandlers<Self> {
2313        WidgetWithHandlers::new(self).on_hover(f)
2314    }
2315
2316    fn on_scroll(
2317        self,
2318        f: impl FnMut(&WidgetEvent, &mut EventContext) -> EventResponse + 'static,
2319    ) -> WidgetWithHandlers<Self> {
2320        WidgetWithHandlers::new(self).on_scroll(f)
2321    }
2322
2323    fn on_access_action(
2324        self,
2325        f: impl FnMut(accesskit::Action, &mut EventContext) -> EventResponse + 'static,
2326    ) -> WidgetWithHandlers<Self> {
2327        WidgetWithHandlers::new(self).on_access_action(f)
2328    }
2329
2330    fn focusable(self, focusable: bool) -> WidgetWithHandlers<Self> {
2331        WidgetWithHandlers::new(self).focusable(focusable)
2332    }
2333
2334    fn tab_index(self, index: i32) -> WidgetWithHandlers<Self> {
2335        WidgetWithHandlers::new(self).tab_index(index)
2336    }
2337
2338    fn cursor(self, cursor: CursorIcon) -> WidgetWithHandlers<Self> {
2339        WidgetWithHandlers::new(self).cursor(cursor)
2340    }
2341
2342    fn clips_children_on(self, clips: bool) -> WidgetWithHandlers<Self> {
2343        WidgetWithHandlers::new(self).clips_children(clips)
2344    }
2345
2346    /// Declare this node a text-input surface, enabling the OS input method
2347    /// (with `ctx`'s purpose) while it is focused. See [`crate::ime`].
2348    fn ime_input(self, ctx: crate::ime::ImeContext) -> WidgetWithHandlers<Self> {
2349        WidgetWithHandlers::new(self).ime_input(ctx)
2350    }
2351
2352    /// Make the widget invisible to pointer hit-testing. See
2353    /// [`HandlerSet::event_pass_through`].
2354    fn event_pass_through(self, pass_through: bool) -> WidgetWithHandlers<Self> {
2355        WidgetWithHandlers::new(self).event_pass_through(pass_through)
2356    }
2357
2358    /// Mark this widget's subtree a gesture dead zone. See
2359    /// [`HandlerSet::gesture_dead_zone`].
2360    fn gesture_dead_zone(self, dead_zone: bool) -> WidgetWithHandlers<Self> {
2361        WidgetWithHandlers::new(self).gesture_dead_zone(dead_zone)
2362    }
2363
2364    /// Select what a hold on this widget's subtree means. See
2365    /// [`HandlerSet::long_press_role`].
2366    fn long_press_role(
2367        self,
2368        role: crate::widget_tree::touch_route::LongPressRole,
2369    ) -> WidgetWithHandlers<Self> {
2370        WidgetWithHandlers::new(self).long_press_role(role)
2371    }
2372
2373    /// Override what a direct pointer may do to this widget's subtree. See
2374    /// [`HandlerSet::touch_action`].
2375    fn touch_action(self, action: TouchAction) -> WidgetWithHandlers<Self> {
2376        WidgetWithHandlers::new(self).touch_action(action)
2377    }
2378
2379    /// Declare this widget a pan surface on `axes`, kinetic, direct pointers
2380    /// only. See [`HandlerSet::scroll_container`].
2381    fn scroll_container(self, axes: PanAxes) -> WidgetWithHandlers<Self> {
2382        WidgetWithHandlers::new(self).scroll_container(axes)
2383    }
2384
2385    /// Declare this widget a pan surface with an explicit [`PanClaim`]. See
2386    /// [`HandlerSet::pan_claim`].
2387    fn pan_claim(self, claim: PanClaim) -> WidgetWithHandlers<Self> {
2388        WidgetWithHandlers::new(self).pan_claim(claim)
2389    }
2390
2391    /// Whether this widget absorbs a boundary scroll or chains it outward. See
2392    /// [`HandlerSet::overscroll_behavior`].
2393    fn overscroll_behavior(self, behavior: crate::OverscrollBehavior) -> WidgetWithHandlers<Self> {
2394        WidgetWithHandlers::new(self).overscroll_behavior(behavior)
2395    }
2396
2397    /// Declare when a drag on this widget may begin relative to the press that
2398    /// starts it. See [`HandlerSet::drag_activation`].
2399    fn drag_activation(
2400        self,
2401        activation: teksilo_tokens::DragActivation,
2402    ) -> WidgetWithHandlers<Self> {
2403        WidgetWithHandlers::new(self).drag_activation(activation)
2404    }
2405
2406    /// Declare how many simultaneous contacts this widget serves. Default
2407    /// [`MultiContact::First`] — the second finger on a single-contact control
2408    /// is terminated there rather than reaching an ancestor.
2409    fn multi_contact(self, policy: MultiContact) -> WidgetWithHandlers<Self> {
2410        WidgetWithHandlers::new(self).multi_contact(policy)
2411    }
2412
2413    /// Mark this widget a keyboard capture surface (terminals, game
2414    /// viewports): while focused, `KeyDown`s bypass shortcut resolution.
2415    /// See [`HandlerSet::keyboard_capture`].
2416    fn keyboard_capture(self, capture: bool) -> WidgetWithHandlers<Self> {
2417        WidgetWithHandlers::new(self).keyboard_capture(capture)
2418    }
2419
2420    /// Make this widget and its whole subtree invisible to pointer
2421    /// hit-testing (decorative overlays). See
2422    /// [`HandlerSet::hit_transparent`].
2423    fn hit_transparent(self, transparent: bool) -> WidgetWithHandlers<Self> {
2424        WidgetWithHandlers::new(self).hit_transparent(transparent)
2425    }
2426
2427    /// Override the miss-only hit slop for this node. See
2428    /// [`HandlerSet::hit_slop`].
2429    fn hit_slop(self, slop: crate::pointer::hit_slop::HitSlop) -> WidgetWithHandlers<Self> {
2430        WidgetWithHandlers::new(self).hit_slop(slop)
2431    }
2432
2433    /// Take this node out of both hit-widening mechanisms — no slop outset and
2434    /// no `Widget::hit_outset`. See [`HandlerSet::no_hit_slop`].
2435    fn no_hit_slop(self) -> WidgetWithHandlers<Self> {
2436        WidgetWithHandlers::new(self).no_hit_slop()
2437    }
2438
2439    /// Set a context-menu factory. See
2440    /// [`HandlerSet::context_menu`] for the full contract.
2441    fn context_menu(
2442        self,
2443        factory: impl Fn(Point, &mut EventContext) -> Option<Box<dyn Widget>> + 'static,
2444    ) -> WidgetWithHandlers<Self> {
2445        WidgetWithHandlers::new(self).context_menu(factory)
2446    }
2447
2448    /// Bind a `Signal<bool>` the framework writes when a strict
2449    /// descendant has focus. See [`HandlerSet::focus_within`].
2450    fn focus_within(self, signal: crate::signal::Signal<bool>) -> WidgetWithHandlers<Self> {
2451        WidgetWithHandlers::new(self).focus_within(signal)
2452    }
2453
2454    /// Bind a `Signal<bool>` the framework writes when a strict
2455    /// descendant is hovered. See [`HandlerSet::hover_within`].
2456    fn hover_within(self, signal: crate::signal::Signal<bool>) -> WidgetWithHandlers<Self> {
2457        WidgetWithHandlers::new(self).hover_within(signal)
2458    }
2459
2460    /// Bind this node's visibility (`bool` / `Signal<bool>` / `Prop<bool>`) as
2461    /// a builder property, so `teksu!` can write `visible_when: sig`. Equivalent
2462    /// to `ctx.visible_when(id, ..)`. See [`HandlerSet::visible_when`].
2463    fn visible_when(self, state: impl Into<Prop<bool>>) -> WidgetWithHandlers<Self> {
2464        WidgetWithHandlers::new(self).visible_when(state)
2465    }
2466
2467    fn on_drag_hover(
2468        self,
2469        f: impl FnMut(
2470            &crate::drag_payload::DragPayload,
2471            teksilo_canvas::Point,
2472            &mut EventContext,
2473        ) -> crate::drag_state::DropFeedback
2474        + 'static,
2475    ) -> WidgetWithHandlers<Self> {
2476        WidgetWithHandlers::new(self).on_drag_hover(f)
2477    }
2478
2479    fn on_drag_leave(self, f: impl FnMut(&mut EventContext) + 'static) -> WidgetWithHandlers<Self> {
2480        WidgetWithHandlers::new(self).on_drag_leave(f)
2481    }
2482
2483    fn on_drag_tick(
2484        self,
2485        f: impl FnMut(teksilo_canvas::Point, &mut EventContext) + 'static,
2486    ) -> WidgetWithHandlers<Self> {
2487        WidgetWithHandlers::new(self).on_drag_tick(f)
2488    }
2489
2490    /// Attach a pointer-cancel handler. See
2491    /// [`HandlerSet::on_pointer_cancel`].
2492    fn on_pointer_cancel(
2493        self,
2494        f: impl FnMut(&crate::pointer::PointerInfo, crate::pointer::CancelReason, &mut EventContext)
2495        + 'static,
2496    ) -> WidgetWithHandlers<Self> {
2497        WidgetWithHandlers::new(self).on_pointer_cancel(f)
2498    }
2499
2500    fn on_drop(
2501        self,
2502        f: impl FnMut(
2503            crate::drag_payload::DragPayload,
2504            teksilo_canvas::Point,
2505            &mut EventContext,
2506        ) -> bool
2507        + 'static,
2508    ) -> WidgetWithHandlers<Self> {
2509        WidgetWithHandlers::new(self).on_drop(f)
2510    }
2511
2512    /// Set the drag-ended handler on a drag source. See
2513    /// [`HandlerSet::on_drag_ended`].
2514    fn on_drag_ended(
2515        self,
2516        f: impl FnMut(crate::drag_payload::DropOutcome, &mut EventContext) + 'static,
2517    ) -> WidgetWithHandlers<Self> {
2518        WidgetWithHandlers::new(self).on_drag_ended(f)
2519    }
2520
2521    // ── Accessibility overrides ────────────────────────────────────────
2522    //
2523    // Trait-level entry points: each method wraps the widget into a
2524    // `WidgetWithHandlers` (the first builder call in any chain) and
2525    // forwards to the inherent method of the same name. See
2526    // `WidgetWithHandlers` for full rustdoc on each method's semantics.
2527    // For translated strings, `LocalizedString` flows through
2528    // `impl Into<Prop<String>>` via `teksilo-i18n`'s
2529    // `From<LocalizedString> for Prop<String>` impl, staying reactive.
2530
2531    fn access_label(self, label: impl Into<Prop<String>>) -> WidgetWithHandlers<Self> {
2532        WidgetWithHandlers::new(self).access_label(label)
2533    }
2534
2535    #[doc(hidden)]
2536    fn access_label_literal(self, label: impl Into<String>) -> WidgetWithHandlers<Self> {
2537        WidgetWithHandlers::new(self).access_label_literal(label)
2538    }
2539
2540    fn access_description(self, description: impl Into<Prop<String>>) -> WidgetWithHandlers<Self> {
2541        WidgetWithHandlers::new(self).access_description(description)
2542    }
2543
2544    #[doc(hidden)]
2545    fn access_description_literal(
2546        self,
2547        description: impl Into<String>,
2548    ) -> WidgetWithHandlers<Self> {
2549        WidgetWithHandlers::new(self).access_description_literal(description)
2550    }
2551
2552    fn access_hint(self, hint: impl Into<Prop<String>>) -> WidgetWithHandlers<Self> {
2553        WidgetWithHandlers::new(self).access_hint(hint)
2554    }
2555
2556    #[doc(hidden)]
2557    fn access_hint_literal(self, hint: impl Into<String>) -> WidgetWithHandlers<Self> {
2558        WidgetWithHandlers::new(self).access_hint_literal(hint)
2559    }
2560
2561    fn access_value(self, value: impl Into<Prop<String>>) -> WidgetWithHandlers<Self> {
2562        WidgetWithHandlers::new(self).access_value(value)
2563    }
2564
2565    #[doc(hidden)]
2566    fn access_value_literal(self, value: impl Into<String>) -> WidgetWithHandlers<Self> {
2567        WidgetWithHandlers::new(self).access_value_literal(value)
2568    }
2569
2570    fn access_role(self, role: accesskit::Role) -> WidgetWithHandlers<Self> {
2571        WidgetWithHandlers::new(self).access_role(role)
2572    }
2573
2574    fn access_hidden(self, hidden: impl Into<Prop<bool>>) -> WidgetWithHandlers<Self> {
2575        WidgetWithHandlers::new(self).access_hidden(hidden)
2576    }
2577
2578    fn access_disabled(self, disabled: bool) -> WidgetWithHandlers<Self> {
2579        WidgetWithHandlers::new(self).access_disabled(disabled)
2580    }
2581
2582    fn access_identifier(self, id: impl Into<String>) -> WidgetWithHandlers<Self> {
2583        WidgetWithHandlers::new(self).access_identifier(id)
2584    }
2585
2586    fn access_controls(self, target: WidgetId) -> WidgetWithHandlers<Self> {
2587        WidgetWithHandlers::new(self).access_controls(target)
2588    }
2589
2590    fn access_described_by(self, target: WidgetId) -> WidgetWithHandlers<Self> {
2591        WidgetWithHandlers::new(self).access_described_by(target)
2592    }
2593
2594    fn access_labelled_by(self, target: WidgetId) -> WidgetWithHandlers<Self> {
2595        WidgetWithHandlers::new(self).access_labelled_by(target)
2596    }
2597
2598    fn access_live(self, mode: accesskit::Live) -> WidgetWithHandlers<Self> {
2599        WidgetWithHandlers::new(self).access_live(mode)
2600    }
2601
2602    fn access_current(self, current: accesskit::AriaCurrent) -> WidgetWithHandlers<Self> {
2603        WidgetWithHandlers::new(self).access_current(current)
2604    }
2605
2606    fn access_shortcut_literal(self, shortcut: impl Into<String>) -> WidgetWithHandlers<Self> {
2607        WidgetWithHandlers::new(self).access_shortcut_literal(shortcut)
2608    }
2609
2610    fn access_shortcut_id(self, id: impl Into<String>) -> WidgetWithHandlers<Self> {
2611        WidgetWithHandlers::new(self).access_shortcut_id(id)
2612    }
2613
2614    fn access_has_popup(self, kind: accesskit::HasPopup) -> WidgetWithHandlers<Self> {
2615        WidgetWithHandlers::new(self).access_has_popup(kind)
2616    }
2617
2618    fn access_orientation(self, orientation: accesskit::Orientation) -> WidgetWithHandlers<Self> {
2619        WidgetWithHandlers::new(self).access_orientation(orientation)
2620    }
2621
2622    fn access_exclude_subtree(self) -> WidgetWithHandlers<Self> {
2623        WidgetWithHandlers::new(self).access_exclude_subtree()
2624    }
2625
2626    fn access_merge_subtree(self) -> WidgetWithHandlers<Self> {
2627        WidgetWithHandlers::new(self).access_merge_subtree()
2628    }
2629
2630    fn access_subtree(self, mode: AccessSubtreeMode) -> WidgetWithHandlers<Self> {
2631        WidgetWithHandlers::new(self).access_subtree(mode)
2632    }
2633
2634    fn access_numeric_value(self, value: f64) -> WidgetWithHandlers<Self> {
2635        WidgetWithHandlers::new(self).access_numeric_value(value)
2636    }
2637
2638    fn access_numeric_range(self, min: f64, max: f64) -> WidgetWithHandlers<Self> {
2639        WidgetWithHandlers::new(self).access_numeric_range(min, max)
2640    }
2641
2642    fn access_numeric_step(self, step: f64) -> WidgetWithHandlers<Self> {
2643        WidgetWithHandlers::new(self).access_numeric_step(step)
2644    }
2645
2646    fn access_action<F>(self, action: accesskit::Action, handler: F) -> WidgetWithHandlers<Self>
2647    where
2648        F: FnMut(&mut EventContext) + 'static,
2649    {
2650        WidgetWithHandlers::new(self).access_action(action, handler)
2651    }
2652
2653    fn access_remove_action(self, action: accesskit::Action) -> WidgetWithHandlers<Self> {
2654        WidgetWithHandlers::new(self).access_remove_action(action)
2655    }
2656
2657    fn access_custom_action<F>(
2658        self,
2659        label: impl Into<Prop<String>>,
2660        handler: F,
2661    ) -> WidgetWithHandlers<Self>
2662    where
2663        F: FnMut(&mut EventContext) + 'static,
2664    {
2665        WidgetWithHandlers::new(self).access_custom_action(label, handler)
2666    }
2667
2668    #[doc(hidden)]
2669    fn access_custom_action_literal<F>(
2670        self,
2671        label: impl Into<String>,
2672        handler: F,
2673    ) -> WidgetWithHandlers<Self>
2674    where
2675        F: FnMut(&mut EventContext) + 'static,
2676    {
2677        WidgetWithHandlers::new(self).access_custom_action_literal(label, handler)
2678    }
2679
2680    fn access_customize<F>(self, f: F) -> WidgetWithHandlers<Self>
2681    where
2682        F: Fn(&mut crate::accessibility::AccessNodeBuilder) + 'static,
2683    {
2684        WidgetWithHandlers::new(self).access_customize(f)
2685    }
2686}
2687
2688// Blanket implementation for all Widget types.
2689impl<W: Widget + Sized + 'static> WidgetBuilder for W {}
2690
2691#[cfg(test)]
2692mod wrapper_forwarding_tests;
2693
2694#[cfg(test)]
2695mod tests {
2696    use super::*;
2697    use crate::widget::WidgetPlacement;
2698    use crate::widget_id::WidgetId;
2699    use crate::widget_tree::WidgetTree;
2700
2701    #[derive(Debug)]
2702    struct CompositeLeaf {
2703        child_id: Option<WidgetId>,
2704    }
2705
2706    impl CompositeLeaf {
2707        fn new() -> Self {
2708            Self { child_id: None }
2709        }
2710    }
2711
2712    impl Widget for CompositeLeaf {
2713        fn build(&mut self, ctx: &mut crate::build_context::BuildContext) -> Vec<WidgetId> {
2714            let child = ctx.add(crate::test_widgets::FillWidget::new());
2715            self.child_id = Some(child);
2716            vec![child]
2717        }
2718
2719        fn layout_response(
2720            &self,
2721            proposal: teksilo_canvas::SizeProposal,
2722            _ctx: &crate::widget::LayoutContext,
2723        ) -> crate::widget::LayoutResponse {
2724            proposal.resolve(120.0, 40.0).into()
2725        }
2726
2727        fn place_children(
2728            &self,
2729            bounds: teksilo_canvas::Rect,
2730            _proposal: teksilo_canvas::SizeProposal,
2731            children: &mut [WidgetPlacement],
2732            _ctx: &crate::widget::LayoutContext,
2733        ) {
2734            for child in children.iter_mut() {
2735                child.origin = bounds.origin();
2736                child.size = bounds.size();
2737            }
2738        }
2739
2740        fn children(&self) -> Vec<WidgetId> {
2741            self.child_id.into_iter().collect()
2742        }
2743    }
2744
2745    #[test]
2746    fn external_handlers_survive_rebuild() {
2747        // Regression check: handlers attached externally via the
2748        // `WidgetBuilder` builder (e.g. `MyCompositeWidget::new().on_tap(...)`)
2749        // must continue to fire after the widget rebuilds in place.
2750        // My handler-clearing fix in `rebuild_single_widget` wiped
2751        // `node.handlers` to stop accumulation of `apply_self_handlers`
2752        // calls across rebuilds — but the extracted-once-at-insertion
2753        // HandlerSet is gone by rebuild time and would be lost.
2754        use std::cell::Cell;
2755        use std::rc::Rc;
2756
2757        let tap_count = Rc::new(Cell::new(0_u32));
2758        let tc = tap_count.clone();
2759
2760        let mut tree = WidgetTree::new();
2761        let id = tree.add(CompositeLeaf::new().on_tap(move |_pos, _ctx| {
2762            tc.set(tc.get() + 1);
2763        }));
2764        tree.layout(teksilo_canvas::SizeProposal::exact(200.0, 100.0));
2765
2766        // Trip a rebuild of the composite — its child gets torn down &
2767        // rebuilt; node.handlers gets cleared and reset.
2768        tree.arena_mark_needs_rebuild_for_testing(id);
2769        tree.layout(teksilo_canvas::SizeProposal::exact(200.0, 100.0));
2770
2771        // Click through the composite; the externally-attached on_tap
2772        // must still be wired up.
2773        tree.click(id);
2774        assert_eq!(
2775            tap_count.get(),
2776            1,
2777            "externally-attached on_tap must survive a rebuild"
2778        );
2779    }
2780
2781    #[test]
2782    fn wrapped_composite_widget_still_builds_children() {
2783        let mut tree = WidgetTree::new();
2784        let root = tree.add(CompositeLeaf::new().on_tap(|_pos, _ctx| {}));
2785        tree.layout(teksilo_canvas::SizeProposal::exact(200.0, 100.0));
2786
2787        assert_eq!(tree.children(root).len(), 1);
2788    }
2789
2790    /// A widget that exposes both downcast hooks, like every widget a
2791    /// composing container reads its child's concrete type through.
2792    #[derive(Debug)]
2793    struct Reflective {
2794        marker: u32,
2795    }
2796
2797    impl Widget for Reflective {
2798        fn layout_response(
2799            &self,
2800            proposal: teksilo_canvas::SizeProposal,
2801            _ctx: &crate::widget::LayoutContext,
2802        ) -> crate::widget::LayoutResponse {
2803            proposal.resolve(0.0, 0.0).into()
2804        }
2805
2806        fn as_any(&self) -> Option<&dyn std::any::Any> {
2807            Some(self)
2808        }
2809
2810        fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
2811            Some(self)
2812        }
2813    }
2814
2815    /// Decorating a widget must not hide its concrete type from a parent that
2816    /// reads it. `as_any` was already forwarded; `as_any_mut` was not, so a
2817    /// container reading a child through the mutable hook (`MenuList` does, for
2818    /// mnemonics, the type-ahead label and radio grouping) silently saw nothing
2819    /// the moment any builder method was called on that child.
2820    #[test]
2821    fn both_downcast_hooks_see_through_the_handler_wrapper() {
2822        let mut wrapped = Reflective { marker: 7 }.focusable(true);
2823
2824        let seen = wrapped
2825            .as_any()
2826            .and_then(|a| a.downcast_ref::<Reflective>())
2827            .map(|r| r.marker);
2828        assert_eq!(seen, Some(7), "as_any must forward through the wrapper");
2829
2830        let seen_mut = wrapped
2831            .as_any_mut()
2832            .and_then(|a| a.downcast_mut::<Reflective>())
2833            .map(|r| r.marker);
2834        assert_eq!(
2835            seen_mut,
2836            Some(7),
2837            "as_any_mut must forward through the wrapper too"
2838        );
2839    }
2840
2841    // --- touch-action / pan-claim builder surfaces ---------------------
2842
2843    /// Surface 1: `HandlerSet`'s own builder methods set its fields
2844    /// directly — no arena involved.
2845    #[test]
2846    fn handler_set_surface_sets_touch_action_and_pan_claim() {
2847        let hs = HandlerSet::new()
2848            .touch_action(TouchAction::PAN_Y)
2849            .scroll_container(PanAxes::BOTH);
2850        assert_eq!(hs.touch_action, Some(TouchAction::PAN_Y));
2851        assert_eq!(
2852            hs.pan_claim,
2853            Some(PanClaim {
2854                axes: PanAxes::BOTH,
2855                devices: teksilo_tokens::PointerKindMask::DIRECT,
2856                kinetic: true,
2857            })
2858        );
2859    }
2860
2861    /// Surface 2: `WidgetWithHandlers<W>`'s inherent methods — reached by
2862    /// chaining a second builder call onto an already-wrapped widget, which
2863    /// resolves to the inherent impl rather than the blanket trait default.
2864    #[test]
2865    fn widget_with_handlers_surface_sets_touch_action_and_pan_claim() {
2866        let wrapped = crate::test_widgets::FillWidget::new()
2867            .gesture_dead_zone(false) // promotes to WidgetWithHandlers via the trait
2868            .touch_action(TouchAction::NONE) // now resolves to the inherent method
2869            .pan_claim(PanClaim::horizontal());
2870        assert_eq!(wrapped.handler_set.touch_action, Some(TouchAction::NONE));
2871        assert_eq!(wrapped.handler_set.pan_claim, Some(PanClaim::horizontal()));
2872    }
2873
2874    /// Surface 3: the blanket `WidgetBuilder` trait default method, called
2875    /// directly on a bare `Widget` and verified end-to-end through the tree
2876    /// (the widget-authoring call shape apps actually use). Read back
2877    /// through the two path folds themselves: for a root with no ancestors,
2878    /// `effective_touch_action` / `pan_candidates` reduce to exactly the
2879    /// node's own declaration, so this doubles as a sanity check on those
2880    /// folds' base case.
2881    #[test]
2882    fn widget_builder_surface_sets_the_node_fields() {
2883        let mut tree = WidgetTree::new();
2884        let id = tree.add(
2885            crate::test_widgets::FillWidget::new()
2886                .touch_action(TouchAction::PAN_X)
2887                .scroll_container(PanAxes::Y),
2888        );
2889        tree.layout(teksilo_canvas::SizeProposal::exact(100.0, 100.0));
2890
2891        assert_eq!(tree.effective_touch_action(id), TouchAction::PAN_X);
2892        assert_eq!(
2893            tree.pan_candidates(id, TouchAction::AUTO),
2894            vec![(
2895                id,
2896                PanClaim {
2897                    axes: PanAxes::Y,
2898                    devices: teksilo_tokens::PointerKindMask::DIRECT,
2899                    kinetic: true,
2900                }
2901            )]
2902        );
2903    }
2904}