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