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