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