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