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    /// The descendant whose accessibility node stands for this widget.
497    ///
498    /// Some composites keep everything an assistive technology reads on one
499    /// inner widget. A `SpinBox`'s editing field holds the focus, the caret,
500    /// the text and the value, so the field is the node a screen reader lands
501    /// on, and it is the node that has to carry the spin box's name and its
502    /// spin semantics. The composite's own node is then structure, and says
503    /// so with `Role::GenericContainer`, which the presentational pass
504    /// collapses.
505    ///
506    /// What remains is that an application can only reach the composite. A
507    /// `FormLayout` names it with `labelled_by`, an application gives it
508    /// `.access_label(..)`, `access_described_by` or a tooltip, all on the
509    /// composite's id, and all of that would land on a node no platform
510    /// adapter exposes. Returning `Some(inner)` makes the walker apply
511    /// everything attached to this widget (its builder overrides, its
512    /// relations, the tooltip it owns) to `inner`'s node instead, after
513    /// `inner`'s own, so the application keeps the last word. A relation that
514    /// names this widget is pointed at `inner`.
515    ///
516    /// Focus follows the same rule. An editor takes focus and the keys on its
517    /// own widget and keeps its text on a body inside it that is not
518    /// focusable; a reader reads the node an update names as focus when it
519    /// arrives, and the Linux adapter reports a caret move only on that node.
520    /// So while this widget holds keyboard focus, the update names `inner`'s
521    /// node as the focus, and an assistive `Focus` on `inner`, when `inner` is
522    /// not focusable, gives the keyboard to this widget.
523    ///
524    /// Only a live, strict descendant counts, and only while the walk reaches
525    /// it: this widget and every widget between the two walked normally,
526    /// neither excluded nor merged. Anything else is ignored and the overrides
527    /// stay where they were attached.
528    ///
529    /// Default: `None`.
530    fn accessibility_proxy(&self) -> Option<WidgetId> {
531        None
532    }
533
534    /// Which descendant a keyboard request for a context menu should target.
535    ///
536    /// The context-menu key (and Shift+F10) opens the menu of the **focused**
537    /// widget. For a data view that is the wrong node: `ListView`, `TreeView`,
538    /// `TableView`, `TreeTableView` and `GridView` are focusable as a whole and
539    /// their rows deliberately are not — the container owns focus and
540    /// `set_selected` is what tells assistive technology which row is current
541    /// (see `list_item_a11y`). Without this hook the chord would open the
542    /// *list's* menu rather than the selected row's, in exactly the widget
543    /// family where a per-row menu matters most.
544    ///
545    /// Return the widget id of the row (or cell, or tile) the menu should be
546    /// about. The dispatcher then walks up from there, so a view whose rows
547    /// carry no factory of their own still finds the container's.
548    ///
549    /// Default: `None` — the focused widget is the target, which is right for
550    /// every widget that is itself the thing the user is pointing at.
551    fn context_menu_key_target(&self) -> Option<WidgetId> {
552        None
553    }
554
555    /// Return the child widget IDs that this widget manages.
556    fn children(&self) -> Vec<WidgetId> {
557        Vec::new()
558    }
559
560    /// Optional override for the child ORDER presented to assistive
561    /// technology, when it must differ from the paint / z-order child
562    /// order returned by [`children`](Self::children).
563    ///
564    /// Return `None` (the default) to let the accessibility walker use the
565    /// arena's child order — correct for almost every widget. Return
566    /// `Some(ids)` to reorder (or restrict) how children appear in the AT
567    /// tree and in the linear Tab reading order, WITHOUT affecting layout or
568    /// paint. `TableView` / `TreeTableView` use this to read the header
569    /// before the body rows even though they build the body first so it
570    /// paints beneath the header (WCAG 1.3.2 Meaningful Sequence).
571    fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
572        None
573    }
574
575    /// Downcast hook. Default implementation returns `None`; concrete
576    /// widgets override with `Some(self)` when they want to expose
577    /// their concrete type to test-level introspection or reflection.
578    /// The trait already bounds on `std::any::Any` so concrete types
579    /// satisfy the `'static` requirement.
580    fn as_any(&self) -> Option<&dyn std::any::Any> {
581        None
582    }
583
584    /// Mutable counterpart of [`as_any`](Self::as_any). Default
585    /// returns `None`; widgets that want to expose mutable state to
586    /// tests (e.g. so a test can mutate a `Scene` inside a
587    /// `SceneView` post-layout) override with `Some(self)`. Should
588    /// follow the same opt-in pattern as `as_any`: only widgets
589    /// that opt into `&` introspection should opt into `&mut`.
590    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
591        None
592    }
593
594    /// Whether this widget clips its children to its bounds.
595    fn clips_children(&self) -> bool {
596        false
597    }
598
599    /// The rectangle (in **absolute tree coordinates**) that best *represents*
600    /// this widget when the framework reveals it into an ancestor scroll area on
601    /// focus gain. Returning `None` (the default) reveals the widget's whole
602    /// bounds — correct for most controls.
603    ///
604    /// A widget that can be much taller than a viewport — a `RichTextEditor`
605    /// grown inside a page `ScrollArea`, a `ListView` / `TreeView` taller than
606    /// its scroller — should override this to return the sub-rectangle the user
607    /// actually cares about (the caret line, the selected row). Otherwise
608    /// [`scroll_focused_into_view`](crate::widget_tree::WidgetTree) reveals the
609    /// *entire* box, which for a tall widget scrolls the page to its bottom on a
610    /// click that only meant to place the caret near the top. The returned rect
611    /// feeds the same ancestor-only `scroll_rect_into_view` engine the caret /
612    /// selection follow uses (the focused widget itself is excluded), so it
613    /// never double-scrolls against the widget's own internal follow.
614    ///
615    /// `bounds` is this widget's current absolute rectangle as the arena stores
616    /// it, so an override can place its interior rect without depending on a
617    /// paint-set origin.
618    fn focus_reveal_rect(&self, _bounds: Rect) -> Option<Rect> {
619        None
620    }
621
622    /// Whether the point lies inside this widget's *actual* shape, not
623    /// just its rectangular bounds. Consulted by hit-testing right after
624    /// the bounds check: returning `false` for a point that *is* inside
625    /// the bounding box makes the widget transparent to the click there,
626    /// so it **falls through** to whatever sibling is painted underneath
627    /// (the same machinery as a fully pass-through node, but shape-aware).
628    ///
629    /// Both arguments are in the widget's bounds space: `local_point` is
630    /// the point being tested and `bounds` is this widget's rectangle, so
631    /// a non-rectangular widget can test the point against its silhouette.
632    ///
633    /// The default returns `true` for any in-bounds point (a plain
634    /// rectangle), so every existing widget is unaffected. Override for
635    /// irregular shapes — an ellipse / cloud scene node, a circular
636    /// handle — so a click lands on the shape you see, not its bounding
637    /// box, and clicks in the transparent corners reach the node beneath.
638    /// The lightweight tier answers the same question from a *value* —
639    /// `SceneItem::shape` returns an `ItemShape` that every query in
640    /// `teksilo-scene` derives from — rather than from a predicate. The two
641    /// are deliberately not the same shape of API and deliberately not the
642    /// same name: a widget is hit-tested by the arena, one point at a time,
643    /// with its bounds already in hand.
644    fn hit_shape(&self, _local_point: Point, _bounds: Rect) -> bool {
645        true
646    }
647
648    /// Veto a hit on one of this widget's **direct children**, per point.
649    ///
650    /// Called during the arena's reverse-sibling walk, once per child, before
651    /// the recursion descends into it. Returning `false` makes the walk fall
652    /// through to the next sibling exactly as a [`hit_shape`](Self::hit_shape)
653    /// rejection on that child would, so the point can land on a lower sibling
654    /// or, finally, on this widget itself.
655    ///
656    /// `point` is in the space this widget's
657    /// [`place_children`](Self::place_children) writes — for an ordinary node
658    /// that is the same absolute space its own bounds are in; for a
659    /// content-transform node (a `SceneView`) it is content coordinates, the
660    /// point already mapped through the inverse of the content transform.
661    ///
662    /// # What this is for
663    ///
664    /// A widget that owns a **second picking system over the same area** — a
665    /// `SceneView`'s lightweight items, a chart's overlay marks, a terminal's
666    /// link layer. Without it the two systems answer independently: the widget
667    /// can paper over the disagreement inside one handler, but press feedback,
668    /// focus-on-release, the touch hold route, the cursor and drag all resolve
669    /// from the arena's answer, so five of the six stay wrong.
670    ///
671    /// It is **not** a replacement for
672    /// [`hit_transparent`](crate::widget_builder::HandlerSet::hit_transparent),
673    /// which is the right tool for a decorative overlay: that is a per-*node*
674    /// declaration ("I never absorb a press"), set from the outside by whoever
675    /// builds the node, and it cannot express "reject this child here and
676    /// accept it one pixel over". This is the per-*point* question, answered by
677    /// the parent that knows why.
678    ///
679    /// # Contract
680    ///
681    /// Must be **pure and cheap**: it runs once per child per hit test, and a
682    /// hit test runs on every pointer sample. It must not mutate anything the
683    /// walk can observe, and — because it runs inside the router — it must not
684    /// re-enter any `RefCell` a handler might already hold. A widget that
685    /// answers from a per-layout snapshot should memoise per walk; the default
686    /// returns `true`, so a widget that does not override it pays one
687    /// devirtualizable call per child.
688    fn accepts_child_hit(&self, _child: WidgetId, _point: Point) -> bool {
689        true
690    }
691
692    /// How far **outside** its own bounds this widget still absorbs a press,
693    /// per edge, for the pointer that is asking.
694    ///
695    /// Consulted **inside** the exact hit test: within one parent, children
696    /// that declare an outset are tested against their outset bounds *before*
697    /// the ordinary reverse-sibling walk, so a 6 dp splitter gutter wins over
698    /// the panes it overlaps instead of losing to whichever pane is painted on
699    /// top. This is the mechanism for a thin **grip**, and the only one of the
700    /// three that can beat a competing target.
701    ///
702    /// Three rules make it safe to add to a widget that already works:
703    ///
704    /// * **Hit-only.** No layout moves, nothing repaints differently, and a
705    ///   Compact build renders byte for byte as it did. The outset exists
706    ///   between the pointer and the arena and nowhere else.
707    /// * **It never escapes the parent.** The recursion has already tested the
708    ///   parent's own bounds before it looks at any child, so an outset can
709    ///   only ever claim space the parent already owns — including through a
710    ///   `clips_children` ancestor, whose rectangle gated the descent.
711    /// * **Zero for a precise pointer** unless the widget deliberately says
712    ///   otherwise. A mouse cursor's hot-spot is exact and occludes nothing, so
713    ///   widening its targets steals clicks. Check
714    ///   `kind.is_direct()` (or accept every kind explicitly, as a control with
715    ///   a genuinely undersized mouse grip may) before returning anything
716    ///   non-zero.
717    ///
718    /// The insets are **reading-order**: `leading` is the left edge in an LTR
719    /// UI and the right edge in an RTL one. The default returns
720    /// [`EdgeInsets::ZERO`](teksilo_canvas::EdgeInsets::ZERO), so every existing
721    /// widget is unaffected.
722    ///
723    /// A grip's conventional value is `9 dp` for a direct pointer and `0 dp`
724    /// for a precise one — enough to lift a 6 dp gutter to a 24 dp target.
725    fn hit_outset(
726        &self,
727        _kind: teksilo_tokens::PointerKind,
728        _tokens: &teksilo_tokens::InputTokens,
729    ) -> teksilo_canvas::EdgeInsets {
730        teksilo_canvas::EdgeInsets::ZERO
731    }
732
733    /// This widget's own say in the *miss-only* slop pass, overriding the
734    /// density default for its node.
735    ///
736    /// Third link of the precedence chain — `no_hit_slop` beats a node-level
737    /// `.hit_slop(..)`, which beats this, which beats
738    /// [`HitSlop::for_pointer`]. Return [`HitSlop::NONE`] to opt a widget out
739    /// of re-attribution entirely, or a larger `up_to` to say that a control
740    /// deserves topping up further than the density asks.
741    ///
742    /// `None` (the default) means "no opinion — use the density default".
743    ///
744    /// [`HitSlop::for_pointer`]: crate::pointer::hit_slop::HitSlop::for_pointer
745    /// [`HitSlop::NONE`]: crate::pointer::hit_slop::HitSlop::NONE
746    fn hit_slop(
747        &self,
748        _kind: teksilo_tokens::PointerKind,
749        _tokens: &teksilo_tokens::InputTokens,
750    ) -> Option<crate::pointer::hit_slop::HitSlop> {
751        None
752    }
753
754    /// How far a *missed* press is from this widget's actual silhouette, in the
755    /// widget's own bounds space.
756    ///
757    /// The key to the miss-only slop pass: once the exact pass has found
758    /// nothing eligible, the framework asks every nearby node how far away it
759    /// really is and re-attributes the press to the closest one still inside
760    /// its earned outset.
761    ///
762    /// The default measures to the bounding rectangle, which is right for the
763    /// rectangular majority. A **round or wedge** control overrides it beside
764    /// its existing [`hit_shape`](Self::hit_shape) so the slop follows the
765    /// shape the user aimed at rather than the box it was laid out in — a
766    /// press past the corner of a radio dot's box is further from the dot than
767    /// a press past its edge, and should lose to a neighbour that is nearer.
768    ///
769    /// Returning `None` withdraws the widget from the pass altogether, which is
770    /// the shape-level equivalent of `no_hit_slop`.
771    ///
772    /// This is **never** consulted by the exact pass, so overriding it cannot
773    /// change where an ordinary click lands.
774    fn hit_distance(&self, local_point: Point, bounds: Rect) -> Option<f32> {
775        Some(crate::pointer::hit_slop::rect_distance(bounds, local_point))
776    }
777
778    /// The interactive sub-regions this widget **paints inside its own single
779    /// node** — a scroll bar's thumb, a slider's knob, a header cell's filter
780    /// affordance.
781    ///
782    /// Reporting only: implementing it changes no layout and no hit test by
783    /// itself. It exists because a control that draws several targets on one
784    /// canvas is otherwise opaque — the router cannot route a coarse press to
785    /// the nearest one, and the target-conformance audit cannot see that any of
786    /// them exists, let alone that it clears the floor.
787    ///
788    /// `bounds` is this widget's current rectangle, and the returned rects are
789    /// in the same space. Build them with
790    /// [`partition_targets`](crate::partition::partition_targets) where the
791    /// split is a horizontal division, so the geometry the widget paints and
792    /// the geometry it reports cannot drift apart.
793    ///
794    /// The default returns an empty list: a widget whose node *is* its target
795    /// has nothing to add.
796    fn target_regions(&self, _bounds: Rect) -> Vec<crate::partition::TargetRegion> {
797        Vec::new()
798    }
799
800    /// How `rebuild_single_widget` treats this widget's existing children
801    /// when re-running its `build()`.
802    ///
803    /// **`false` (default) — re-derive.** Rebuild is "tear down and
804    /// reconstruct": every old child subtree is destroyed up front, then
805    /// `build()` produces a fresh set. The right semantic for data-driven
806    /// widgets like `Repeater` / `ListView` that rebuild their children from
807    /// current model state with fresh `WidgetId`s. A `false` widget must NOT
808    /// re-attach an old child id — it has already been destroyed.
809    ///
810    /// **`true` — reconcile.** `build()` re-attaches (by id) the children it
811    /// keeps and drops the rest. The framework keeps every re-attached child's
812    /// subtree intact — focus, scroll offset, text contents, signal
813    /// subscriptions all survive — and destroys only the old children the new
814    /// build dropped *and* did not re-parent elsewhere. This is the mode for
815    /// widgets that memoize stateful children across rebuilds:
816    ///
817    /// * `Switcher` keeps every mounted page alive so switching tabs doesn't
818    ///   wipe the inactive pages' state.
819    /// * `SceneView` re-pushes the same heavyweight scene-widget ids each
820    ///   rebuild (draining drag-to-move / marquee commits) — they must stay
821    ///   attached or the cards "disappear" on every drag end.
822    /// * `TabWidget` / `DockingLayout` / `CompositeTooltip` re-attach memoized
823    ///   panes / a one-shot body widget that cannot be reconstructed.
824    /// * `MenuBar` re-derives its menu triggers fresh each build (the model may
825    ///   have changed — the reconcile reaps the superseded ones) while keeping
826    ///   its memoized leading/trailing slot widgets, so a stateful slot control
827    ///   survives a model-version rebuild.
828    ///
829    /// The reconcile follows **authoritative parent pointers**, so a kept
830    /// subtree that `build()` re-parents *out* of a dropped sibling and into
831    /// the new tree survives — it is not swept via the dropped sibling's now
832    /// stale `children` list. Dropped children are genuinely destroyed (state
833    /// unmounted, arena slots freed), not left as stranded, still-active
834    /// orphans.
835    fn preserves_children_on_rebuild(&self) -> bool {
836        false
837    }
838
839    /// Whether this widget, used as tooltip content, currently has anything
840    /// worth showing.
841    ///
842    /// Consulted by `WidgetTree` just before a dwell matures into an overlay.
843    /// Returning `false` cancels the show — the anchor simply has no tooltip
844    /// this time — so a blank or unresolved string does not pop an empty
845    /// chromed bubble, which reads as a rendering fault rather than as
846    /// "nothing to say here".
847    ///
848    /// Defaults to `true`: content that hosts an arbitrary widget tree (a
849    /// chart, a progress row) is meaningful without any text, and a custom
850    /// content widget must never be suppressed by a check it did not opt into.
851    /// Only widgets whose *whole* payload is a string — `TooltipWidget` — have
852    /// a well-defined notion of being empty.
853    fn tooltip_has_content(&self) -> bool {
854        true
855    }
856
857    /// Declare the rebindable keyboard shortcuts this widget exposes,
858    /// *without* installing handlers. The framework calls this at
859    /// arena insertion time (before `build()`) and at certain lazy
860    /// boundaries (e.g. `Switcher` walks declarations on its
861    /// not-yet-mounted `Pending` slots), so settings UIs and the
862    /// `ShortcutRegistry` see the keystrokes the moment the owning
863    /// container mounts — even if `build()` hasn't run.
864    ///
865    /// Pair this with `BuildContext::register_shortcut` in `build()`
866    /// to install the matching `on_activate` handler: the build-time
867    /// registration *upserts* the declared entry, preserving any user
868    /// override and the declared keystrokes while attaching the
869    /// closure that actually fires.
870    ///
871    /// The returned shortcuts may omit `on_activate` (a metadata-only
872    /// declaration). When matched at dispatch time without a
873    /// registered handler, the framework synthesizes a no-parameter
874    /// intent from the shortcut's id — same path as a build-time
875    /// registration with `on_activate: None`.
876    ///
877    /// Default: empty (no declared shortcuts).
878    fn declare_shortcuts(&self) -> Vec<crate::shortcut::Shortcut> {
879        Vec::new()
880    }
881
882    /// Extract attached handler set from a `WidgetWithHandlers` wrapper.
883    /// Called during arena insertion to transfer handlers to the `WidgetNode`.
884    /// Default: returns `None` (no attached handlers).
885    fn take_handler_set(&mut self) -> Option<crate::widget_builder::HandlerSet> {
886        None
887    }
888}
889
890/// A boxed widget is a widget.
891///
892/// Without this, `Box<dyn Widget>` is the one widget-shaped value that cannot
893/// go where a widget goes: `.child(..)`, a `Vec` of children, a `match` arm.
894/// 238 functions in `teksilo-widgets` alone return it, the `teksu!` macro's own
895/// over-four-arms advice recommends it, and only two containers in the whole
896/// catalog (`Switcher`, `Cycle`) shipped a `child_boxed` to take it. Every
897/// other call site had to invent an adapter widget, which costs a real arena
898/// node per use.
899///
900/// Every method forwards to the inner widget, so the box is invisible to the
901/// arena: it adds no node, no layout pass and no AT element. In particular
902/// `as_any` / `as_any_mut` forward, so `EventContext::with_widget_mut::<W>`
903/// downcasts to the widget that was boxed rather than to the box.
904/// `#[deny(clippy::missing_trait_methods)]` for the reason the trait's own
905/// header gives: the arena holds `Box<dyn Widget>`, so a call on a node
906/// resolves to *this* impl and not to the vtable. A method left out here
907/// answers with the trait default for every widget in the tree, the
908/// widget's own override is never reached, and nothing fails to compile —
909/// which is exactly how `accepts_child_hit` and `culls_children` went
910/// missing when this impl and those two methods were written on separate
911/// branches and merged cleanly.
912#[deny(clippy::missing_trait_methods)]
913impl<W: Widget + ?Sized> Widget for Box<W> {
914    fn type_name(&self) -> &'static str {
915        (**self).type_name()
916    }
917
918    fn build(
919        &mut self,
920        ctx: &mut crate::build_context::BuildContext,
921    ) -> Vec<crate::widget_id::WidgetId> {
922        (**self).build(ctx)
923    }
924
925    fn layout_response(&self, proposal: SizeProposal, ctx: &LayoutContext) -> LayoutResponse {
926        (**self).layout_response(proposal, ctx)
927    }
928
929    fn cacheable_layout(&self) -> bool {
930        (**self).cacheable_layout()
931    }
932
933    fn place_children(
934        &self,
935        bounds: Rect,
936        proposal: SizeProposal,
937        children: &mut [WidgetPlacement],
938        ctx: &LayoutContext,
939    ) {
940        (**self).place_children(bounds, proposal, children, ctx)
941    }
942
943    fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
944        (**self).paint(bounds, canvas, ctx)
945    }
946
947    fn wants_after_paint(&self) -> bool {
948        (**self).wants_after_paint()
949    }
950
951    fn after_paint(&self, view: &WidgetTreeView<'_>, ctx: &PaintContext) {
952        (**self).after_paint(view, ctx)
953    }
954
955    fn wants_post_paint(&self) -> bool {
956        (**self).wants_post_paint()
957    }
958
959    fn post_paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
960        (**self).post_paint(bounds, canvas, ctx)
961    }
962
963    fn accessibility(&self, builder: &mut AccessNodeBuilder) {
964        (**self).accessibility(builder)
965    }
966
967    fn wants_descendant_redirects(&self) -> bool {
968        (**self).wants_descendant_redirects()
969    }
970
971    fn a11y_redirect_descendant(
972        &self,
973        self_id: WidgetId,
974        descendant: WidgetId,
975    ) -> Option<accesskit::NodeId> {
976        (**self).a11y_redirect_descendant(self_id, descendant)
977    }
978
979    fn accessible_title_hint(&self) -> Option<String> {
980        (**self).accessible_title_hint()
981    }
982
983    fn accessible_title_node(&self) -> Option<crate::widget_id::WidgetId> {
984        (**self).accessible_title_node()
985    }
986
987    fn initial_focus_hint(&self) -> Option<WidgetId> {
988        (**self).initial_focus_hint()
989    }
990
991    fn accessibility_proxy(&self) -> Option<WidgetId> {
992        (**self).accessibility_proxy()
993    }
994
995    fn context_menu_key_target(&self) -> Option<WidgetId> {
996        (**self).context_menu_key_target()
997    }
998
999    fn children(&self) -> Vec<WidgetId> {
1000        (**self).children()
1001    }
1002
1003    fn accessibility_children(&self) -> Option<Vec<WidgetId>> {
1004        (**self).accessibility_children()
1005    }
1006
1007    fn as_any(&self) -> Option<&dyn std::any::Any> {
1008        (**self).as_any()
1009    }
1010
1011    fn as_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1012        (**self).as_any_mut()
1013    }
1014
1015    fn clips_children(&self) -> bool {
1016        (**self).clips_children()
1017    }
1018
1019    fn focus_reveal_rect(&self, bounds: Rect) -> Option<Rect> {
1020        (**self).focus_reveal_rect(bounds)
1021    }
1022
1023    fn hit_shape(&self, local_point: Point, bounds: Rect) -> bool {
1024        (**self).hit_shape(local_point, bounds)
1025    }
1026
1027    fn hit_outset(
1028        &self,
1029        kind: teksilo_tokens::PointerKind,
1030        tokens: &teksilo_tokens::InputTokens,
1031    ) -> teksilo_canvas::EdgeInsets {
1032        (**self).hit_outset(kind, tokens)
1033    }
1034
1035    fn hit_slop(
1036        &self,
1037        kind: teksilo_tokens::PointerKind,
1038        tokens: &teksilo_tokens::InputTokens,
1039    ) -> Option<crate::pointer::hit_slop::HitSlop> {
1040        (**self).hit_slop(kind, tokens)
1041    }
1042
1043    fn hit_distance(&self, local_point: Point, bounds: Rect) -> Option<f32> {
1044        (**self).hit_distance(local_point, bounds)
1045    }
1046
1047    fn accepts_child_hit(&self, child: crate::widget_id::WidgetId, point: Point) -> bool {
1048        (**self).accepts_child_hit(child, point)
1049    }
1050
1051    fn culls_children(&self) -> bool {
1052        (**self).culls_children()
1053    }
1054
1055    fn target_regions(&self, bounds: Rect) -> Vec<crate::partition::TargetRegion> {
1056        (**self).target_regions(bounds)
1057    }
1058
1059    fn preserves_children_on_rebuild(&self) -> bool {
1060        (**self).preserves_children_on_rebuild()
1061    }
1062
1063    fn tooltip_has_content(&self) -> bool {
1064        (**self).tooltip_has_content()
1065    }
1066
1067    fn declare_shortcuts(&self) -> Vec<crate::shortcut::Shortcut> {
1068        (**self).declare_shortcuts()
1069    }
1070
1071    fn take_handler_set(&mut self) -> Option<crate::widget_builder::HandlerSet> {
1072        (**self).take_handler_set()
1073    }
1074}