Skip to main content

teksilo_core/
widget.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use teksilo_canvas::{Canvas, Point, Rect, Size, SizeProposal};
5
6use crate::accessibility::AccessNodeBuilder;
7use crate::widget_id::WidgetId;
8
9mod cursor;
10mod event_context;
11mod layout_context;
12mod paint_context;
13
14pub use cursor::CursorIcon;
15pub use event_context::EventContext;
16pub(crate) use event_context::{CursorRequest, GestureAct};
17pub use layout_context::{LayoutContext, StackAxis};
18pub use paint_context::{PaintContext, WidgetPlacement, WidgetTreeView};
19
20pub(crate) use event_context::{DismissScope, ShortcutMutation, TreeMutation};
21pub(crate) use layout_context::LayoutExtras;
22
23/// A child that is either pre-registered (ID) or waiting to be inserted.
24/// Used by the inline `child()` builder pattern: deferred children are stored
25/// inside the container and resolved recursively when `BuildContext::add()`
26/// inserts the container into the arena.
27pub enum PendingChild {
28    /// Already in the arena — use this ID directly.
29    Id(WidgetId),
30    /// Not yet in the arena — insert during resolution.
31    Deferred(Box<dyn Widget>),
32}
33
34impl std::fmt::Debug for PendingChild {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        match self {
37            PendingChild::Id(id) => write!(f, "PendingChild::Id({:?})", id),
38            PendingChild::Deferred(_) => f.write_str("PendingChild::Deferred(..)"),
39        }
40    }
41}
42
43/// A widget's reply to a parent's layout query.
44///
45/// Carries four quantities that together describe how the widget participates
46/// in a stack's space distribution along the layout's main axis:
47///
48/// - `size` — the widget's wanted/ideal size; the floor for **growth**.
49/// - `flex` — positive-slack **grow** weight. `0.0` = rigid (no claim on
50///   surplus); `> 0.0` = wants a share of surplus proportional to its weight.
51/// - `min` — the hard floor for **compression**. A parent must never shrink
52///   the widget below this. Defaults to `size` (i.e. "I do not shrink").
53/// - `shrink` — negative-slack **shrink** weight. `0.0` = will not compress
54///   (the widget overflows before it shrinks); `> 0.0` = absorbs a share of an
55///   over-constraint deficit proportional to its weight, down to `min`.
56///
57/// `flex` and `shrink` are independent — as in CSS flexbox (`flex-grow` vs
58/// `flex-shrink`), a widget may grow but not shrink, or shrink but not grow.
59/// Most widgets just return a `Size`; the `From<Size>` impl wraps it as fully
60/// rigid (`flex = 0`, `shrink = 0`, `min = size`). Grow-bearing widgets
61/// (`Spacer`, `Expand`) use [`LayoutResponse::flexible`]; shrink-bearing ones
62/// (`Shrinkable`, single-line `TextWidget`) use [`LayoutResponse::shrinkable`].
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct LayoutResponse {
65    pub size: Size,
66    pub flex: f32,
67    pub min: Size,
68    pub shrink: f32,
69}
70
71impl LayoutResponse {
72    pub const ZERO: Self = Self {
73        size: Size::ZERO,
74        flex: 0.0,
75        min: Size::ZERO,
76        shrink: 0.0,
77    };
78
79    /// A fully rigid response: wanted `size`, no growth, no compression
80    /// (`min == size`).
81    pub fn rigid(size: Size) -> Self {
82        Self {
83            size,
84            flex: 0.0,
85            min: size,
86            shrink: 0.0,
87        }
88    }
89
90    /// A grow-bearing response: wanted `size` with grow weight `flex`. Does
91    /// not shrink (`min == size`).
92    pub fn flexible(size: Size, flex: f32) -> Self {
93        Self {
94            size,
95            flex: flex.max(0.0),
96            min: size,
97            shrink: 0.0,
98        }
99    }
100
101    /// A shrink-bearing response: wanted `size`, compressible down to `min`
102    /// with shrink weight `shrink`. Does not grow (`flex == 0`). `min` is
103    /// clamped componentwise to be no larger than `size`.
104    pub fn shrinkable(size: Size, min: Size, shrink: f32) -> Self {
105        Self {
106            size,
107            flex: 0.0,
108            min: Size::new(min.width.min(size.width), min.height.min(size.height)),
109            shrink: shrink.max(0.0),
110        }
111    }
112
113    /// Builder: set the grow weight on an existing response.
114    pub fn with_flex(mut self, flex: f32) -> Self {
115        self.flex = flex.max(0.0);
116        self
117    }
118
119    /// Builder: set the shrink weight on an existing response.
120    pub fn with_shrink(mut self, shrink: f32) -> Self {
121        self.shrink = shrink.max(0.0);
122        self
123    }
124
125    /// Builder: set the compression floor (clamped componentwise ≤ `size`).
126    pub fn with_min(mut self, min: Size) -> Self {
127        self.min = Size::new(
128            min.width.min(self.size.width),
129            min.height.min(self.size.height),
130        );
131        self
132    }
133}
134
135impl From<Size> for LayoutResponse {
136    fn from(size: Size) -> Self {
137        Self {
138            size,
139            flex: 0.0,
140            min: size,
141            shrink: 0.0,
142        }
143    }
144}
145
146/// The full Widget trait for Level 2 (custom rendering) widgets.
147///
148/// # Adding a method here
149///
150/// A defaulted method added to this trait is **inert for every widget a builder
151/// method has touched** until the framework's same-node wrappers forward it.
152/// [`WidgetWithHandlers`](crate::widget_builder::WidgetWithHandlers) and the
153/// `TeksiBranch{,3,4}` sum types replace the widget at its own arena node, so an
154/// unforwarded method answers this default and the widget loses the behaviour
155/// silently — no compile error, and no test that drives the hook on a bare
156/// struct can see it. Those impls deny `clippy::missing_trait_methods` so the
157/// omission surfaces as a lint on them rather than as a defect in an app.
158pub trait Widget: std::fmt::Debug + std::any::Any {
159    /// Concrete type name of this widget (e.g.
160    /// `"teksilo_widgets::button::Button"`). The default implementation
161    /// resolves at the impl site via `std::any::type_name::<Self>()`,
162    /// so calls through `&dyn Widget` correctly dispatch to the
163    /// monomorphized fn for the concrete type — getting the
164    /// concrete name through the vtable without per-impl boilerplate.
165    ///
166    /// Used by [`crate::widget_tree::WidgetTree::widget_type_histogram`]
167    /// for the `widget.census` telemetry event. Custom
168    /// widgets that wrap their state in a generic struct may
169    /// override to give analytics a stable name independent of the
170    /// generic parameter.
171    fn type_name(&self) -> &'static str {
172        std::any::type_name::<Self>()
173    }
174
175    /// Compose child widgets. Called once after the widget is placed in the
176    /// arena, and again whenever the widget is marked for rebuild — a
177    /// `BindingLevel::Rebuild` binding, `rebuild_single_widget`, or a density
178    /// switch. A theme or locale switch does **not** rebuild: `set_theme` and
179    /// `set_locale` mark layout + paint dirty and leave the built subtree
180    /// standing, so anything derived from the theme or the locale must be read
181    /// per pass or bound to a signal rather than captured here.
182    /// Takes `&mut self` — store child IDs, signal handles, any state needed later.
183    /// Returns the list of root child IDs (empty for leaf widgets).
184    fn build(
185        &mut self,
186        _ctx: &mut crate::build_context::BuildContext,
187    ) -> Vec<crate::widget_id::WidgetId> {
188        Vec::new()
189    }
190
191    /// Respond to the parent's size proposal with this widget's wanted size,
192    /// grow/shrink weights, and compression floor (see [`LayoutResponse`]).
193    ///
194    /// Most widgets just return a `Size` (auto-converts via `From<Size>` to a
195    /// fully rigid response). Grow-bearing widgets (`Spacer`, `Expand`) return
196    /// a non-zero `flex`; shrink-bearing widgets (`Shrinkable`, single-line
197    /// `TextWidget`) return a non-zero `shrink` with a `min` floor.
198    ///
199    /// The parent honors `size` as a floor for growth and distributes positive
200    /// slack proportional to `flex`; when over-constrained it distributes the
201    /// deficit proportional to `shrink`, never below `min`.
202    ///
203    /// **Determinism / height-for-width contract.** This must be a *deterministic
204    /// function of the widget's state and the `proposal`*: two calls with the
205    /// same proposal in one layout pass must return the same value. The result
206    /// must be correct *for the proposal given* — in particular a
207    /// height-for-width widget queried with `{width: Some(w), height: None}`
208    /// must return its height *at width `w`*. The framework memoizes results per
209    /// `(widget, proposal)` within a pass (see
210    /// [`cacheable_layout`](Self::cacheable_layout)) to keep negotiation O(n).
211    ///
212    /// Side effects are permitted **as long as they are idempotent** — the cache
213    /// may skip them on a repeat query, so a side effect (e.g. snapshotting
214    /// measured state into a `Signal`) must be safe to run any number of times
215    /// ≥ 1 per pass and leave the same final state. Most measuring widgets
216    /// (`Collapse`, `SceneView`, inspector tabs) satisfy this with a guarded or
217    /// overwriting set. A side effect that must run on *every* call (e.g. a call
218    /// counter) is non-idempotent — opt out via `cacheable_layout`.
219    fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse;
220
221    /// Whether this widget's [`layout_response`](Self::layout_response) may be
222    /// memoized by the per-pass layout cache. Defaults to `true`.
223    ///
224    /// Override to `false` only when `layout_response` has a **non-idempotent**
225    /// side effect that must run on every call (a call counter, a one-shot
226    /// trigger). Idempotent side effects — the common case, e.g. overwriting a
227    /// measured size into a `Signal` — do **not** need to opt out: the cache may
228    /// skip a redundant identical-proposal repeat, but the value was already
229    /// written and the final state is correct. The debug inspector's
230    /// `BoundsTracker` opts out defensively (its whole-tree snapshot is the
231    /// payload, not a by-product of sizing).
232    fn cacheable_layout(&self) -> bool {
233        true
234    }
235
236    /// Position children within the allocated bounds.
237    ///
238    /// Called for **every active widget on every layout pass** — including
239    /// leaves, which receive an empty `children` slice. It is therefore also the
240    /// canonical *"here are your final, parent-assigned bounds"* hook, and the
241    /// only one that runs during layout: `layout_response` sees a *proposal*, not
242    /// the outcome, and `paint` runs too late for anything the renderer consumes
243    /// before it (a node-level transform scope, a text engine's viewport).
244    ///
245    /// A widget whose bounds feed such a thing must read them here, not in
246    /// `paint`. `SceneView` is the motivating case: it folds `bounds.origin` into
247    /// the view transform the render walker pushes *around* its subtree, so a
248    /// scene that learned its origin only at paint time drew its content offset
249    /// by `-bounds.origin` — an error that then scaled with zoom.
250    ///
251    /// **If you mutate interior state here, keep the write and its consequences
252    /// together.** This hook runs *before* `paint`, so writing a field that
253    /// `paint` later uses as a compare-then-act change detector will silently
254    /// blind that detector. (Both text engines were bitten: `place_children` set
255    /// the `viewport_width` that `paint` compared against, so `paint` concluded
256    /// "unchanged" and skipped the `engine.set_viewport` + relayout it owed.)
257    /// Route such writes through one idempotent helper that both hooks call.
258    ///
259    /// **Do not `Signal::set` here at [`BindingLevel::Relayout`] or
260    /// [`Rebuild`](crate::binding::BindingLevel::Rebuild).** This runs inside the
261    /// layout pass, so dirtying the tree from it re-enters layout. A plain
262    /// `Cell`/`RefCell` (what the colour-picker leaves use to cache their bounds
263    /// for hit-testing) or a `RepaintOnly` signal is fine.
264    ///
265    /// [`BindingLevel::Relayout`]: crate::binding::BindingLevel::Relayout
266    fn place_children(
267        &self,
268        _bounds: Rect,
269        _proposal: SizeProposal,
270        _children: &mut [WidgetPlacement],
271        _ctx: &LayoutContext,
272    ) {
273        // Leaf widgets have no children to place.
274    }
275
276    /// Draw the widget's visual representation.
277    fn paint(&self, _bounds: Rect, _canvas: &mut Canvas, _ctx: &PaintContext) {
278        // Default: nothing to paint (layout-only containers).
279    }
280
281    /// Whether this widget wants its [`after_paint`](Self::after_paint)
282    /// hook to fire each frame. Returning `false` (the default) saves
283    /// a virtual call per widget per frame for the vast majority of
284    /// widgets that don't aggregate descendant geometry.
285    ///
286    /// Same opt-in pattern as
287    /// [`wants_descendant_redirects`](Self::wants_descendant_redirects).
288    fn wants_after_paint(&self) -> bool {
289        false
290    }
291
292    /// Called once per frame after this widget's subtree has finished
293    /// painting. Receives a read-only view of the layout-resolved
294    /// arena so a parent can read its descendants' final bounds —
295    /// e.g. `TitleBar` aggregates its drag region and control-button
296    /// rects into a single `HitRegions` payload for the Windows
297    /// backend's `WM_NCHITTEST`.
298    ///
299    /// Walk order is depth-first **post**-order: a parent's
300    /// `after_paint` runs after every descendant's `paint` has
301    /// committed.
302    ///
303    /// Default: empty. Only widgets that override
304    /// [`wants_after_paint`](Self::wants_after_paint) and return `true`
305    /// see this called.
306    fn after_paint(&self, _view: &WidgetTreeView<'_>, _ctx: &PaintContext) {}
307
308    /// Whether this widget wants its [`post_paint`](Self::post_paint)
309    /// hook to fire each frame. Returning `false` (the default) saves a
310    /// virtual call per widget per frame for the vast majority of widgets
311    /// that don't draw a foreground over their children.
312    ///
313    /// Same opt-in pattern as [`wants_after_paint`](Self::wants_after_paint).
314    fn wants_post_paint(&self) -> bool {
315        false
316    }
317
318    /// Draw a foreground layer *over* this widget's children.
319    ///
320    /// The normal [`paint`](Self::paint) emits a widget's draws *before*
321    /// its children — a backdrop. `post_paint` emits *after* the entire
322    /// child subtree, so its draws land on top. This is the supported way
323    /// for a composing widget to paint over its own descendants:
324    /// inset shadows, a focus ring that must overlay content, a scrim, or
325    /// `SceneView`'s "over" lightweight band (selection lasso, highlighted
326    /// connectors).
327    ///
328    /// Runs inside the same clip / transform / opacity / blur scopes as
329    /// the widget and its children, so a foreground decoration pans,
330    /// scales and clips consistently with the subtree it covers. It is
331    /// paint-only — no hit-testing and no accessibility node; for
332    /// interactive overlays that must escape the widget's bounds, use the
333    /// overlay system instead.
334    ///
335    /// Default: empty. Only widgets that override
336    /// [`wants_post_paint`](Self::wants_post_paint) and return `true` see
337    /// this called.
338    fn post_paint(&self, _bounds: Rect, _canvas: &mut Canvas, _ctx: &PaintContext) {}
339
340    /// Declare this widget's accessibility identity.
341    fn accessibility(&self, _builder: &mut AccessNodeBuilder) {}
342
343    /// Whether this widget wants the AT walker to consult its
344    /// [`a11y_redirect_descendant`](Self::a11y_redirect_descendant)
345    /// hook for *every* descendant during AT tree emission, not
346    /// just its direct arena children.
347    ///
348    /// Returning `true` opts this widget into ancestor-chain
349    /// queries: as the walker iterates each descendant's parent
350    /// to decide where the descendant's `NodeId` lands in the AT
351    /// tree, it walks up the arena from that parent and asks
352    /// every ancestor with this flag set. First `Some(_)` wins
353    /// (closest ancestor takes priority — same precedence as a
354    /// CSS-like cascade).
355    ///
356    /// Returning `false` (the default) makes the walker pay the
357    /// O(depth) ancestor walk only for trees that genuinely need
358    /// it. Only opt in if your widget actively places
359    /// non-direct-child descendant `NodeId`s in its own
360    /// `accessibility()` emission — `teksilo_scene::SceneView` is
361    /// the canonical example.
362    ///
363    /// Default: `false`.
364    fn wants_descendant_redirects(&self) -> bool {
365        false
366    }
367
368    /// Whether this widget decides, on every layout pass, which of its
369    /// children exist at all.
370    ///
371    /// Opting in changes what [`place_children`](Self::place_children)
372    /// receives and what the framework does with it:
373    ///
374    /// * the `children` slice carries **every** child, dormant ones included,
375    ///   rather than only the active ones — otherwise a container could never
376    ///   ask for a child back, having parked it;
377    /// * each [`WidgetPlacement::dormant`] arrives pre-set to that child's
378    ///   current state, and whatever the widget leaves there is applied: a
379    ///   child newly cleared is woken and laid out **in the same pass**, a
380    ///   child newly set is parked after the pass, with focus revalidated
381    ///   behind it.
382    ///
383    /// The cost of opting in is one iteration per child per pass, which is why
384    /// it is a choice rather than the rule: an ordinary container pays for its
385    /// active children only.
386    ///
387    /// This exists for containers that hold far more content than they show —
388    /// a scene viewport, a canvas, a map — where the off-screen half is not
389    /// merely invisible but should not be *reachable*: a card 90 000 px away
390    /// is a Tab stop between two visible ones and a node an assistive client
391    /// is offered. Collapsing its `size` to zero answers neither, because a
392    /// zero-size widget is still alive.
393    ///
394    /// A container that only ever hides one branch at a time wants
395    /// [`BuildContext::visible_when`](crate::build_context::BuildContext::visible_when)
396    /// instead: a gate per branch is cheaper than a pass per child, and that
397    /// is the shape of `Switcher`, a popover or a collapsed panel.
398    ///
399    /// Default: `false`.
400    fn culls_children(&self) -> bool {
401        false
402    }
403
404    /// Optional redirection hook for AT-tree placement of a child.
405    ///
406    /// The accessibility walker consults every ancestor that opts
407    /// in via
408    /// [`wants_descendant_redirects`](Self::wants_descendant_redirects),
409    /// starting at the child's immediate arena parent and walking
410    /// up to the root. An ancestor whose flag is `false` is
411    /// skipped without its hook ever being called, the immediate
412    /// parent included, and the walk carries on past it. First
413    /// `Some(_)` wins, scanned bottom-up (closest opted-in
414    /// ancestor takes priority). Returning
415    /// `Some(_)` tells the walker that this widget has *already*
416    /// placed `descendant`'s `NodeId` somewhere else (typically
417    /// under a synthetic node it emitted in its own
418    /// `accessibility()` call), and the walker should NOT add it
419    /// to its arena parent's children list.
420    ///
421    /// The returned `NodeId` is informational — it identifies the
422    /// new logical parent in case the walker wants to bookkeep
423    /// (e.g., dedupe). The walker does not validate that
424    /// `descendant`'s NodeId is actually in that target's children
425    /// list; it is the implementing widget's responsibility to
426    /// have placed it there during its `accessibility()` emission
427    /// (e.g. via `AccessNodeBuilder::attach_scene_child_under`).
428    ///
429    /// Used by `teksilo_scene::SceneView` to graft heavyweight
430    /// `Widget` items into an app-declared logical AT tree.
431    /// Other layered containers can adopt the same pattern.
432    ///
433    /// Default: `None` — no redirection.
434    fn a11y_redirect_descendant(
435        &self,
436        _self_id: WidgetId,
437        _descendant: WidgetId,
438    ) -> Option<accesskit::NodeId> {
439        None
440    }
441
442    /// Suggest an accessible title to an enclosing container that
443    /// wraps this widget as content — typically a modal / dialog
444    /// shell that wants to propagate the inner content's visible
445    /// title as the shell's own accessible name.
446    ///
447    /// Example: `ModalContainer` wraps a `DialogContent`. The
448    /// container owns the `Role::Dialog` node and needs a name;
449    /// `DialogContent` overrides this method to return its own
450    /// `title` string. The container queries this on its pending
451    /// content at build time and uses the result if set.
452    ///
453    /// Default: `None` — widgets that don't carry a natural
454    /// title don't need to override.
455    fn accessible_title_hint(&self) -> Option<String> {
456        None
457    }
458
459    /// The widget that *paints* this one's title, when it has one.
460    ///
461    /// Preferred over [`accessible_title_hint`](Self::accessible_title_hint)
462    /// where both are available: an enclosing container points at the
463    /// title node through a `labelled_by` relation instead of copying
464    /// its string, so the title keeps its own node and stays reviewable
465    /// by character rather than being announced only as part of the
466    /// container's name.
467    ///
468    /// Queried right after the content is mounted — `build()` runs
469    /// eagerly on insertion, so the title node already exists by then.
470    ///
471    /// Default: `None`.
472    fn accessible_title_node(&self) -> Option<crate::widget_id::WidgetId> {
473        None
474    }
475
476    /// Optional hint that directs initial focus to a specific
477    /// descendant when this widget is the root of a deferred-built
478    /// modal surface.
479    ///
480    /// The modal presentation pipeline consults this after building
481    /// the content subtree, in priority order: the caller's
482    /// `ModalRequest::focus_target` → the content widget's
483    /// `initial_focus_hint` → `first_focusable_descendant`.
484    /// `MessageBox` overrides this to return the widget id of its
485    /// configured default button, so platform-native button orderings
486    /// (Cancel-left + Default-right-but-focused) work without
487    /// forcing the default button to be the first focusable
488    /// descendant in tree-walk order.
489    ///
490    /// Default: `None` — widgets that don't need to direct initial
491    /// focus to a non-first-focusable descendant don't override.
492    fn initial_focus_hint(&self) -> Option<WidgetId> {
493        None
494    }
495
496    /// Which descendant a keyboard request for a context menu should target.
497    ///
498    /// The context-menu key (and Shift+F10) opens the menu of the **focused**
499    /// widget. For a data view that is the wrong node: `ListView`, `TreeView`,
500    /// `TableView`, `TreeTableView` and `GridView` are focusable as a whole and
501    /// their rows deliberately are not — the container owns focus and
502    /// `set_selected` is what tells assistive technology which row is current
503    /// (see `list_item_a11y`). Without this hook the chord would open the
504    /// *list's* menu rather than the selected row's, in exactly the widget
505    /// family where a per-row menu matters most.
506    ///
507    /// Return the widget id of the row (or cell, or tile) the menu should be
508    /// about. The dispatcher then walks up from there, so a view whose rows
509    /// carry no factory of their own still finds the container's.
510    ///
511    /// Default: `None` — the focused widget is the target, which is right for
512    /// every widget that is itself the thing the user is pointing at.
513    fn context_menu_key_target(&self) -> Option<WidgetId> {
514        None
515    }
516
517    /// Return the child widget IDs that this widget manages.
518    fn children(&self) -> Vec<WidgetId> {
519        Vec::new()
520    }
521
522    /// Optional override for the child ORDER presented to assistive
523    /// technology, when it must differ from the paint / z-order child
524    /// order returned by [`children`](Self::children).
525    ///
526    /// Return `None` (the default) to let the accessibility walker use the
527    /// arena's child order — correct for almost every widget. Return
528    /// `Some(ids)` to reorder (or restrict) how children appear in the AT
529    /// tree and in the linear Tab reading order, WITHOUT affecting layout or
530    /// paint. `TableView` / `TreeTableView` use this to read the header
531    /// before the body rows even though they build the body first so it
532    /// paints beneath the header (WCAG 1.3.2 Meaningful Sequence).
533    fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
534        None
535    }
536
537    /// Downcast hook. Default implementation returns `None`; concrete
538    /// widgets override with `Some(self)` when they want to expose
539    /// their concrete type to test-level introspection or reflection.
540    /// The trait already bounds on `std::any::Any` so concrete types
541    /// satisfy the `'static` requirement.
542    fn as_any(&self) -> Option<&dyn std::any::Any> {
543        None
544    }
545
546    /// Mutable counterpart of [`as_any`](Self::as_any). Default
547    /// returns `None`; widgets that want to expose mutable state to
548    /// tests (e.g. so a test can mutate a `Scene` inside a
549    /// `SceneView` post-layout) override with `Some(self)`. Should
550    /// follow the same opt-in pattern as `as_any`: only widgets
551    /// that opt into `&` introspection should opt into `&mut`.
552    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
553        None
554    }
555
556    /// Whether this widget clips its children to its bounds.
557    fn clips_children(&self) -> bool {
558        false
559    }
560
561    /// The rectangle (in **absolute tree coordinates**) that best *represents*
562    /// this widget when the framework reveals it into an ancestor scroll area on
563    /// focus gain. Returning `None` (the default) reveals the widget's whole
564    /// bounds — correct for most controls.
565    ///
566    /// A widget that can be much taller than a viewport — a `RichTextEditor`
567    /// grown inside a page `ScrollArea`, a `ListView` / `TreeView` taller than
568    /// its scroller — should override this to return the sub-rectangle the user
569    /// actually cares about (the caret line, the selected row). Otherwise
570    /// [`scroll_focused_into_view`](crate::widget_tree::WidgetTree) reveals the
571    /// *entire* box, which for a tall widget scrolls the page to its bottom on a
572    /// click that only meant to place the caret near the top. The returned rect
573    /// feeds the same ancestor-only `scroll_rect_into_view` engine the caret /
574    /// selection follow uses (the focused widget itself is excluded), so it
575    /// never double-scrolls against the widget's own internal follow.
576    ///
577    /// `bounds` is this widget's current absolute rectangle as the arena stores
578    /// it, so an override can place its interior rect without depending on a
579    /// paint-set origin.
580    fn focus_reveal_rect(&self, _bounds: Rect) -> Option<Rect> {
581        None
582    }
583
584    /// Whether the point lies inside this widget's *actual* shape, not
585    /// just its rectangular bounds. Consulted by hit-testing right after
586    /// the bounds check: returning `false` for a point that *is* inside
587    /// the bounding box makes the widget transparent to the click there,
588    /// so it **falls through** to whatever sibling is painted underneath
589    /// (the same machinery as a fully pass-through node, but shape-aware).
590    ///
591    /// Both arguments are in the widget's bounds space: `local_point` is
592    /// the point being tested and `bounds` is this widget's rectangle, so
593    /// a non-rectangular widget can test the point against its silhouette.
594    ///
595    /// The default returns `true` for any in-bounds point (a plain
596    /// rectangle), so every existing widget is unaffected. Override for
597    /// irregular shapes — an ellipse / cloud scene node, a circular
598    /// handle — so a click lands on the shape you see, not its bounding
599    /// box, and clicks in the transparent corners reach the node beneath.
600    /// The lightweight tier answers the same question from a *value* —
601    /// `SceneItem::shape` returns an `ItemShape` that every query in
602    /// `teksilo-scene` derives from — rather than from a predicate. The two
603    /// are deliberately not the same shape of API and deliberately not the
604    /// same name: a widget is hit-tested by the arena, one point at a time,
605    /// with its bounds already in hand.
606    fn hit_shape(&self, _local_point: Point, _bounds: Rect) -> bool {
607        true
608    }
609
610    /// Veto a hit on one of this widget's **direct children**, per point.
611    ///
612    /// Called during the arena's reverse-sibling walk, once per child, before
613    /// the recursion descends into it. Returning `false` makes the walk fall
614    /// through to the next sibling exactly as a [`hit_shape`](Self::hit_shape)
615    /// rejection on that child would, so the point can land on a lower sibling
616    /// or, finally, on this widget itself.
617    ///
618    /// `point` is in the space this widget's
619    /// [`place_children`](Self::place_children) writes — for an ordinary node
620    /// that is the same absolute space its own bounds are in; for a
621    /// content-transform node (a `SceneView`) it is content coordinates, the
622    /// point already mapped through the inverse of the content transform.
623    ///
624    /// # What this is for
625    ///
626    /// A widget that owns a **second picking system over the same area** — a
627    /// `SceneView`'s lightweight items, a chart's overlay marks, a terminal's
628    /// link layer. Without it the two systems answer independently: the widget
629    /// can paper over the disagreement inside one handler, but press feedback,
630    /// focus-on-release, the touch hold route, the cursor and drag all resolve
631    /// from the arena's answer, so five of the six stay wrong.
632    ///
633    /// It is **not** a replacement for
634    /// [`hit_transparent`](crate::widget_builder::HandlerSet::hit_transparent),
635    /// which is the right tool for a decorative overlay: that is a per-*node*
636    /// declaration ("I never absorb a press"), set from the outside by whoever
637    /// builds the node, and it cannot express "reject this child here and
638    /// accept it one pixel over". This is the per-*point* question, answered by
639    /// the parent that knows why.
640    ///
641    /// # Contract
642    ///
643    /// Must be **pure and cheap**: it runs once per child per hit test, and a
644    /// hit test runs on every pointer sample. It must not mutate anything the
645    /// walk can observe, and — because it runs inside the router — it must not
646    /// re-enter any `RefCell` a handler might already hold. A widget that
647    /// answers from a per-layout snapshot should memoise per walk; the default
648    /// returns `true`, so a widget that does not override it pays one
649    /// devirtualizable call per child.
650    fn accepts_child_hit(&self, _child: WidgetId, _point: Point) -> bool {
651        true
652    }
653
654    /// How far **outside** its own bounds this widget still absorbs a press,
655    /// per edge, for the pointer that is asking.
656    ///
657    /// Consulted **inside** the exact hit test: within one parent, children
658    /// that declare an outset are tested against their outset bounds *before*
659    /// the ordinary reverse-sibling walk, so a 6 dp splitter gutter wins over
660    /// the panes it overlaps instead of losing to whichever pane is painted on
661    /// top. This is the mechanism for a thin **grip**, and the only one of the
662    /// three that can beat a competing target.
663    ///
664    /// Three rules make it safe to add to a widget that already works:
665    ///
666    /// * **Hit-only.** No layout moves, nothing repaints differently, and a
667    ///   Compact build renders byte for byte as it did. The outset exists
668    ///   between the pointer and the arena and nowhere else.
669    /// * **It never escapes the parent.** The recursion has already tested the
670    ///   parent's own bounds before it looks at any child, so an outset can
671    ///   only ever claim space the parent already owns — including through a
672    ///   `clips_children` ancestor, whose rectangle gated the descent.
673    /// * **Zero for a precise pointer** unless the widget deliberately says
674    ///   otherwise. A mouse cursor's hot-spot is exact and occludes nothing, so
675    ///   widening its targets steals clicks. Check
676    ///   `kind.is_direct()` (or accept every kind explicitly, as a control with
677    ///   a genuinely undersized mouse grip may) before returning anything
678    ///   non-zero.
679    ///
680    /// The insets are **reading-order**: `leading` is the left edge in an LTR
681    /// UI and the right edge in an RTL one. The default returns
682    /// [`EdgeInsets::ZERO`](teksilo_canvas::EdgeInsets::ZERO), so every existing
683    /// widget is unaffected.
684    ///
685    /// A grip's conventional value is `9 dp` for a direct pointer and `0 dp`
686    /// for a precise one — enough to lift a 6 dp gutter to a 24 dp target.
687    fn hit_outset(
688        &self,
689        _kind: teksilo_tokens::PointerKind,
690        _tokens: &teksilo_tokens::InputTokens,
691    ) -> teksilo_canvas::EdgeInsets {
692        teksilo_canvas::EdgeInsets::ZERO
693    }
694
695    /// This widget's own say in the *miss-only* slop pass, overriding the
696    /// density default for its node.
697    ///
698    /// Third link of the precedence chain — `no_hit_slop` beats a node-level
699    /// `.hit_slop(..)`, which beats this, which beats
700    /// [`HitSlop::for_pointer`]. Return [`HitSlop::NONE`] to opt a widget out
701    /// of re-attribution entirely, or a larger `up_to` to say that a control
702    /// deserves topping up further than the density asks.
703    ///
704    /// `None` (the default) means "no opinion — use the density default".
705    ///
706    /// [`HitSlop::for_pointer`]: crate::pointer::hit_slop::HitSlop::for_pointer
707    /// [`HitSlop::NONE`]: crate::pointer::hit_slop::HitSlop::NONE
708    fn hit_slop(
709        &self,
710        _kind: teksilo_tokens::PointerKind,
711        _tokens: &teksilo_tokens::InputTokens,
712    ) -> Option<crate::pointer::hit_slop::HitSlop> {
713        None
714    }
715
716    /// How far a *missed* press is from this widget's actual silhouette, in the
717    /// widget's own bounds space.
718    ///
719    /// The key to the miss-only slop pass: once the exact pass has found
720    /// nothing eligible, the framework asks every nearby node how far away it
721    /// really is and re-attributes the press to the closest one still inside
722    /// its earned outset.
723    ///
724    /// The default measures to the bounding rectangle, which is right for the
725    /// rectangular majority. A **round or wedge** control overrides it beside
726    /// its existing [`hit_shape`](Self::hit_shape) so the slop follows the
727    /// shape the user aimed at rather than the box it was laid out in — a
728    /// press past the corner of a radio dot's box is further from the dot than
729    /// a press past its edge, and should lose to a neighbour that is nearer.
730    ///
731    /// Returning `None` withdraws the widget from the pass altogether, which is
732    /// the shape-level equivalent of `no_hit_slop`.
733    ///
734    /// This is **never** consulted by the exact pass, so overriding it cannot
735    /// change where an ordinary click lands.
736    fn hit_distance(&self, local_point: Point, bounds: Rect) -> Option<f32> {
737        Some(crate::pointer::hit_slop::rect_distance(bounds, local_point))
738    }
739
740    /// The interactive sub-regions this widget **paints inside its own single
741    /// node** — a scroll bar's thumb, a slider's knob, a header cell's filter
742    /// affordance.
743    ///
744    /// Reporting only: implementing it changes no layout and no hit test by
745    /// itself. It exists because a control that draws several targets on one
746    /// canvas is otherwise opaque — the router cannot route a coarse press to
747    /// the nearest one, and the target-conformance audit cannot see that any of
748    /// them exists, let alone that it clears the floor.
749    ///
750    /// `bounds` is this widget's current rectangle, and the returned rects are
751    /// in the same space. Build them with
752    /// [`partition_targets`](crate::partition::partition_targets) where the
753    /// split is a horizontal division, so the geometry the widget paints and
754    /// the geometry it reports cannot drift apart.
755    ///
756    /// The default returns an empty list: a widget whose node *is* its target
757    /// has nothing to add.
758    fn target_regions(&self, _bounds: Rect) -> Vec<crate::partition::TargetRegion> {
759        Vec::new()
760    }
761
762    /// How `rebuild_single_widget` treats this widget's existing children
763    /// when re-running its `build()`.
764    ///
765    /// **`false` (default) — re-derive.** Rebuild is "tear down and
766    /// reconstruct": every old child subtree is destroyed up front, then
767    /// `build()` produces a fresh set. The right semantic for data-driven
768    /// widgets like `Repeater` / `ListView` that rebuild their children from
769    /// current model state with fresh `WidgetId`s. A `false` widget must NOT
770    /// re-attach an old child id — it has already been destroyed.
771    ///
772    /// **`true` — reconcile.** `build()` re-attaches (by id) the children it
773    /// keeps and drops the rest. The framework keeps every re-attached child's
774    /// subtree intact — focus, scroll offset, text contents, signal
775    /// subscriptions all survive — and destroys only the old children the new
776    /// build dropped *and* did not re-parent elsewhere. This is the mode for
777    /// widgets that memoize stateful children across rebuilds:
778    ///
779    /// * `Switcher` keeps every mounted page alive so switching tabs doesn't
780    ///   wipe the inactive pages' state.
781    /// * `SceneView` re-pushes the same heavyweight scene-widget ids each
782    ///   rebuild (draining drag-to-move / marquee commits) — they must stay
783    ///   attached or the cards "disappear" on every drag end.
784    /// * `TabWidget` / `DockingLayout` / `CompositeTooltip` re-attach memoized
785    ///   panes / a one-shot body widget that cannot be reconstructed.
786    /// * `MenuBar` re-derives its menu triggers fresh each build (the model may
787    ///   have changed — the reconcile reaps the superseded ones) while keeping
788    ///   its memoized leading/trailing slot widgets, so a stateful slot control
789    ///   survives a model-version rebuild.
790    ///
791    /// The reconcile follows **authoritative parent pointers**, so a kept
792    /// subtree that `build()` re-parents *out* of a dropped sibling and into
793    /// the new tree survives — it is not swept via the dropped sibling's now
794    /// stale `children` list. Dropped children are genuinely destroyed (state
795    /// unmounted, arena slots freed), not left as stranded, still-active
796    /// orphans.
797    fn preserves_children_on_rebuild(&self) -> bool {
798        false
799    }
800
801    /// Whether this widget, used as tooltip content, currently has anything
802    /// worth showing.
803    ///
804    /// Consulted by `WidgetTree` just before a dwell matures into an overlay.
805    /// Returning `false` cancels the show — the anchor simply has no tooltip
806    /// this time — so a blank or unresolved string does not pop an empty
807    /// chromed bubble, which reads as a rendering fault rather than as
808    /// "nothing to say here".
809    ///
810    /// Defaults to `true`: content that hosts an arbitrary widget tree (a
811    /// chart, a progress row) is meaningful without any text, and a custom
812    /// content widget must never be suppressed by a check it did not opt into.
813    /// Only widgets whose *whole* payload is a string — `TooltipWidget` — have
814    /// a well-defined notion of being empty.
815    fn tooltip_has_content(&self) -> bool {
816        true
817    }
818
819    /// Declare the rebindable keyboard shortcuts this widget exposes,
820    /// *without* installing handlers. The framework calls this at
821    /// arena insertion time (before `build()`) and at certain lazy
822    /// boundaries (e.g. `Switcher` walks declarations on its
823    /// not-yet-mounted `Pending` slots), so settings UIs and the
824    /// `ShortcutRegistry` see the keystrokes the moment the owning
825    /// container mounts — even if `build()` hasn't run.
826    ///
827    /// Pair this with `BuildContext::register_shortcut` in `build()`
828    /// to install the matching `on_activate` handler: the build-time
829    /// registration *upserts* the declared entry, preserving any user
830    /// override and the declared keystrokes while attaching the
831    /// closure that actually fires.
832    ///
833    /// The returned shortcuts may omit `on_activate` (a metadata-only
834    /// declaration). When matched at dispatch time without a
835    /// registered handler, the framework synthesizes a no-parameter
836    /// intent from the shortcut's id — same path as a build-time
837    /// registration with `on_activate: None`.
838    ///
839    /// Default: empty (no declared shortcuts).
840    fn declare_shortcuts(&self) -> Vec<crate::shortcut::Shortcut> {
841        Vec::new()
842    }
843
844    /// Extract attached handler set from a `WidgetWithHandlers` wrapper.
845    /// Called during arena insertion to transfer handlers to the `WidgetNode`.
846    /// Default: returns `None` (no attached handlers).
847    fn take_handler_set(&mut self) -> Option<crate::widget_builder::HandlerSet> {
848        None
849    }
850}
851
852/// A boxed widget is a widget.
853///
854/// Without this, `Box<dyn Widget>` is the one widget-shaped value that cannot
855/// go where a widget goes: `.child(..)`, a `Vec` of children, a `match` arm.
856/// 238 functions in `teksilo-widgets` alone return it, the `teksu!` macro's own
857/// over-four-arms advice recommends it, and only two containers in the whole
858/// catalog (`Switcher`, `Cycle`) shipped a `child_boxed` to take it. Every
859/// other call site had to invent an adapter widget, which costs a real arena
860/// node per use.
861///
862/// Every method forwards to the inner widget, so the box is invisible to the
863/// arena: it adds no node, no layout pass and no AT element. In particular
864/// `as_any` / `as_any_mut` forward, so `EventContext::with_widget_mut::<W>`
865/// downcasts to the widget that was boxed rather than to the box.
866/// `#[deny(clippy::missing_trait_methods)]` for the reason the trait's own
867/// header gives: the arena holds `Box<dyn Widget>`, so a call on a node
868/// resolves to *this* impl and not to the vtable. A method left out here
869/// answers with the trait default for every widget in the tree, the
870/// widget's own override is never reached, and nothing fails to compile —
871/// which is exactly how `accepts_child_hit` and `culls_children` went
872/// missing when this impl and those two methods were written on separate
873/// branches and merged cleanly.
874#[deny(clippy::missing_trait_methods)]
875impl<W: Widget + ?Sized> Widget for Box<W> {
876    fn type_name(&self) -> &'static str {
877        (**self).type_name()
878    }
879
880    fn build(
881        &mut self,
882        ctx: &mut crate::build_context::BuildContext,
883    ) -> Vec<crate::widget_id::WidgetId> {
884        (**self).build(ctx)
885    }
886
887    fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse {
888        (**self).layout_response(proposal, ctx)
889    }
890
891    fn cacheable_layout(&self) -> bool {
892        (**self).cacheable_layout()
893    }
894
895    fn place_children(
896        &self,
897        bounds: Rect,
898        proposal: SizeProposal,
899        children: &mut [WidgetPlacement],
900        ctx: &LayoutContext,
901    ) {
902        (**self).place_children(bounds, proposal, children, ctx)
903    }
904
905    fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
906        (**self).paint(bounds, canvas, ctx)
907    }
908
909    fn wants_after_paint(&self) -> bool {
910        (**self).wants_after_paint()
911    }
912
913    fn after_paint(&self, view: &WidgetTreeView<'_>, ctx: &PaintContext) {
914        (**self).after_paint(view, ctx)
915    }
916
917    fn wants_post_paint(&self) -> bool {
918        (**self).wants_post_paint()
919    }
920
921    fn post_paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
922        (**self).post_paint(bounds, canvas, ctx)
923    }
924
925    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
926        (**self).accessibility(builder)
927    }
928
929    fn wants_descendant_redirects(&self) -> bool {
930        (**self).wants_descendant_redirects()
931    }
932
933    fn a11y_redirect_descendant(
934        &self,
935        self_id: WidgetId,
936        descendant: WidgetId,
937    ) -> Option<accesskit::NodeId> {
938        (**self).a11y_redirect_descendant(self_id, descendant)
939    }
940
941    fn accessible_title_hint(&self) -> Option<String> {
942        (**self).accessible_title_hint()
943    }
944
945    fn accessible_title_node(&self) -> Option<crate::widget_id::WidgetId> {
946        (**self).accessible_title_node()
947    }
948
949    fn initial_focus_hint(&self) -> Option<WidgetId> {
950        (**self).initial_focus_hint()
951    }
952
953    fn context_menu_key_target(&self) -> Option<WidgetId> {
954        (**self).context_menu_key_target()
955    }
956
957    fn children(&self) -> Vec<WidgetId> {
958        (**self).children()
959    }
960
961    fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
962        (**self).accessibility_children()
963    }
964
965    fn as_any(&self) -> Option<&dyn std::any::Any> {
966        (**self).as_any()
967    }
968
969    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
970        (**self).as_any_mut()
971    }
972
973    fn clips_children(&self) -> bool {
974        (**self).clips_children()
975    }
976
977    fn focus_reveal_rect(&self, bounds: Rect) -> Option<Rect> {
978        (**self).focus_reveal_rect(bounds)
979    }
980
981    fn hit_shape(&self, local_point: Point, bounds: Rect) -> bool {
982        (**self).hit_shape(local_point, bounds)
983    }
984
985    fn hit_outset(
986        &self,
987        kind: teksilo_tokens::PointerKind,
988        tokens: &teksilo_tokens::InputTokens,
989    ) -> teksilo_canvas::EdgeInsets {
990        (**self).hit_outset(kind, tokens)
991    }
992
993    fn hit_slop(
994        &self,
995        kind: teksilo_tokens::PointerKind,
996        tokens: &teksilo_tokens::InputTokens,
997    ) -> Option<crate::pointer::hit_slop::HitSlop> {
998        (**self).hit_slop(kind, tokens)
999    }
1000
1001    fn hit_distance(&self, local_point: Point, bounds: Rect) -> Option<f32> {
1002        (**self).hit_distance(local_point, bounds)
1003    }
1004
1005    fn accepts_child_hit(&self, child: crate::widget_id::WidgetId, point: Point) -> bool {
1006        (**self).accepts_child_hit(child, point)
1007    }
1008
1009    fn culls_children(&self) -> bool {
1010        (**self).culls_children()
1011    }
1012
1013    fn target_regions(&self, bounds: Rect) -> Vec<crate::partition::TargetRegion> {
1014        (**self).target_regions(bounds)
1015    }
1016
1017    fn preserves_children_on_rebuild(&self) -> bool {
1018        (**self).preserves_children_on_rebuild()
1019    }
1020
1021    fn tooltip_has_content(&self) -> bool {
1022        (**self).tooltip_has_content()
1023    }
1024
1025    fn declare_shortcuts(&self) -> Vec<crate::shortcut::Shortcut> {
1026        (**self).declare_shortcuts()
1027    }
1028
1029    fn take_handler_set(&mut self) -> Option<crate::widget_builder::HandlerSet> {
1030        (**self).take_handler_set()
1031    }
1032}