Skip to main content

teksilo_core/
arena.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use slotmap::SlotMap;
5
6use crate::environment::ThemeOverride;
7use crate::event_handlers::EventHandlers;
8use crate::event_source::{SubscriptionHandle, SubscriptionId};
9use crate::gesture::MultiContact;
10use crate::pointer::hit_slop::{HitCandidate, HitContext};
11use crate::pointer::touch_action::{PanClaim, TouchAction};
12use crate::signal::{ObserverHandle, Prop, Signal};
13use crate::widget::{CursorIcon, Widget};
14use crate::widget_id::WidgetId;
15use teksilo_canvas::RenderFrame;
16
17/// Minimal placeholder widget used during composite rebuild and ID reservation.
18#[derive(Debug)]
19pub(crate) struct PlaceholderWidget;
20
21impl Widget for PlaceholderWidget {
22    fn layout_response(
23        &self,
24        _proposal: teksilo_canvas::SizeProposal,
25        _ctx: &crate::widget::LayoutContext,
26    ) -> crate::widget::LayoutResponse {
27        teksilo_canvas::Size::ZERO.into()
28    }
29}
30
31/// Activation state for a widget in the arena.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ActivationState {
34    Active,
35    Dormant,
36    Destroyed,
37}
38
39/// Where a `HandlerSet` should land on the node: handlers the widget
40/// attaches to itself (cleared on rebuild) vs handlers attached from
41/// outside (persist across rebuilds).
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub(crate) enum HandlerScope {
44    /// Handlers registered during the widget's own `build()` via
45    /// `BuildContext::apply_self_handlers`.
46    Own,
47    /// Handlers attached externally — at insertion time via
48    /// `WidgetBuilder::on_tap` et al., or by a composing parent's
49    /// `BuildContext::apply_handlers(child_id, ...)`.
50    External,
51}
52
53/// Dirty flags for a widget.
54#[derive(Debug, Clone, Copy, Default)]
55pub struct DirtyFlags {
56    pub needs_layout: bool,
57    pub needs_paint: bool,
58    /// When true, the widget's `build()` should be re-run to regenerate children.
59    /// Set by `BindingLevel::Rebuild` bindings (data-driven widgets).
60    pub needs_rebuild: bool,
61}
62
63/// One node's resolved hit-test geometry: which point tests its own bounds,
64/// which point its children receive, its bounds, and how much its own transform
65/// scales a local distance.
66///
67/// Shared by the exact pass, the outset pre-pass and the slop candidate walk so
68/// the three cannot disagree about where a transformed node actually is.
69struct HitSpace {
70    bounds_point: teksilo_canvas::Point,
71    child_point: teksilo_canvas::Point,
72    bounds: teksilo_canvas::Rect,
73    /// The minimum singular value of this node's own transform (`1.0` when it
74    /// has none) — the factor that turns a distance in its local space into one
75    /// in its parent's.
76    scale: f32,
77}
78
79/// `0.0` for a non-finite or negative inset, so a widget that computes an
80/// outset from a `NaN` measurement cannot inflate a rectangle into nonsense.
81fn finite(v: f32) -> f32 {
82    if v.is_finite() && v > 0.0 { v } else { 0.0 }
83}
84
85/// A node in the widget arena storing a widget and its metadata.
86pub struct WidgetNode {
87    pub widget: Box<dyn Widget>,
88    pub parent: Option<WidgetId>,
89    pub children: Vec<WidgetId>,
90    pub activation: ActivationState,
91    /// Whether this node is dormant **on its own account** — parked by a
92    /// direct [`WidgetArena::set_dormant`] rather than swept along by an
93    /// ancestor going dormant.
94    ///
95    /// This is the ungated twin of `visible_state`, and [`WidgetArena::activate`]
96    /// honours the two identically: a self-parked child is left asleep when an
97    /// ancestor wakes, because the ancestor's dormancy was never why it was
98    /// asleep. Cleared the moment a caller activates this node *by id*, which is
99    /// exactly how pre-registered overlay content is shown.
100    ///
101    /// Without it, every widget that pre-builds hidden content as a child with
102    /// `ctx.add(..)` + `ctx.set_dormant(..)` — `SplitButton`'s dropdown,
103    /// `MenuBar`'s menus, `Popover`, `Snackbar`, the date editors' calendars —
104    /// spilled that content onto the screen as soon as any ancestor completed a
105    /// dormancy cycle, laid out inline with no overlay behind it.
106    pub(crate) self_dormant: bool,
107    pub dirty: DirtyFlags,
108    pub bounds: teksilo_canvas::Rect,
109    pub(crate) theme_override: Option<ThemeOverride>,
110    pub(crate) visible_state: Option<Prop<bool>>,
111    pub(crate) enabled_state: Option<Prop<bool>>,
112    /// Reactive Tab-key participation. When bound and evaluates to
113    /// `false`, the widget is excluded from Tab / Shift+Tab traversal
114    /// (`cycle_focus`) — but remains reachable via `request_focus`
115    /// and arrow-key navigation that calls `request_focus`. This
116    /// implements the ARIA roving-tabindex pattern (HTML
117    /// `tabindex="-1"` semantics). `None` means "always a Tab stop
118    /// when focusable" — the default. The selected `TabHeader` is the
119    /// canonical user.
120    pub(crate) tab_stop: Option<Prop<bool>>,
121    /// What a data view's `Space` should do when the row containing this node
122    /// holds the keyboard cursor.
123    ///
124    /// A `ListView` / `TreeView` row is deliberately not focusable — the
125    /// container is — and the view takes the row subtree out of the Tab order,
126    /// because a listbox is one Tab stop and a per-row stop would make the Tab
127    /// order track the virtualization window. That leaves a checkbox inside a
128    /// row with no keyboard route, so the row publishes one here and the view
129    /// calls it. Carrying the *action* rather than the target's id keeps the
130    /// views from having to know what kind of control it is.
131    ///
132    /// `StandardListItem` / `StandardTreeItem` set it on the checkbox they
133    /// embed, so the common path needs no wiring; a hand-written delegate
134    /// calls `BuildContext::set_keyboard_toggle`.
135    #[allow(clippy::type_complexity)]
136    pub(crate) keyboard_toggle: Option<std::rc::Rc<dyn Fn(&mut crate::widget::EventContext)>>,
137    /// User-bound signal that the framework sets to `true` whenever
138    /// the focused widget is a strict descendant of this node, and
139    /// `false` otherwise. Used by `Panel` / `Card` / composite
140    /// widgets that want a unified focus halo without per-child
141    /// `on_focus` plumbing. See `WidgetBuilder::focus_within`.
142    pub(crate) focus_within_signal: Option<Signal<bool>>,
143    /// Framework-managed signal, lazily attached to a focusable node, set to
144    /// `true` whenever the focus is this node **or** a descendant (i.e. the node
145    /// is an *inclusive* ancestor of the focused widget). Unlike
146    /// `focus_within_signal` (strict descendants), this includes the node being
147    /// focused itself — so a data view that holds focus directly reads `true`.
148    /// Powers focus-aware selection (`BuildContext::view_focus_active`).
149    pub(crate) view_focus_signal: Option<Signal<bool>>,
150    /// User-bound signal that the framework sets to `true` whenever
151    /// the hovered widget is a strict descendant of this node.
152    /// Symmetric to `focus_within_signal`. See
153    /// `WidgetBuilder::hover_within`.
154    pub(crate) hover_within_signal: Option<Signal<bool>>,
155    /// User-bound signal that the framework sets to `true` while this
156    /// node is `ActivationState::Active` and `false` while it is
157    /// `Dormant`. Opted into via `BuildContext::activation_signal`.
158    /// Unlike every other widget — which is hidden automatically when
159    /// the paint pass skips a dormant subtree — a widget that owns a
160    /// resource living *outside* the wgpu pass (a native OS subview: a
161    /// `WebView` engine surface) has no other way to learn it was parked
162    /// dormant by a `Switcher` / `visible_when` gate, so it cannot hide
163    /// that resource. This signal is that notification. Set only on an
164    /// actual Active↔Dormant transition. See `set_dormant` / `activate`.
165    pub(crate) activation_signal: Option<Signal<bool>>,
166    /// Framework-written press visual: `true` while this node holds a pointer
167    /// press that has not slid off, been claimed by a peer, or been cancelled.
168    /// Opted into via `BuildContext::pressed_signal`, and written by the
169    /// router — see [`crate::press`] for why the widget cannot maintain this
170    /// from its own handlers.
171    pub(crate) pressed_signal: Option<Signal<bool>>,
172    /// Framework-written mirror of [`WidgetArena::is_enabled`] for this node —
173    /// the AND of its own `enabled_state` and every ancestor's. Opted into via
174    /// `BuildContext::effective_enabled_signal`.
175    ///
176    /// This has to be a *node-resident* signal that the framework refreshes,
177    /// rather than a signal derived by walking ancestors at call time, because
178    /// a widget's `parent` is still `None` while its own `build()` runs — the
179    /// parent link is wired only after `build()` returns (see
180    /// `WidgetTree::insert_widget`). A signal derived during `build()` would
181    /// therefore capture an empty ancestor chain and report only the widget's
182    /// own `enabled` prop, forever. Refreshed in
183    /// `WidgetTree::flush_effective_enabled_signals`.
184    pub(crate) effective_enabled_signal: Option<Signal<bool>>,
185    pub(crate) alignment_override: Option<teksilo_tokens::Alignment>,
186    /// When true, the paint pass clips child rendering to this widget's bounds.
187    /// Set by scroll areas and overflow-hidden containers.
188    pub clips_children: bool,
189    /// Optional OS input-method (IME) descriptor. `Some(..)` declares this
190    /// node a text-input surface — the platform enables the OS IME (with the
191    /// descriptor's purpose) while the node is focused. `None` (the default)
192    /// means no OS IME: enabling IME changes how text arrives, so the safe
193    /// common-case default is off. The platform reads the focused node's
194    /// descriptor at focus-change time. See [`crate::ime`].
195    pub ime: Option<crate::ime::ImeContext>,
196    /// When true, hit-testing skips this node — pointer events fall
197    /// through to whatever sits behind it. Descendants are still
198    /// hit-tested normally (the recursion walks into children before
199    /// the pass-through check), so an interactive subtree under a
200    /// pass-through wrapper stays usable. Used by the debug inspector's
201    /// `HighlightLayer` and `HoverProbe` to paint over the user's
202    /// content without absorbing clicks. Default `false`.
203    pub event_pass_through: bool,
204    /// When `true`, a pointer press anywhere in this widget's subtree must
205    /// NOT arm a drag/swipe recognizer on any ancestor **above** this node —
206    /// the subtree is a *gesture dead zone* for ancestor gestures. Used so
207    /// interactive controls (buttons, a `⋮` menu) placed inside a draggable /
208    /// swipeable container (a dock-panel header, a card, a list row) can be
209    /// clicked without a few px of pointer jitter starting the ancestor's drag.
210    /// The boundary is honored by `PointerSequence` member enrolment. Mirrors Electron's
211    /// `-webkit-app-region: no-drag`. Default `false`. See the `DeadZone`
212    /// wrapper widget.
213    pub gesture_dead_zone: bool,
214    /// What a **hold** on this node's subtree means when the widget itself does
215    /// not say — the selector for the tree-owned long-press route. Default
216    /// `LongPressRole::Auto`. Set via `.long_press_role(..)`. A node's own
217    /// `on_long_press` always takes precedence over this, and a mouse never
218    /// consults it. See [`crate::widget_tree::touch_route`].
219    pub long_press_role: crate::widget_tree::touch_route::LongPressRole,
220    /// What a direct pointer (touch, pen) is permitted to do to this node's
221    /// subtree. Intersected with every ancestor's on the way down by
222    /// `WidgetTree::effective_touch_action` — an ancestor can only narrow
223    /// what a descendant permits, never widen it. Default
224    /// [`TouchAction::AUTO`] (everything permitted). Set via
225    /// `.touch_action(..)`. A mouse never consults this field. Read at press
226    /// time, to gate pan claimants and the two-contact pinch — see
227    /// [`crate::pointer::touch_action`].
228    pub touch_action: TouchAction,
229    /// This node's declaration that it is a **pan surface** — it wants to
230    /// consume a direct pointer's drag as content panning. `None` (the
231    /// default) means the node makes no such claim. `WidgetTree::
232    /// pan_candidates` collects every claim from a target up to the root.
233    /// Set via `.pan_claim(..)` or the `.scroll_container(..)` sugar. Read at
234    /// press time to build the chain a synthesised pan walks — see
235    /// [`crate::pointer::touch_action`].
236    pub pan_claim: Option<PanClaim>,
237    /// Whether this node absorbs a scroll it cannot use, or lets it chain to
238    /// the next scrollable outward — the CSS `overscroll-behavior` model.
239    ///
240    /// Read by `WidgetTree::deliver_pan` when it walks the claimant chain: an
241    /// [`OverscrollBehavior::Contain`](crate::OverscrollBehavior::Contain)
242    /// claimant **stops** the chain even when it absorbed nothing, so a
243    /// self-contained panel never lets a boundary pan escape into the page
244    /// behind it. Default
245    /// [`Chain`](crate::OverscrollBehavior::Chain). Set via
246    /// `.overscroll_behavior(..)`.
247    ///
248    /// Declared on the node rather than left inside each scrollable's own
249    /// `on_scroll` closure because the *chain* has to read it, and the chain
250    /// runs in the router, above every handler.
251    pub overscroll_behavior: crate::OverscrollBehavior,
252    /// When a drag on this node may begin relative to the press that starts
253    /// it. [`DragActivation::Auto`](teksilo_tokens::DragActivation::Auto) — the
254    /// default — resolves to `Immediate`
255    /// for a precise pointer (today's behaviour, unchanged) and to
256    /// `AfterLongPress` for a coarse pointer whose axis is already claimed by
257    /// a pan surface. Set via `.drag_activation(..)`, read by the arbitration
258    /// when the node is enrolled as a sequence member.
259    pub drag_activation: teksilo_tokens::DragActivation,
260    /// How many simultaneous contacts this node's gesture recognizers serve.
261    /// Default [`MultiContact::First`] — one press at a time, which is what
262    /// every widget written before the touch programme assumes. Under it a
263    /// *second* contact arriving while the first is live is terminated at this
264    /// node: not delivered to it, and not bubbled to an ancestor either, so two
265    /// fingers on a button inside a scroll area cannot start a pan with the
266    /// second finger. Set via `.multi_contact(..)`.
267    pub multi_contact: MultiContact,
268    /// When `true` and this widget holds keyboard focus, a `KeyDown` is
269    /// delivered straight to it **without** first running shortcut →
270    /// intent → action resolution. The node is a *keyboard capture*
271    /// surface: it wants every keystroke (including chords the host app
272    /// binds as `Shortcut`s — `Ctrl+C`, `Ctrl+W`, `Alt+<letter>`, …).
273    /// Used by a terminal emulator (which must forward `Ctrl+C` to the
274    /// child process, not trigger the app's copy shortcut), a game
275    /// viewport, or a vim-mode editor. Honored by `dispatch_event_impl`,
276    /// which skips the shortcut block for a focused capture node.
277    ///
278    /// **`Ctrl+Tab` / `Ctrl+Shift+Tab` are reserved**: `dispatch_event_impl`
279    /// cycles focus on that chord before dispatching to a focused capture
280    /// node, so no capture surface can trap the keyboard (WCAG 2.1.2).
281    /// Escape is not reserved — overlay back-navigation runs ahead of the
282    /// check only while an overlay is open, so a capture surface below no
283    /// overlay does see Escape. Default `false`.
284    pub keyboard_capture: bool,
285    /// When `true`, this widget AND its entire subtree are invisible to
286    /// hit-testing: the recursion returns immediately without descending
287    /// into children, so the point falls through to whatever sits
288    /// behind. Unlike [`event_pass_through`](Self::event_pass_through)
289    /// (which is per-node — descendants stay hittable), this excludes
290    /// the whole subtree. Use for purely decorative overlays whose
291    /// children are themselves widgets — a count badge over a button, a
292    /// watermark, a status dot — so they never steal clicks meant for
293    /// the control underneath. Default `false`.
294    pub hit_transparent: bool,
295    /// Per-node override of the *miss-only* slop this node may earn, set via
296    /// `.hit_slop(..)`. Second link of the precedence chain — it beats the
297    /// widget's own `Widget::hit_slop` and the density default, and loses only
298    /// to [`no_hit_slop`](Self::no_hit_slop). `None` (the default) defers to
299    /// the widget, then to the density.
300    pub hit_slop: Option<crate::pointer::hit_slop::HitSlop>,
301    /// When `true`, this node is excluded from **both** hit-widening
302    /// mechanisms: it earns no slop outset in the miss-only pass, and its
303    /// `Widget::hit_outset` is ignored inside the exact pass. The head of the
304    /// precedence chain, set via `.no_hit_slop()`.
305    ///
306    /// Per-node, not per-subtree: a descendant may still widen. Excluding a
307    /// whole subtree from hit-testing is
308    /// [`hit_transparent`](Self::hit_transparent)'s job, and excluding a region
309    /// that hosts foreign content (a `WebView` surface) is exactly this flag on
310    /// that one node. Default `false`.
311    pub no_hit_slop: bool,
312    /// Optional opacity multiplier (0..1) applied to this widget's
313    /// entire subtree during paint. The render walker emits
314    /// `SetOpacity(value)` before walking the widget's own paint and
315    /// children, then `RestoreOpacity` afterwards — so the multiplier
316    /// composes with ancestor opacity scopes via the canvas's
317    /// already-stacked opacity model. Bound at `Repaint` level: opacity
318    /// changes never trigger relayout. `None` means "no opacity scope"
319    /// (the default for almost every widget). The `Fade` widget sets
320    /// this on its own node to drive an animated visibility tween.
321    pub(crate) opacity_prop: Option<Prop<f32>>,
322    /// Optional 2D affine transform applied to this widget's entire
323    /// subtree during paint. The render walker emits
324    /// `PushTransform(value)` before walking the widget's own paint
325    /// and children, then `PopTransform` afterwards — the renderer
326    /// composes it onto its transform stack so nested wrappers and
327    /// widget-internal canvas transforms compose correctly. Bound at
328    /// `Repaint` level by default (visual-only); a wrapper that wants
329    /// the transform to drive layout (e.g. `Scale::reflow(true)`)
330    /// must additionally bind its driver signal at `Relayout`.
331    /// `None` means "no transform scope" (the default for almost every
332    /// widget). The `Scale` and `Rotate` widgets set this on their own
333    /// node.
334    pub(crate) transform_prop: Option<Prop<teksilo_canvas::Transform2D>>,
335    /// Whether [`transform_prop`](Self::transform_prop) transforms this node's
336    /// **content** within a fixed parent-space viewport (`true`), versus
337    /// transforming the **node itself** (`false`, the default).
338    ///
339    /// `Scale` / `Rotate` are *self* transforms: the node's own bounds move
340    /// with the transform, so hit-testing inverse-applies the transform before
341    /// the bounds test (a click lands where the scaled/rotated visual is).
342    ///
343    /// `SceneView` is a *content* transform: its bounds are a fixed screen
344    /// viewport and the pan/zoom only moves its content, so hit-testing must
345    /// test the bounds in parent space (keeping the whole visible viewport
346    /// interactive at any pan) and apply the transform only when descending
347    /// into children. Set via `BuildContext::set_content_transform`.
348    pub(crate) content_transform: bool,
349    /// Optional Gaussian-equivalent blur radius applied to this widget's
350    /// entire subtree during paint. The render walker emits
351    /// `BeginBlurredSubtree { bounds, radius }` before walking the
352    /// widget's own paint and children, then `EndBlurredSubtree`
353    /// afterwards — the renderer redirects drawing into an intermediate
354    /// texture, runs a dual-Kawase blur chain at the requested radius,
355    /// and composites the blurred result back into the parent pass.
356    /// Bound at `Repaint` level: blur radius changes never trigger
357    /// relayout. `None` (or `Some(radius < 0.5)`) means "no blur scope"
358    /// — the walker skips the Begin/End pair entirely so disabled blur
359    /// has zero per-frame cost. The `Blur` widget sets this on its own
360    /// node.
361    pub(crate) blur_prop: Option<Prop<f32>>,
362    /// Cached paint output for this widget (excludes children).
363    /// Reused when `needs_paint` is false to avoid re-running `paint()`.
364    pub(crate) cached_paint: Option<RenderFrame>,
365    /// Cached foreground output for widgets that override
366    /// [`Widget::post_paint`] — the
367    /// draws emitted *after* this widget's children. Separate frame from
368    /// `cached_paint` because it lands at a different position in
369    /// `draw_order` (after the child subtree). Reused on the same
370    /// `needs_paint` gate.
371    pub(crate) cached_post_paint: Option<RenderFrame>,
372    /// The ambient raster scale `cached_paint` / `cached_post_paint`
373    /// were baked at (the paint walker's accumulated transform scale,
374    /// quantized). Glyph quads in those frames reference bitmaps of
375    /// that density; when the walker's current scale differs (a scene
376    /// zoom crossed a quantization bucket), the cached frames are
377    /// treated as `needs_paint` even though the widget itself is clean.
378    pub(crate) paint_raster_scale: f32,
379    /// The `WidgetTree::paint_epoch` at which this widget's bounds were
380    /// last observed inside the window viewport by the paint pass.
381    /// The animation scheduler uses this to pause looping animations
382    /// for offscreen widgets: an animation whose
383    /// `last_painted_epoch + 1 < tree.paint_epoch` is considered
384    /// off-screen and skipped. `0` means "not yet painted"; visibility is
385    /// waived wholesale while `tree.paint_epoch` is itself `0`, which keeps
386    /// headless tests (no `render()` call) from regressing.
387    pub last_painted_epoch: u64,
388
389    // --- V2 fields ---
390    /// Event handlers the widget attached to itself during its own
391    /// `build()` via `BuildContext::apply_self_handlers`. Cleared on
392    /// rebuild so accumulating `apply_self_handlers` calls across
393    /// rebuilds don't stack N-fold handler chains.
394    pub(crate) handlers: EventHandlers,
395    /// Event handlers attached *externally* — either via the
396    /// `WidgetBuilder` chain at the widget's creation site
397    /// (`SomeWidget::new().on_tap(...)`) or by a parent's
398    /// `BuildContext::apply_handlers(child_id, ...)`. These survive
399    /// rebuilds: the widget didn't register them and shouldn't decide
400    /// when they go away.
401    pub(crate) external_handlers: EventHandlers,
402    /// Focusable override set via HandlerSet. The only source of a node's
403    /// focusability — `WidgetTree::is_node_focusable` reads this field and
404    /// nothing else, so `None` means not focusable.
405    pub(crate) node_focusable: Option<bool>,
406    /// Tab index override set via HandlerSet.
407    pub(crate) node_tab_index: Option<i32>,
408    /// Traversal-scope marker. When `Some(policy)`, `cycle_focus` treats this
409    /// node's subtree as an independent Tab group: `tab_index` numbering is
410    /// scoped to its descendants (so sibling scopes never interleave) and
411    /// `policy` governs what Tab does at the scope's ends. `None` (default)
412    /// means the node is transparent to traversal scoping. Set by the
413    /// `FocusScope` wrapper via `BuildContext::set_traversal_scope`. A node
414    /// carrying this marker is forced non-focusable (it is a boundary, never a
415    /// Tab stop). See [`crate::focus::TraversalScopePolicy`].
416    pub(crate) node_traversal_scope: Option<crate::focus::TraversalScopePolicy>,
417    /// Cursor override set via HandlerSet.
418    pub(crate) node_cursor: Option<CursorIcon>,
419    /// RAII observer handles for effects registered during build().
420    /// Dropped on rebuild or widget destruction.
421    pub(crate) effect_handles: Vec<ObserverHandle>,
422    /// Backend-event subscriptions registered during build() via
423    /// `BuildContext::subscribe_event`. Each entry pairs a subscription id
424    /// (used to remove the UI-side callback from `TreeAppContext`) with the
425    /// opaque source-side handle whose `Drop` removes the subscriber from
426    /// the source's internal registry.
427    pub(crate) subscription_handles: Vec<(SubscriptionId, SubscriptionHandle)>,
428    /// Parentless nodes this widget created during `build()` and still owns —
429    /// pre-built overlay content (a menu, a calendar, a tooltip's nested
430    /// cascade children) that is deliberately *not* a child.
431    ///
432    /// Such content cannot be a child: activation and the paint walk both
433    /// descend through `children`, so a dormant popup parked there wakes with
434    /// its host and paints inline at zero size. Keeping it parentless fixes
435    /// that and creates the opposite problem — no teardown walk reaches it, so
436    /// every rebuild of the host strands another copy in the arena for the
437    /// lifetime of the process. This list is the missing ownership edge:
438    /// [`WidgetTree::destroy_subtree`](crate::widget_tree::WidgetTree) reaps it
439    /// with the owner, and a rebuild reaps the previous generation. Recorded
440    /// via `BuildContext::add_detached`.
441    pub(crate) detached: Vec<WidgetId>,
442    /// Context menu factory — invoked on right-click to produce overlay content.
443    pub(crate) context_menu_factory: Option<crate::widget_builder::ContextMenuFactory>,
444    /// Intent-bound actions attached by this widget during `build()`.
445    /// Consulted during intent dispatch (source-widget → root walk).
446    /// Cleared on rebuild in the same pass that clears handlers.
447    pub(crate) actions: Vec<crate::action::Action>,
448    /// Builder-level accessibility overrides (`access_label`,
449    /// `access_role`, etc.). Mirrored from the wrapper's `HandlerSet`
450    /// at insertion via `apply_handler_set`. Applied by the
451    /// accessibility tree walker after the inner widget's
452    /// `accessibility(&self, builder)` runs. Action callbacks
453    /// (`actions`, `custom_actions` inside this struct) are dispatched
454    /// by `pointer_router.rs` when handling
455    /// `WidgetEvent::AccessAction`.
456    pub(crate) access_overrides: Option<Box<crate::widget_builder::AccessibilityOverrides>>,
457    /// Subtree visibility / merge mode (`access_exclude_subtree` /
458    /// `access_merge_subtree`). Mirrored from the wrapper's
459    /// `HandlerSet`.
460    pub(crate) access_subtree: crate::widget_builder::AccessSubtreeMode,
461}
462
463impl std::fmt::Debug for WidgetNode {
464    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
465        f.debug_struct("WidgetNode")
466            .field("widget", &self.widget)
467            .field("parent", &self.parent)
468            .field("children", &self.children)
469            .field("activation", &self.activation)
470            .field("dirty", &self.dirty)
471            .field("bounds", &self.bounds)
472            .field("has_gesture_arena", &self.handlers.gesture_arena.is_some())
473            .field("has_theme_override", &self.theme_override.is_some())
474            .field("has_visible_state", &self.visible_state.is_some())
475            .field("has_enabled_state", &self.enabled_state.is_some())
476            .finish()
477    }
478}
479
480impl WidgetNode {
481    /// Construct a fresh node wrapping `widget`, parented at `parent`
482    /// (`None` for a root). All other fields take their insertion defaults;
483    /// the caller wires up `children` / parent back-links afterward.
484    pub(crate) fn new(widget: Box<dyn Widget>, parent: Option<WidgetId>) -> Self {
485        WidgetNode {
486            widget,
487            parent,
488            children: Vec::new(),
489            activation: ActivationState::Active,
490            self_dormant: false,
491            dirty: DirtyFlags {
492                needs_layout: true,
493                needs_paint: true,
494                needs_rebuild: false,
495            },
496            bounds: teksilo_canvas::Rect::ZERO,
497            theme_override: None,
498            visible_state: None,
499            enabled_state: None,
500            tab_stop: None,
501            keyboard_toggle: None,
502            focus_within_signal: None,
503            view_focus_signal: None,
504            hover_within_signal: None,
505            activation_signal: None,
506            pressed_signal: None,
507            effective_enabled_signal: None,
508            alignment_override: None,
509            clips_children: false,
510            ime: None,
511            event_pass_through: false,
512            gesture_dead_zone: false,
513            long_press_role: crate::widget_tree::touch_route::LongPressRole::Auto,
514            touch_action: TouchAction::AUTO,
515            pan_claim: None,
516            overscroll_behavior: crate::OverscrollBehavior::Chain,
517            drag_activation: teksilo_tokens::DragActivation::Auto,
518            multi_contact: MultiContact::First,
519            keyboard_capture: false,
520            hit_transparent: false,
521            hit_slop: None,
522            no_hit_slop: false,
523            opacity_prop: None,
524            transform_prop: None,
525            content_transform: false,
526            blur_prop: None,
527            cached_paint: None,
528            cached_post_paint: None,
529            paint_raster_scale: 1.0,
530            last_painted_epoch: 0,
531            handlers: EventHandlers::new(),
532            external_handlers: EventHandlers::new(),
533            node_focusable: None,
534            node_tab_index: None,
535            node_traversal_scope: None,
536            node_cursor: None,
537            effect_handles: Vec::new(),
538            subscription_handles: Vec::new(),
539            detached: Vec::new(),
540            context_menu_factory: None,
541            actions: Vec::new(),
542            access_overrides: None,
543            access_subtree: crate::widget_builder::AccessSubtreeMode::default(),
544        }
545    }
546
547    /// Does EITHER handler slot (own or external) have a handler of the
548    /// requested kind? Use this when deciding whether to build a gesture
549    /// arena, mark the node as a drop target, etc.
550    pub(crate) fn any_handler<F>(&self, f: F) -> bool
551    where
552        F: Fn(&EventHandlers) -> bool,
553    {
554        f(&self.handlers) || f(&self.external_handlers)
555    }
556}
557
558/// Flat arena storage for all widgets, using SlotMap for O(1) access.
559pub struct WidgetArena {
560    nodes: SlotMap<WidgetId, WidgetNode>,
561    /// Number of nodes with theme overrides. When zero, resolve_theme is O(1).
562    pub(crate) theme_override_count: usize,
563    /// Cached root widget IDs (widgets with no parent).
564    cached_roots: Vec<WidgetId>,
565    /// Whether the cached_roots list needs rebuilding.
566    roots_dirty: bool,
567    /// Per-pass memoization of `Widget::layout_response`, keyed by
568    /// `(WidgetId, ProposalKey)`. Cleared once at the start of every layout
569    /// pass (see `clear_layout_cache`). Height-for-width negotiation queries
570    /// each child along the main axis and again along the cross axis, so
571    /// without this the cost compounds super-linearly with nesting depth;
572    /// with it, each `(id, proposal)` is computed at most once per pass.
573    /// `RefCell` because layout runs through shared `&WidgetArena` borrows.
574    layout_cache: std::cell::RefCell<
575        std::collections::HashMap<(WidgetId, ProposalKey), crate::widget::LayoutResponse>,
576    >,
577    /// Widgets whose box moved without changing size since the last
578    /// accessibility walk, and by how much.
579    ///
580    /// A move is the one geometry change the accessibility tree can absorb
581    /// without being rebuilt: nothing about a widget's *content* depends
582    /// on where it sits, so its node and every text run under it can be
583    /// re-placed in the cached tree by the same delta. A scroll frame
584    /// moves every descendant of the scroll area, so this is the common
585    /// case and re-walking for it was what made the AT tree go stale
586    /// instead — the walk was too expensive to run per frame, so it was
587    /// not run at all and every node's bounds drifted.
588    a11y_moved: std::collections::HashMap<WidgetId, teksilo_canvas::Point>,
589    /// Set when any widget's box changed *size* since the last
590    /// accessibility walk.
591    ///
592    /// A resize is not absorbable: a wrapped label re-wraps, so its lines —
593    /// and therefore its text runs — are a different set, not the same set
594    /// somewhere else.
595    a11y_resized: bool,
596    /// True while [`measure_intrinsic`](Self::measure_intrinsic) is running.
597    /// In this mode `cached_layout_response` measures even dormant widgets
598    /// (and their dormant subtrees) and bypasses the cache, so an adaptive
599    /// container can size an item it intends to keep hidden without that size
600    /// leaking into the normal per-pass cache.
601    measuring: std::cell::Cell<bool>,
602    /// Active↔Dormant transitions of nodes carrying an `activation_signal`,
603    /// recorded by [`set_dormant`](Self::set_dormant) / [`activate`](Self::activate)
604    /// and drained by `WidgetTree::flush_activation_signals` *after* the
605    /// mutation completes. Signals are fired at the tree level, never from
606    /// inside the arena recursion — mirroring how `focus_within` /
607    /// `hover_within` are updated from `WidgetTree` methods rather than mid
608    /// mutation, so an observer (e.g. a `WebView`'s `set_visible`, which on a
609    /// real backend is an OS call) never runs while the arena is being walked.
610    /// Only nodes with a signal contribute, so the buffer is empty for the
611    /// overwhelming majority of trees.
612    pending_activation_changes: Vec<(WidgetId, bool)>,
613    /// Every node that installed an `effective_enabled_signal`, so the
614    /// per-pass refresh visits only opted-in nodes instead of the whole arena.
615    /// Unlike `pending_activation_changes` this is NOT a change queue: an
616    /// ancestor's `enabled` prop is a `Signal` that can flip at any time
617    /// without the arena being told, so there is no single mutation site to
618    /// record a transition at. The refresh recomputes and diffs instead —
619    /// see `WidgetTree::flush_effective_enabled_signals`. Dead ids are pruned
620    /// there, so a destroyed widget cannot leak.
621    effective_enabled_watchers: Vec<WidgetId>,
622}
623
624/// Hashable key for a [`teksilo_canvas::SizeProposal`] used by the per-pass
625/// layout cache. Each axis is encoded to a `u64`: `None` → a sentinel
626/// distinct from any finite `f32`, `Some(v)` → the canonicalized `f32` bits
627/// (`-0.0` folded to `0.0`, all NaNs folded to one pattern) so two equal
628/// proposals always hash and compare equal.
629#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
630struct ProposalKey([u64; 2]);
631
632impl ProposalKey {
633    fn from_proposal(p: teksilo_canvas::SizeProposal) -> Self {
634        fn axis_bits(v: Option<f32>) -> u64 {
635            match v {
636                // `f32::to_bits()` widens into 0..=u32::MAX, so u64::MAX is a
637                // safe sentinel that no `Some(_)` can collide with.
638                None => u64::MAX,
639                Some(f) => {
640                    let canon = if f == 0.0 {
641                        0.0
642                    } else if f.is_nan() {
643                        f32::NAN
644                    } else {
645                        f
646                    };
647                    canon.to_bits() as u64
648                }
649            }
650        }
651        Self([axis_bits(p.width), axis_bits(p.height)])
652    }
653}
654
655impl WidgetArena {
656    pub fn new() -> Self {
657        Self {
658            nodes: SlotMap::with_key(),
659            theme_override_count: 0,
660            cached_roots: Vec::new(),
661            roots_dirty: true,
662            layout_cache: std::cell::RefCell::new(std::collections::HashMap::new()),
663            measuring: std::cell::Cell::new(false),
664            a11y_moved: std::collections::HashMap::new(),
665            a11y_resized: false,
666            pending_activation_changes: Vec::new(),
667            effective_enabled_watchers: Vec::new(),
668        }
669    }
670
671    /// Record what a bounds change means for the accessibility tree.
672    ///
673    /// Called by the layout pass at each of its two bounds writers, after
674    /// the node has been updated. Same size = a move the cached tree can
675    /// absorb; any size change = a rebuild.
676    pub(crate) fn note_bounds_change(
677        &mut self,
678        id: WidgetId,
679        previous: teksilo_canvas::Rect,
680        current: teksilo_canvas::Rect,
681    ) {
682        if previous.width != current.width || previous.height != current.height {
683            self.a11y_resized = true;
684            self.a11y_moved.remove(&id);
685            return;
686        }
687        let delta = teksilo_canvas::Point::new(current.x - previous.x, current.y - previous.y);
688        // A widget can move several times between two walks; the cached
689        // tree only ever sees the total.
690        let entry = self
691            .a11y_moved
692            .entry(id)
693            .or_insert(teksilo_canvas::Point::new(0.0, 0.0));
694        entry.x += delta.x;
695        entry.y += delta.y;
696    }
697
698    /// Whether any widget changed size since the last accessibility walk,
699    /// clearing the flag.
700    pub(crate) fn take_a11y_resized(&mut self) -> bool {
701        std::mem::take(&mut self.a11y_resized)
702    }
703
704    /// The widgets that moved since the last accessibility walk, clearing
705    /// the record.
706    pub(crate) fn take_a11y_moved(
707        &mut self,
708    ) -> std::collections::HashMap<WidgetId, teksilo_canvas::Point> {
709        std::mem::take(&mut self.a11y_moved)
710    }
711
712    /// Clear the per-pass layout memoization cache. Called once at the start of
713    /// each layout pass — geometry (and therefore `layout_response` results)
714    /// may change between passes, so the cache is valid only within one pass.
715    pub(crate) fn clear_layout_cache(&self) {
716        self.layout_cache.borrow_mut().clear();
717    }
718
719    /// Compute a widget's layout response, memoized per `(id, proposal)` for
720    /// the current layout pass. Returns `None` if the id is missing or
721    /// dormant. Widgets that opt out via `Widget::cacheable_layout() == false`
722    /// (e.g. the inspector's bounds tracker, which deliberately mutates signals
723    /// in `layout_response`) bypass the cache so their side effect fires on
724    /// every call.
725    ///
726    /// The key is `(id, proposal)` only: `layout_response` also reads the
727    /// `LayoutContext` (resolved theme, layout direction, text backend), but
728    /// those are a stable function of `id` within a single pass, so the pair
729    /// uniquely determines the input.
730    pub(crate) fn cached_layout_response(
731        &self,
732        id: WidgetId,
733        proposal: teksilo_canvas::SizeProposal,
734        ctx: &crate::widget::LayoutContext,
735    ) -> Option<crate::widget::LayoutResponse> {
736        let node = self.nodes.get(id)?;
737        let measuring = self.measuring.get();
738        if node.activation != ActivationState::Active && !measuring {
739            return None;
740        }
741        // While measuring intrinsic sizes (incl. of dormant subtrees), bypass
742        // the cache entirely so a dormant widget's size never pollutes the
743        // normal per-pass cache.
744        if measuring || !node.widget.cacheable_layout() {
745            return Some(node.widget.layout_response(proposal, ctx));
746        }
747        let key = (id, ProposalKey::from_proposal(proposal));
748        // Scope the shared borrow so it is released before `layout_response`
749        // runs — that call recurses into children, which borrow the same
750        // `layout_cache` (read, then write) and would otherwise alias.
751        {
752            if let Some(cached) = self.layout_cache.borrow().get(&key) {
753                return Some(*cached);
754            }
755        }
756        let resp = node.widget.layout_response(proposal, ctx);
757        self.layout_cache.borrow_mut().insert(key, resp);
758        Some(resp)
759    }
760
761    /// Measure a widget's intrinsic `layout_response` size for `proposal`,
762    /// **regardless of activation** — including dormant/collapsed widgets and
763    /// their dormant subtrees. Returns `None` only if the id is absent.
764    ///
765    /// Adaptive containers (e.g. an overflow [`Toolbar`](crate) that collapses
766    /// items into a menu) use this to size an item they intend to keep hidden,
767    /// so they can decide when to show it again as space grows — something
768    /// `child_layout_response` cannot do, since it returns `None` for inactive
769    /// widgets.
770    ///
771    /// Runs uncached (a dormant widget's size never enters the per-pass cache)
772    /// and is re-entrant-safe (saves/restores the measuring flag). Calls
773    /// `layout_response`, which must be idempotent (see
774    /// [`Widget::cacheable_layout`]).
775    pub(crate) fn measure_intrinsic(
776        &self,
777        id: WidgetId,
778        proposal: teksilo_canvas::SizeProposal,
779        ctx: &crate::widget::LayoutContext,
780    ) -> Option<teksilo_canvas::Size> {
781        if !self.nodes.contains_key(id) {
782            return None;
783        }
784        let prev = self.measuring.replace(true);
785        // `cached_layout_response` (and every nested child query during this
786        // call) sees `measuring == true`, so it bypasses the active check and
787        // the cache for the whole subtree.
788        let resp = self.cached_layout_response(id, proposal, ctx);
789        self.measuring.set(prev);
790        resp.map(|r| r.size)
791    }
792
793    /// Insert a widget into the arena as a root-level widget.
794    pub fn insert(&mut self, widget: Box<dyn Widget>) -> WidgetId {
795        self.roots_dirty = true;
796        let children = widget.children();
797        let id = self.nodes.insert(WidgetNode::new(widget, None));
798        // Set up parent-child for declared children
799        for &child_id in &children {
800            if let Some(child_node) = self.nodes.get_mut(child_id) {
801                child_node.parent = Some(id);
802            }
803        }
804        if let Some(node) = self.nodes.get_mut(id) {
805            node.children = children;
806        }
807        id
808    }
809
810    /// Insert a widget as a child of the given parent.
811    pub fn insert_child(&mut self, parent: WidgetId, widget: Box<dyn Widget>) -> WidgetId {
812        assert!(
813            self.nodes.contains_key(parent),
814            "insert_child() called with invalid parent WidgetId {parent:?}"
815        );
816        self.roots_dirty = true;
817        let children = widget.children();
818        let id = self.nodes.insert(WidgetNode::new(widget, Some(parent)));
819        // Set up parent-child for declared children
820        for &child_id in &children {
821            if let Some(child_node) = self.nodes.get_mut(child_id) {
822                child_node.parent = Some(id);
823            }
824        }
825        if let Some(node) = self.nodes.get_mut(id) {
826            node.children = children;
827        }
828        if let Some(parent_node) = self.nodes.get_mut(parent) {
829            parent_node.children.push(id);
830        }
831        id
832    }
833
834    pub fn get(&self, id: WidgetId) -> Option<&WidgetNode> {
835        self.nodes.get(id)
836    }
837
838    pub fn get_mut(&mut self, id: WidgetId) -> Option<&mut WidgetNode> {
839        self.nodes.get_mut(id)
840    }
841
842    pub fn children(&self, id: WidgetId) -> &[WidgetId] {
843        self.nodes
844            .get(id)
845            .map(|n| n.children.as_slice())
846            .unwrap_or(&[])
847    }
848
849    pub fn parent(&self, id: WidgetId) -> Option<WidgetId> {
850        self.nodes.get(id).and_then(|n| n.parent)
851    }
852
853    pub fn bounds(&self, id: WidgetId) -> teksilo_canvas::Rect {
854        self.nodes
855            .get(id)
856            .map(|n| n.bounds)
857            .unwrap_or(teksilo_canvas::Rect::ZERO)
858    }
859
860    /// The accumulated 2D affine transform that maps `id`'s pre-transform
861    /// local-space points to screen space — equivalent to the renderer's
862    /// `transform_stack` top by the time it begins painting `id`. Used by
863    /// hit-testing and any consumer that needs to project a node's
864    /// pre-transform bounds into screen space (e.g. teksilo-scene's a11y
865    /// bounds projection of view-transformed scene items).
866    ///
867    /// **Composition order.** Mirrors `crates/teksilo-render/src/renderer.rs`'s
868    /// `PushTransform` handling: each push composes as
869    /// `new_top = device_t.then(prev_top)`, so the deepest (innermost)
870    /// transform is applied **first** to a local point and outer ancestors
871    /// compose afterward. Walking root→leaf, each ancestor's
872    /// `transform_prop` is folded in via `t.then(effective)` (NOT
873    /// `effective.then(t)`).
874    ///
875    /// Returns `Transform2D::IDENTITY` if no ancestor sets a non-identity
876    /// transform, which is the common case (90%+ of widgets).
877    pub fn effective_transform(&self, id: WidgetId) -> teksilo_canvas::Transform2D {
878        // Collect leaf→root, then iterate root→leaf. Composition is
879        // `t_new.then(effective_so_far)` so the outer ancestor is applied
880        // *after* the deeper push — matching the renderer's stack semantic
881        // (`device_t.then(prev_top)` at PushTransform).
882        let mut chain: Vec<WidgetId> = Vec::new();
883        let mut current = Some(id);
884        while let Some(c) = current {
885            chain.push(c);
886            current = self.parent(c);
887        }
888        let mut effective = teksilo_canvas::Transform2D::IDENTITY;
889        for node_id in chain.iter().rev() {
890            if let Some(node) = self.nodes.get(*node_id)
891                && let Some(p) = node.transform_prop.as_ref()
892            {
893                let t = p.get();
894                if !t.is_identity() {
895                    effective = t.then(&effective);
896                }
897            }
898        }
899        effective
900    }
901
902    /// Convert a **window-space** pointer position into the **widget-local**
903    /// coordinate space of `id`'s event handlers — i.e. relative to `id`'s
904    /// top-left, after undoing any transform scopes between the window and
905    /// `id`. This is the single conversion the dispatcher applies before
906    /// handing a position to `on_tap` / `on_drag` / `on_pointer_event`, so
907    /// every handler sees positions in its own local space.
908    ///
909    /// The transform handling mirrors `Self::hit_test_recursive` so the
910    /// position a handler receives is in the same space the hit-test used
911    /// to pick it:
912    /// * A **content** transform node (`content_transform`, e.g.
913    ///   `SceneView`) owns its transform and maps its content itself. The
914    ///   framework feeds such a node positions in its **parent-effective**
915    ///   space (the same space `hit_test_recursive` passes through
916    ///   `inv(transform)`), with **no** bounds-origin subtraction — the
917    ///   node's `view_transform` already accounts for its placement.
918    /// * Any other node (the 90%+ identity case, plus `Scale` / `Rotate`
919    ///   self-transforms) receives widget-local coordinates: undo the full
920    ///   transform chain including its own, then subtract its bounds
921    ///   origin so the result is relative to its top-left.
922    ///
923    /// In the common no-transform case this collapses to
924    /// `window_point - bounds.origin`.
925    pub fn local_pointer_position(
926        &self,
927        id: WidgetId,
928        window_point: teksilo_canvas::Point,
929    ) -> teksilo_canvas::Point {
930        let content_transform = self.get(id).map(|n| n.content_transform).unwrap_or(false);
931        if content_transform {
932            // Parent-effective space, no origin subtraction (the node's
933            // own transform consumes these coordinates).
934            let to_parent = self
935                .parent(id)
936                .map(|p| self.effective_transform(p))
937                .unwrap_or(teksilo_canvas::Transform2D::IDENTITY);
938            return match to_parent.inverse() {
939                Some(inv) => inv.apply_point(window_point),
940                None => window_point,
941            };
942        }
943        let in_local = match self.effective_transform(id).inverse() {
944            Some(inv) => inv.apply_point(window_point),
945            // Degenerate transform: fall back to the raw point rather than
946            // dropping the event.
947            None => window_point,
948        };
949        let bounds = self.bounds(id);
950        teksilo_canvas::Point::new(in_local.x - bounds.x, in_local.y - bounds.y)
951    }
952
953    /// Get all root-level widget IDs (widgets with no parent).
954    pub fn roots(&self) -> Vec<WidgetId> {
955        if self.roots_dirty {
956            // Fall back to scanning when cache is stale.
957            // refresh_roots() should be called from layout() for the fast path.
958            return self
959                .nodes
960                .iter()
961                .filter(|(_, node)| node.parent.is_none())
962                .map(|(id, _)| id)
963                .collect();
964        }
965        self.cached_roots.clone()
966    }
967
968    /// Refresh the cached roots list. Call once per frame from layout().
969    pub fn refresh_roots(&mut self) {
970        if self.roots_dirty {
971            self.cached_roots = self
972                .nodes
973                .iter()
974                .filter(|(_, node)| node.parent.is_none())
975                .map(|(id, _)| id)
976                .collect();
977            self.roots_dirty = false;
978        }
979    }
980
981    /// Walk the active widget tree at `point` and return the deepest
982    /// widget under it (the front-most hit, last child wins). Honors
983    /// `event_pass_through` (such nodes pass through to whatever sits
984    /// behind them but their descendants are still hit-testable). Does
985    /// not consider overlays — for the full pointer-routing hit-test
986    /// see `WidgetTree::hit_test`.
987    ///
988    /// `exclude`: if `Some(id)`, that widget (and any descendants
989    /// within its subtree) are skipped during the walk. Used by the
990    /// debug inspector's picker tool to ignore the picker overlay
991    /// itself, and by drag-and-drop to ignore the drag preview.
992    pub fn hit_test_at(
993        &self,
994        point: teksilo_canvas::Point,
995        exclude: Option<WidgetId>,
996    ) -> Option<WidgetId> {
997        self.hit_test_at_with(point, exclude, &HitContext::mouse())
998    }
999
1000    /// [`hit_test_at`](Self::hit_test_at) on behalf of a named pointer.
1001    ///
1002    /// The **exact** pass only: `Widget::hit_outset` is consulted (so a grip
1003    /// wins over what it overlaps for the kind that asked), but no slop
1004    /// re-attribution happens. Callers that want re-attribution too use
1005    /// [`hit_test_at_with_slop`](Self::hit_test_at_with_slop).
1006    pub fn hit_test_at_with(
1007        &self,
1008        point: teksilo_canvas::Point,
1009        exclude: Option<WidgetId>,
1010        hit: &HitContext<'_>,
1011    ) -> Option<WidgetId> {
1012        let roots = self.roots();
1013        // Roots take the outset pre-pass too, so a grip that happens to be a
1014        // top-level node behaves like one nested anywhere else. The window is
1015        // its "parent", and the window does not clip — and, having no widget,
1016        // it vetoes nothing.
1017        let no_veto = |_: WidgetId| false;
1018        if let Some(grip) = self.outset_hit(&roots, point, exclude, hit, &no_veto) {
1019            return Some(grip);
1020        }
1021        for &root in roots.iter().rev() {
1022            if let Some(found) = self.hit_test_recursive(root, point, exclude, hit) {
1023                return Some(found);
1024            }
1025        }
1026        None
1027    }
1028
1029    /// The full two-stage hit test: the exact pass, then — **only when it found
1030    /// nothing eligible** — the nearest-candidate slop pass.
1031    ///
1032    /// Returns whatever the exact pass returned unless a slop candidate is
1033    /// strictly closer than the bubble owner's uninflated shape. See
1034    /// [`hit_candidates`](Self::hit_candidates) for the eligibility rules and
1035    /// `docs/density-and-targets.md` for the prose.
1036    ///
1037    /// For a mouse this is [`hit_test_at`](Self::hit_test_at): the mouse slop
1038    /// radius is `0.0` at every density, so the second stage short-circuits
1039    /// before it walks anything.
1040    pub fn hit_test_at_with_slop(
1041        &self,
1042        point: teksilo_canvas::Point,
1043        exclude: Option<WidgetId>,
1044        hit: &HitContext<'_>,
1045    ) -> Option<WidgetId> {
1046        let exact = self.hit_test_at_with(point, exclude, hit);
1047        self.apply_slop(self.roots(), point, exclude, hit, exact)
1048    }
1049
1050    /// [`hit_test_in_subtree`](Self::hit_test_in_subtree) with the slop pass,
1051    /// scoped so candidates never leave `start`'s subtree.
1052    ///
1053    /// This is what restricts the pass to the topmost overlay layer the exact
1054    /// pass entered: the tree calls it with the overlay's content root, so a
1055    /// press inside a menu can never be re-attributed to a control on the page
1056    /// behind it.
1057    pub fn hit_test_in_subtree_with_slop(
1058        &self,
1059        start: WidgetId,
1060        point: teksilo_canvas::Point,
1061        exclude: Option<WidgetId>,
1062        hit: &HitContext<'_>,
1063    ) -> Option<WidgetId> {
1064        let exact = self.hit_test_recursive(start, point, exclude, hit);
1065        self.apply_slop(vec![start], point, exclude, hit, exact)
1066    }
1067
1068    /// Hit-test starting from a specific subtree root rather than the
1069    /// arena's top-level roots. Same semantics as
1070    /// [`hit_test_at`](Self::hit_test_at) but scoped — useful when
1071    /// callers want to ignore everything outside a known subtree
1072    /// (e.g. the inspector's picker hit-tests inside the user-root
1073    /// subtree so it never resolves to its own chrome).
1074    pub fn hit_test_in_subtree(
1075        &self,
1076        start: WidgetId,
1077        point: teksilo_canvas::Point,
1078    ) -> Option<WidgetId> {
1079        self.hit_test_recursive(start, point, None, &HitContext::mouse())
1080    }
1081
1082    /// Like [`hit_test_in_subtree`](Self::hit_test_in_subtree) but also
1083    /// excludes a widget (and its descendants) from the walk. Lets the
1084    /// overlay / drag-and-drop hit-test reuse the single canonical recursion
1085    /// in `hit_test_recursive` instead of duplicating it.
1086    pub fn hit_test_in_subtree_excluding(
1087        &self,
1088        start: WidgetId,
1089        point: teksilo_canvas::Point,
1090        exclude: Option<WidgetId>,
1091    ) -> Option<WidgetId> {
1092        self.hit_test_recursive(start, point, exclude, &HitContext::mouse())
1093    }
1094
1095    /// [`hit_test_in_subtree_excluding`](Self::hit_test_in_subtree_excluding)
1096    /// on behalf of a named pointer. Exact pass only.
1097    pub fn hit_test_in_subtree_with(
1098        &self,
1099        start: WidgetId,
1100        point: teksilo_canvas::Point,
1101        exclude: Option<WidgetId>,
1102        hit: &HitContext<'_>,
1103    ) -> Option<WidgetId> {
1104        self.hit_test_recursive(start, point, exclude, hit)
1105    }
1106
1107    fn hit_test_recursive(
1108        &self,
1109        id: WidgetId,
1110        point: teksilo_canvas::Point,
1111        exclude: Option<WidgetId>,
1112        hit: &HitContext<'_>,
1113    ) -> Option<WidgetId> {
1114        if !self.is_active(id) || Some(id) == exclude {
1115            return None;
1116        }
1117        // Decorative subtree: skip this node and ALL its descendants so
1118        // the point falls through to whatever is painted behind. Checked
1119        // before descending into children (the difference from
1120        // `event_pass_through`, which is applied only after the children
1121        // miss).
1122        if self.get(id).map(|n| n.hit_transparent).unwrap_or(false) {
1123            return None;
1124        }
1125        let space = self.hit_space(id, point)?;
1126        let HitSpace {
1127            bounds_point,
1128            child_point,
1129            bounds,
1130            ..
1131        } = space;
1132        if !bounds.contains(bounds_point) {
1133            return None;
1134        }
1135        // Shape rejection: a widget with a non-rectangular silhouette (an
1136        // ellipse / cloud scene node, a circular handle) can reject a point
1137        // that is inside its bounding box but outside its actual shape via
1138        // `Widget::hit_shape`. Returning None here lets the caller's
1139        // reverse-sibling loop fall through to whatever is painted
1140        // underneath — the same path `event_pass_through` takes, but
1141        // shape-aware (only the rejected sub-region falls through, not the
1142        // whole widget). Default `hit_shape` returns true, so rectangular
1143        // widgets take this branch for free with no behavior change.
1144        if let Some(node) = self.get(id)
1145            && !node.widget.hit_shape(bounds_point, bounds)
1146        {
1147            return None;
1148        }
1149        let pass_through = self.get(id).map(|n| n.event_pass_through).unwrap_or(false);
1150        let children: Vec<WidgetId> = self.children(id).to_vec();
1151        // A child that declares a `Widget::hit_outset` is offered the point
1152        // BEFORE the ordinary reverse-sibling walk, so a thin grip wins over
1153        // whatever it overlaps rather than losing to whichever neighbour is
1154        // painted on top of it. Only the ring OUTSIDE a child's own bounds is
1155        // resolved here — a point genuinely inside a child falls through to the
1156        // normal walk below, which resolves descendants and honours
1157        // `hit_shape`, so declaring an outset never changes where an in-bounds
1158        // press lands.
1159        // A parent that owns a second picking system over the same area gets
1160        // to veto a child for this point — see `Widget::accepts_child_hit`.
1161        // Resolved once here and threaded into `outset_hit`, so a grip cannot
1162        // sneak past a veto the ordinary walk would have honoured.
1163        let parent = self.get(id);
1164        let vetoes = |child: WidgetId| {
1165            parent.is_some_and(|node| !node.widget.accepts_child_hit(child, child_point))
1166        };
1167        if let Some(grip) = self.outset_hit(&children, child_point, exclude, hit, &vetoes) {
1168            return Some(grip);
1169        }
1170        for &child in children.iter().rev() {
1171            if vetoes(child) {
1172                continue;
1173            }
1174            if let Some(found) = self.hit_test_recursive(child, child_point, exclude, hit) {
1175                return Some(found);
1176            }
1177        }
1178        if pass_through {
1179            return None;
1180        }
1181        Some(id)
1182    }
1183
1184    /// The outset pre-pass over one parent's children.
1185    ///
1186    /// A child that declares an outset is offered the point against its
1187    /// **inflated** bounds, ahead of the ordinary reverse-sibling walk, so a
1188    /// thin grip wins over whatever is painted on top of it — both in its ring
1189    /// and in its own body, which is the whole point of a splitter gutter lying
1190    /// under two panes.
1191    ///
1192    /// Ordering is by distance to the child's own uninflated rectangle, so two
1193    /// adjacent grips whose rings overlap split the difference at the midpoint
1194    /// rather than letting sibling order decide; ties go to the later sibling,
1195    /// which is the one painted on top.
1196    ///
1197    /// A candidate is resolved through the ordinary recursion first, so a
1198    /// descendant inside the grip still wins and `hit_shape` is still honoured;
1199    /// only a point genuinely in the ring — outside the child's real bounds —
1200    /// resolves to the child itself. A candidate that resolves to nothing hands
1201    /// over to the next-nearest, and finally to the normal walk.
1202    ///
1203    /// `vetoes` is the parent's own per-point rejection
1204    /// ([`Widget::accepts_child_hit`]),
1205    /// applied here as well as in the ordinary walk — a grip must not win a
1206    /// point the parent has already refused for it.
1207    fn outset_hit(
1208        &self,
1209        children: &[WidgetId],
1210        point: teksilo_canvas::Point,
1211        exclude: Option<WidgetId>,
1212        hit: &HitContext<'_>,
1213        vetoes: &dyn Fn(WidgetId) -> bool,
1214    ) -> Option<WidgetId> {
1215        // Almost every parent has no outset-declaring child at all, so the
1216        // common case allocates nothing and returns on the first loop.
1217        let mut candidates: Vec<(WidgetId, f32, bool)> = Vec::new();
1218        // Walked topmost-first so that, after a STABLE ascending sort, two
1219        // grips at exactly the same distance are resolved in paint order.
1220        for &child in children.iter().rev() {
1221            if !self.is_active(child) || Some(child) == exclude {
1222                continue;
1223            }
1224            let Some(node) = self.get(child) else {
1225                continue;
1226            };
1227            // A decorative or pass-through node never absorbs a press, so
1228            // widening it would only punch a hole in whatever is behind it.
1229            // `no_hit_slop` is the head of the precedence chain and turns off
1230            // BOTH widening mechanisms.
1231            if node.hit_transparent || node.event_pass_through || node.no_hit_slop {
1232                continue;
1233            }
1234            let outset = node.widget.hit_outset(hit.kind(), hit.tokens());
1235            let (top, bottom) = (finite(outset.top), finite(outset.bottom));
1236            let (leading, trailing) = (finite(outset.leading), finite(outset.trailing));
1237            if top <= 0.0 && bottom <= 0.0 && leading <= 0.0 && trailing <= 0.0 {
1238                continue;
1239            }
1240            // The parent's per-point veto applies here too: a grip that the
1241            // ordinary walk would refuse must not win by being offered first.
1242            //
1243            // Asked **after** the zero-outset test, not before. Almost no child
1244            // declares an outset, and this predicate is a real per-point query
1245            // (the `SceneView`'s is a snapshot scan), so asking it first made
1246            // every hit test on a vetoing parent pay it twice per child — once
1247            // here for children that were about to be skipped anyway, and once
1248            // in the ordinary walk. The order does not change the answer: a
1249            // child that survives to `candidates` is exactly one this used to
1250            // reach.
1251            if vetoes(child) {
1252                continue;
1253            }
1254            let Some(space) = self.hit_space(child, point) else {
1255                continue;
1256            };
1257            // Reading order → screen edges.
1258            let (left, right) = match hit.layout_direction() {
1259                crate::environment::LayoutDirection::LeftToRight => (leading, trailing),
1260                crate::environment::LayoutDirection::RightToLeft => (trailing, leading),
1261            };
1262            let inflated = teksilo_canvas::Rect::new(
1263                space.bounds.x - left,
1264                space.bounds.y - top,
1265                space.bounds.width + left + right,
1266                space.bounds.height + top + bottom,
1267            );
1268            if !inflated.contains(space.bounds_point) {
1269                continue;
1270            }
1271            let inside = space.bounds.contains(space.bounds_point);
1272            let distance =
1273                crate::pointer::hit_slop::rect_distance(space.bounds, space.bounds_point);
1274            candidates.push((child, distance, inside));
1275        }
1276        if candidates.is_empty() {
1277            return None;
1278        }
1279        candidates.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
1280        for (child, _, inside) in candidates {
1281            if let Some(found) = self.hit_test_recursive(child, point, exclude, hit) {
1282                return Some(found);
1283            }
1284            // The ring: the point is outside the child's real bounds, so the
1285            // ordinary recursion could never have found it, and the outset is
1286            // the whole reason it is being offered.
1287            if !inside {
1288                return Some(child);
1289            }
1290            // Inside the bounds but the recursion declined (a `hit_shape`
1291            // rejection, an empty pass-through): the outset has nothing to add,
1292            // so hand back to the normal walk.
1293        }
1294        None
1295    }
1296
1297    /// Resolve one node's transform for hit-testing: the point to test its own
1298    /// bounds against, the point to hand its children, and its bounds.
1299    ///
1300    /// The input point arrives in this node's parent-effective space. A
1301    /// `set_transform` scope is composed by the render walker around this
1302    /// node's subtree, so hit-testing mirrors it by inverse-applying the
1303    /// transform once. *Which* rectangle the transform applies to depends
1304    /// on whether it's a **content** transform or a **self** transform
1305    /// (see `WidgetNode::content_transform`):
1306    ///
1307    /// * A **content** transform (`content_transform`, e.g. `SceneView`) is
1308    ///   a fixed viewport: its bounds are a rectangle in PARENT space and
1309    ///   the transform pans / zooms only its CONTENT. Test the bounds
1310    ///   against the parent-space point; inverse-transform only for
1311    ///   descending into children, so the whole visible viewport stays
1312    ///   interactive regardless of pan / zoom. (Without this, panning the
1313    ///   content shifts the hittable region off the viewport — clicks /
1314    ///   wheel over the visible scene fall through to whatever is behind.)
1315    /// * A **self** transform (`Scale` / `Rotate`, whose own bounds move
1316    ///   with the transform) inverse-transforms first, then tests its
1317    ///   bounds in the resulting local space (a click lands where the
1318    ///   scaled / rotated visual actually is).
1319    ///
1320    /// Identity / missing transforms collapse both paths to the scalar
1321    /// case, so the hot path stays cheap. `content_transform` is
1322    /// `SceneView`-only today, so this only changes SceneView hit-testing;
1323    /// `Scale` / `Rotate` (also `clips_children`) keep the self-transform
1324    /// path.
1325    ///
1326    /// `None` when the transform is singular (a collapsed axis) — that hides
1327    /// the entire subtree visually, and hit-testing mirrors it.
1328    fn hit_space(&self, id: WidgetId, point: teksilo_canvas::Point) -> Option<HitSpace> {
1329        let transform = self
1330            .get(id)
1331            .and_then(|n| n.transform_prop.as_ref())
1332            .map(|p| p.get())
1333            .filter(|t| !t.is_identity());
1334        let content_transform = self.get(id).map(|n| n.content_transform).unwrap_or(false);
1335        let child_point = match transform {
1336            Some(t) => t.inverse()?.apply_point(point),
1337            None => point,
1338        };
1339        let bounds_point = if content_transform {
1340            point
1341        } else {
1342            child_point
1343        };
1344        Some(HitSpace {
1345            bounds_point,
1346            child_point,
1347            bounds: self.bounds(id),
1348            scale: transform
1349                .as_ref()
1350                .map(crate::pointer::hit_slop::min_singular_value)
1351                .unwrap_or(1.0),
1352        })
1353    }
1354
1355    /// Every node the *miss-only* slop pass would consider for `point`, nearest
1356    /// first, scoped to `start`'s subtree.
1357    ///
1358    /// Public so a test — and the target-conformance audit — can inspect the
1359    /// pass's reasoning rather than only its verdict. Returning candidates does
1360    /// **not** mean one of them wins: see
1361    /// [`hit_test_at_with_slop`](Self::hit_test_at_with_slop) for the
1362    /// bubble-path rule that decides.
1363    ///
1364    /// # Eligibility
1365    ///
1366    /// A node is a candidate only if all of the following hold. Each is pinned
1367    /// by its own test in `widget_tree::hit_targeting_tests`.
1368    ///
1369    /// * It earns a non-zero outset from its resolved [`HitSlop`] — which, by
1370    ///   the size formula, excludes anything already at least `up_to` on its
1371    ///   smaller axis. A scrim, a page, a list row are excluded by arithmetic.
1372    /// * It would actually *do* something with the press:
1373    ///   [`takes_a_press`](Self::takes_a_press). Re-attributing to a node that
1374    ///   ignores presses would silently swallow one.
1375    /// * It is **enabled** — its own `enabled_state` and every ancestor's.
1376    /// * It is not **read-only**, as reported by the context's probe.
1377    /// * It does not carry `no_hit_slop`, and it is not `event_pass_through`
1378    ///   (which absorbs nothing; its **children** stay eligible).
1379    /// * It is not inside a `hit_transparent` subtree — those are pruned whole.
1380    /// * No `clips_children` ancestor's **uninflated** rectangle excludes the
1381    ///   point: slop never reaches out of a scroller.
1382    /// * Its [`Widget::hit_distance`] answers `Some(d)` with `0 < d ≤ outset`.
1383    ///   `d = 0` means the point is inside the shape, which is the exact pass's
1384    ///   business — the slop pass only ever re-attributes a genuine miss.
1385    ///
1386    /// Distances are measured in each node's own space and converted to screen
1387    /// dp through the accumulated
1388    /// [`min_singular_value`](crate::pointer::hit_slop::min_singular_value) of
1389    /// the transforms above it. For a chain of transforms the product of the
1390    /// per-node minima is a lower bound on the true composed minimum, so the
1391    /// reach under a stack of transforms errs towards being generous rather
1392    /// than short.
1393    ///
1394    /// [`HitSlop`]: crate::pointer::hit_slop::HitSlop
1395    /// [`Widget::hit_distance`]: crate::widget::Widget::hit_distance
1396    pub fn hit_candidates(
1397        &self,
1398        start: WidgetId,
1399        point: teksilo_canvas::Point,
1400        exclude: Option<WidgetId>,
1401        hit: &HitContext<'_>,
1402    ) -> Vec<HitCandidate> {
1403        let mut out = Vec::new();
1404        if hit.slop_enabled() {
1405            self.collect_candidates(start, point, 1.0, true, exclude, hit, &mut out);
1406            out.sort_by(|a, b| {
1407                a.distance
1408                    .partial_cmp(&b.distance)
1409                    .unwrap_or(std::cmp::Ordering::Equal)
1410            });
1411        }
1412        out
1413    }
1414
1415    #[allow(clippy::too_many_arguments)]
1416    fn collect_candidates(
1417        &self,
1418        id: WidgetId,
1419        point: teksilo_canvas::Point,
1420        scale: f32,
1421        enabled: bool,
1422        exclude: Option<WidgetId>,
1423        hit: &HitContext<'_>,
1424        out: &mut Vec<HitCandidate>,
1425    ) {
1426        if !self.is_active(id) || Some(id) == exclude {
1427            return;
1428        }
1429        let Some(node) = self.get(id) else { return };
1430        // Decorative subtree: pruned whole, exactly as in the exact pass.
1431        if node.hit_transparent {
1432            return;
1433        }
1434        let Some(space) = self.hit_space(id, point) else {
1435            return;
1436        };
1437        // Slop never escapes a clipping ancestor's UNINFLATED rectangle: a
1438        // control scrolled out of a `ScrollArea` must not catch a press landing
1439        // on the scroller's border.
1440        if node.clips_children && !space.bounds.contains(space.bounds_point) {
1441            return;
1442        }
1443        let enabled = enabled
1444            && node
1445                .enabled_state
1446                .as_ref()
1447                .map(|state| state.get())
1448                .unwrap_or(true);
1449        let scale_children = scale * space.scale;
1450        // A content transform leaves the node's own bounds in parent space; a
1451        // self transform moves them with it.
1452        let scale_self = if node.content_transform {
1453            scale
1454        } else {
1455            scale_children
1456        };
1457        if enabled
1458            && !node.no_hit_slop
1459            && !node.event_pass_through
1460            && !hit.is_read_only(id)
1461            && self.takes_a_press(id)
1462        {
1463            let slop = node
1464                .hit_slop
1465                .or_else(|| node.widget.hit_slop(hit.kind(), hit.tokens()))
1466                .unwrap_or_else(|| hit.default_slop());
1467            let outset = slop.outset_for(space.bounds.size());
1468            if outset > 0.0
1469                && let Some(local) = node.widget.hit_distance(space.bounds_point, space.bounds)
1470            {
1471                let distance = local * scale_self;
1472                if distance > 0.0 && distance <= outset && distance.is_finite() {
1473                    out.push(HitCandidate {
1474                        id,
1475                        distance,
1476                        outset,
1477                    });
1478                }
1479            }
1480        }
1481        for &child in self.children(id) {
1482            self.collect_candidates(
1483                child,
1484                space.child_point,
1485                scale_children,
1486                enabled,
1487                exclude,
1488                hit,
1489                out,
1490            );
1491        }
1492    }
1493
1494    /// Whether a press landing on this node would do anything at all — the
1495    /// definition of an "eligible handler" for the slop pass's bubble-path
1496    /// rule.
1497    ///
1498    /// A node qualifies if it carries any pointer-facing handler (tap, multi
1499    /// tap, long press, drag, swipe, pinch, the raw pointer stream, scroll) or
1500    /// is focusable, and is enabled. Accessibility actions and key handlers do
1501    /// not count: neither is reachable from a pointer.
1502    pub fn takes_a_press(&self, id: WidgetId) -> bool {
1503        let Some(node) = self.get(id) else {
1504            return false;
1505        };
1506        if !self.is_enabled(id) {
1507            return false;
1508        }
1509        let pointer_facing = |h: &crate::event_handlers::EventHandlers| {
1510            h.on_tap.is_some()
1511                || h.on_double_tap.is_some()
1512                || h.on_triple_tap.is_some()
1513                || h.on_long_press.is_some()
1514                || h.on_drag.is_some()
1515                || h.on_swipe.is_some()
1516                || h.on_pinch.is_some()
1517                || h.on_pointer_event.is_some()
1518                || h.on_scroll.is_some()
1519        };
1520        pointer_facing(&node.handlers)
1521            || pointer_facing(&node.external_handlers)
1522            || node.node_focusable.unwrap_or(false)
1523    }
1524
1525    /// Run the miss-only pass over `roots` and decide between it and `exact`.
1526    ///
1527    /// The rule, in one place: the exact hit's **entire bubble path** is
1528    /// examined, and a slop candidate wins only when that path carries no
1529    /// eligible handler at all, or when the candidate is strictly closer than
1530    /// the bubble owner's *uninflated* shape. That is what keeps a press on a
1531    /// row label 5 dp from an inline checkbox on the row — the row owns the
1532    /// press at distance zero, and nothing beats zero.
1533    fn apply_slop(
1534        &self,
1535        roots: Vec<WidgetId>,
1536        point: teksilo_canvas::Point,
1537        exclude: Option<WidgetId>,
1538        hit: &HitContext<'_>,
1539        exact: Option<WidgetId>,
1540    ) -> Option<WidgetId> {
1541        if !hit.slop_enabled() {
1542            return exact;
1543        }
1544        let owner_distance = match exact.and_then(|target| self.bubble_owner(target, &roots)) {
1545            Some(owner) => self.distance_to(owner, point, &roots).unwrap_or(0.0),
1546            // Either nothing was hit, or what was hit ignores presses all the
1547            // way up: there is nothing to beat.
1548            None => f32::INFINITY,
1549        };
1550        if owner_distance <= 0.0 {
1551            return exact;
1552        }
1553        // A grip that won its point through its own `Widget::hit_outset` made a
1554        // deliberate claim *inside* the exact pass, and the miss-only pass must
1555        // not take it back.
1556        //
1557        // Without this the two mechanisms fight, and the outset loses every
1558        // time: a grip only ever claims a point at a positive distance from its
1559        // own shape, so any slop-eligible node under its ring is strictly
1560        // closer and wins. The rule, rather than the arithmetic: a ring is taken
1561        // back wherever a neighbour is still small enough to earn a top-up of
1562        // its own, so raising the density can LOWER a grip's reach — `up_to`
1563        // grows from 24 to 44 dp and rows that earned nothing become candidates.
1564        // It is not confined to the coarse densities either: at Compact a
1565        // neighbour under 24 dp is already a candidate.
1566        //
1567        // The two measurements this rests on are pinned in
1568        // teksilo-target-conformance by
1569        // `an_outsets_claim_survives_the_slop_pass_in_the_shipped_controls`
1570        // (a SearchField's clear button at Compact, a TableView's scroll bar at
1571        // Touch), and the mechanism itself by
1572        // `a_grip_that_won_through_its_outset_keeps_its_point_against_the_slop_pass`
1573        // in this crate. Reverting this branch reddens all three. The precedence
1574        // chain in `docs/density-and-targets.md` names one chain for both
1575        // mechanisms, and this is what keeps it one.
1576        if exact.is_some_and(|target| self.won_through_outset(target, point, &roots, hit)) {
1577            return exact;
1578        }
1579        let mut best: Option<HitCandidate> = None;
1580        for &root in roots.iter().rev() {
1581            for candidate in self.hit_candidates(root, point, exclude, hit) {
1582                if candidate.distance < owner_distance
1583                    && best.is_none_or(|b| candidate.distance < b.distance)
1584                {
1585                    best = Some(candidate);
1586                }
1587            }
1588        }
1589        best.map(|c| c.id).or(exact)
1590    }
1591
1592    /// The deepest node on `target`'s own path (itself, then ancestors, up to
1593    /// and including whichever of `roots` contains it) that would act on a
1594    /// press.
1595    fn bubble_owner(&self, target: WidgetId, roots: &[WidgetId]) -> Option<WidgetId> {
1596        let mut current = Some(target);
1597        while let Some(id) = current {
1598            if self.takes_a_press(id) {
1599                return Some(id);
1600            }
1601            if roots.contains(&id) {
1602                return None;
1603            }
1604            current = self.get(id).and_then(|n| n.parent);
1605        }
1606        None
1607    }
1608
1609    /// Whether `target`, or a node on its path to a root, claimed `point`
1610    /// through its own [`Widget::hit_outset`] — the point sits outside that
1611    /// node's real bounds and inside its inflated ones.
1612    ///
1613    /// The predicate behind the outset's precedence over the miss-only pass in
1614    /// [`apply_slop`](Self::apply_slop). The whole path is examined because the
1615    /// pre-pass resolves a candidate *through* the ordinary recursion, so the
1616    /// node the exact pass returns may be a descendant of the grip that won.
1617    ///
1618    /// [`Widget::hit_outset`]: crate::widget::Widget::hit_outset
1619    fn won_through_outset(
1620        &self,
1621        target: WidgetId,
1622        point: teksilo_canvas::Point,
1623        roots: &[WidgetId],
1624        hit: &HitContext<'_>,
1625    ) -> bool {
1626        let mut chain = vec![target];
1627        let mut current = target;
1628        while !roots.contains(&current) {
1629            match self.get(current).and_then(|n| n.parent) {
1630                Some(parent) => {
1631                    chain.push(parent);
1632                    current = parent;
1633                }
1634                None => break,
1635            }
1636        }
1637        chain.reverse();
1638        let mut p = point;
1639        for &node_id in &chain {
1640            let Some(space) = self.hit_space(node_id, p) else {
1641                return false;
1642            };
1643            let Some(node) = self.get(node_id) else {
1644                return false;
1645            };
1646            if !node.no_hit_slop {
1647                let outset = node.widget.hit_outset(hit.kind(), hit.tokens());
1648                let (top, bottom) = (finite(outset.top), finite(outset.bottom));
1649                let (leading, trailing) = (finite(outset.leading), finite(outset.trailing));
1650                if top > 0.0 || bottom > 0.0 || leading > 0.0 || trailing > 0.0 {
1651                    let (left, right) = match hit.layout_direction() {
1652                        crate::environment::LayoutDirection::LeftToRight => (leading, trailing),
1653                        crate::environment::LayoutDirection::RightToLeft => (trailing, leading),
1654                    };
1655                    let inflated = teksilo_canvas::Rect::new(
1656                        space.bounds.x - left,
1657                        space.bounds.y - top,
1658                        space.bounds.width + left + right,
1659                        space.bounds.height + top + bottom,
1660                    );
1661                    if !space.bounds.contains(space.bounds_point)
1662                        && inflated.contains(space.bounds_point)
1663                    {
1664                        return true;
1665                    }
1666                }
1667            }
1668            p = space.child_point;
1669        }
1670        false
1671    }
1672
1673    /// Distance from a root-space `point` to `id`'s own shape, in screen dp.
1674    ///
1675    /// Walks down from whichever of `roots` owns `id` so the transforms are
1676    /// applied in the same order the hit test applies them, and converts the
1677    /// local distance through the accumulated minimum singular value.
1678    fn distance_to(
1679        &self,
1680        id: WidgetId,
1681        point: teksilo_canvas::Point,
1682        roots: &[WidgetId],
1683    ) -> Option<f32> {
1684        let mut chain = vec![id];
1685        let mut current = id;
1686        while !roots.contains(&current) {
1687            match self.get(current).and_then(|n| n.parent) {
1688                Some(parent) => {
1689                    chain.push(parent);
1690                    current = parent;
1691                }
1692                None => break,
1693            }
1694        }
1695        chain.reverse();
1696        let mut p = point;
1697        let mut scale = 1.0_f32;
1698        for (index, &node_id) in chain.iter().enumerate() {
1699            let space = self.hit_space(node_id, p)?;
1700            if index + 1 == chain.len() {
1701                let scale_self = if self.get(node_id).map(|n| n.content_transform)? {
1702                    scale
1703                } else {
1704                    scale * space.scale
1705                };
1706                let local = self
1707                    .get(node_id)?
1708                    .widget
1709                    .hit_distance(space.bounds_point, space.bounds)?;
1710                return Some(local * scale_self);
1711            }
1712            scale *= space.scale;
1713            p = space.child_point;
1714        }
1715        None
1716    }
1717
1718    /// Iterate over all active widget IDs.
1719    ///
1720    /// Allocating wrapper around [`Self::active_ids_iter`]. Hot-path
1721    /// callers that hold `&self` for the whole iteration should call
1722    /// the iterator directly to avoid the per-call `Vec` allocation;
1723    /// callers that need an owned snapshot (because they mutate
1724    /// arena state inside the loop) should use
1725    /// [`Self::fill_active_ids`] with a reusable buffer.
1726    pub fn active_ids(&self) -> Vec<WidgetId> {
1727        self.active_ids_iter().collect()
1728    }
1729
1730    /// Stream all active widget IDs without allocating. The iterator
1731    /// borrows the arena, so the caller cannot mutate it while
1732    /// iterating — for that case use [`Self::fill_active_ids`].
1733    pub fn active_ids_iter(&self) -> impl Iterator<Item = WidgetId> + '_ {
1734        self.nodes
1735            .iter()
1736            .filter(|(_, node)| node.activation == ActivationState::Active)
1737            .map(|(id, _)| id)
1738    }
1739
1740    /// Fill `out` with every active widget ID. Clears `out` first so
1741    /// callers can reuse a long-lived buffer across calls. Use this
1742    /// when the iteration site needs an owned snapshot independent
1743    /// of the arena borrow (typically because it mutates per-widget
1744    /// state with `arena.get_mut(id)` inside the loop).
1745    pub fn fill_active_ids(&self, out: &mut Vec<WidgetId>) {
1746        out.clear();
1747        out.extend(self.active_ids_iter());
1748    }
1749
1750    /// Set a widget subtree to dormant state (state preserved, not rendered).
1751    /// Recursively dormants all children.
1752    ///
1753    /// The node named here is marked self-parked (`WidgetNode::self_dormant`);
1754    /// the descendants swept along by the recursion are not, since their
1755    /// dormancy belongs to this ancestor rather than to them. That distinction
1756    /// is what lets [`activate`](Self::activate) put the subtree back exactly as
1757    /// it found it instead of waking content that was already closed.
1758    ///
1759    /// **Returns the whole parked subtree**, `id` first, because a caller that
1760    /// cannot see which nodes went to sleep cannot cancel the pointers holding
1761    /// them. Dormancy is invisible to hit-testing and to dispatch, so a widget
1762    /// parked mid-interaction keeps whatever the press latched and never
1763    /// receives another event: the ids are how the tree finds it and tells it
1764    /// to let go. Every caller is audited in `docs/touch-and-pen.md` §3.3.
1765    pub fn set_dormant(&mut self, id: WidgetId) -> Vec<WidgetId> {
1766        let mut parked = Vec::new();
1767        self.park(id, true, &mut parked);
1768        parked
1769    }
1770
1771    /// [`set_dormant`](Self::set_dormant)'s body, plus whether `id` is being
1772    /// parked on its own account or dragged along by an ancestor, and the
1773    /// accumulator the parked ids land in.
1774    ///
1775    /// A node already self-parked stays that way when an ancestor sweeps over
1776    /// it — the flag is only ever set here, never cleared, so nesting two
1777    /// dormancy cycles cannot lose the inner one.
1778    fn park(&mut self, id: WidgetId, on_its_own_account: bool, parked: &mut Vec<WidgetId>) {
1779        if let Some(node) = self.nodes.get_mut(id) {
1780            let was_active = node.activation == ActivationState::Active;
1781            node.activation = ActivationState::Dormant;
1782            if on_its_own_account {
1783                node.self_dormant = true;
1784            }
1785            // Record the Active→Dormant transition for nodes that opted into an
1786            // activation signal; the signal is fired later by
1787            // `WidgetTree::flush_activation_signals`, not here — see the
1788            // `pending_activation_changes` field docs.
1789            if was_active && node.activation_signal.is_some() {
1790                self.pending_activation_changes.push((id, false));
1791            }
1792            parked.push(id);
1793        }
1794        let children: Vec<WidgetId> = self.children(id).to_vec();
1795        for child in children {
1796            self.park(child, false, parked);
1797        }
1798    }
1799
1800    /// Activate a dormant widget subtree (triggers relayout and repaint).
1801    /// Recursively activates all children, **except** those a descendant
1802    /// widget has independently gated off via `visible_when(false)`.
1803    ///
1804    /// The directly-targeted `id` is always activated (the caller asked for
1805    /// it). When recursing, a child whose own `visible_state` currently
1806    /// evaluates to `false` is left dormant along with its subtree: it is
1807    /// hidden by its own gate, not by the ancestor's dormancy, so a parent
1808    /// reactivation must not wake it. This is what keeps a `ComboBox`'s
1809    /// closed dropdown panel, a collapsed overlay, or any `visible_when`-
1810    /// gated child from leaking back to the screen when an ancestor (e.g. a
1811    /// `Toolbar` item reappearing from overflow) is re-activated. The
1812    /// per-pass visibility reconciliation
1813    /// ([`visibility_checks_iter`](Self::visibility_checks_iter)) still owns
1814    /// the eventual activate/dormant transitions when the gate flips.
1815    pub fn activate(&mut self, id: WidgetId) {
1816        if let Some(node) = self.nodes.get_mut(id) {
1817            // Only Dormant→Active is a real "show" transition. Guard on
1818            // `== Dormant` (not `!= Active`) so a `Destroyed` node — or any
1819            // future non-Active state — is never resurrected or signalled.
1820            let was_dormant = node.activation == ActivationState::Dormant;
1821            node.activation = ActivationState::Active;
1822            node.self_dormant = false;
1823            node.dirty.needs_layout = true;
1824            node.dirty.needs_paint = true;
1825            if was_dormant && node.activation_signal.is_some() {
1826                self.pending_activation_changes.push((id, true));
1827            }
1828        }
1829        let children: Vec<WidgetId> = self.children(id).to_vec();
1830        for child in children {
1831            let asleep_on_its_own_account = self
1832                .nodes
1833                .get(child)
1834                .map(|n| {
1835                    n.self_dormant
1836                        || n.visible_state
1837                            .as_ref()
1838                            .map(|vs| !vs.get())
1839                            .unwrap_or(false)
1840                })
1841                .unwrap_or(false);
1842            if asleep_on_its_own_account {
1843                continue;
1844            }
1845            self.activate(child);
1846        }
1847    }
1848
1849    /// Destroy a widget and remove it from the arena entirely.
1850    /// Recursively destroys all children. State is gone.
1851    pub fn destroy(&mut self, id: WidgetId) {
1852        self.roots_dirty = true;
1853        let children: Vec<WidgetId> = self.children(id).to_vec();
1854        for child in children {
1855            self.destroy(child);
1856        }
1857        self.remove_node(id);
1858    }
1859
1860    /// Remove a *single* node: unlink it from its parent's child list and drop
1861    /// it from the arena. Does **not** recurse into its children.
1862    ///
1863    /// The caller owns the recursion. This exists for
1864    /// [`WidgetTree::destroy_subtree`](crate::widget_tree::WidgetTree) /
1865    /// the reconciling rebuild path, which walks the subtree itself so it can
1866    /// honour re-parenting — a child re-homed into the surviving tree must NOT
1867    /// be torn down via this node's now-stale `children` list. Using
1868    /// [`destroy`](Self::destroy) there would re-recurse that stale list and
1869    /// destroy the re-homed survivor.
1870    pub fn remove_node(&mut self, id: WidgetId) {
1871        self.roots_dirty = true;
1872        if let Some(parent_id) = self.parent(id)
1873            && let Some(parent) = self.nodes.get_mut(parent_id)
1874        {
1875            parent.children.retain(|&c| c != id);
1876        }
1877        self.nodes.remove(id);
1878    }
1879
1880    /// Drain the buffered Active↔Dormant transitions recorded since the last
1881    /// call. Each `(id, active)` is fed to `WidgetTree::flush_activation_signals`
1882    /// which fires the node's `activation_signal` — at the tree level, outside
1883    /// any arena mutation.
1884    pub(crate) fn take_activation_changes(&mut self) -> Vec<(WidgetId, bool)> {
1885        std::mem::take(&mut self.pending_activation_changes)
1886    }
1887
1888    /// Record that `id` installed an `effective_enabled_signal`. Idempotent —
1889    /// the signal is install-or-reuse, so a rebuild re-registering the same
1890    /// node must not grow the list.
1891    pub(crate) fn watch_effective_enabled(&mut self, id: WidgetId) {
1892        if !self.effective_enabled_watchers.contains(&id) {
1893            self.effective_enabled_watchers.push(id);
1894        }
1895    }
1896
1897    /// The nodes carrying an `effective_enabled_signal`, for the per-pass
1898    /// refresh. Cloned so the caller can recompute `is_enabled` (an immutable
1899    /// ancestor walk) without holding a borrow on the arena.
1900    pub(crate) fn effective_enabled_watchers(&self) -> Vec<WidgetId> {
1901        self.effective_enabled_watchers.clone()
1902    }
1903
1904    /// Drop watchers whose node is gone (destroyed / rebuilt away).
1905    pub(crate) fn prune_effective_enabled_watchers(&mut self) {
1906        self.effective_enabled_watchers
1907            .retain(|id| self.nodes.contains_key(*id));
1908    }
1909
1910    pub fn is_active(&self, id: WidgetId) -> bool {
1911        self.nodes
1912            .get(id)
1913            .map(|n| n.activation == ActivationState::Active)
1914            .unwrap_or(false)
1915    }
1916
1917    pub fn len(&self) -> usize {
1918        self.nodes.len()
1919    }
1920
1921    pub fn is_empty(&self) -> bool {
1922        self.nodes.is_empty()
1923    }
1924
1925    pub fn mark_all_clean(&mut self) {
1926        for (_, node) in self.nodes.iter_mut() {
1927            node.dirty = DirtyFlags::default();
1928        }
1929    }
1930
1931    pub fn any_needs_layout(&self) -> bool {
1932        self.nodes
1933            .values()
1934            .any(|n| n.activation == ActivationState::Active && n.dirty.needs_layout)
1935    }
1936
1937    pub fn any_needs_paint(&self) -> bool {
1938        self.nodes
1939            .values()
1940            .any(|n| n.activation == ActivationState::Active && n.dirty.needs_paint)
1941    }
1942
1943    pub fn mark_needs_paint(&mut self, id: WidgetId) {
1944        if let Some(node) = self.nodes.get_mut(id) {
1945            node.dirty.needs_paint = true;
1946        }
1947    }
1948
1949    /// Recursively mark a widget and all its descendants needs_paint.
1950    /// Used by callers that want a fresh paint of an entire subtree
1951    /// — e.g. a rich tooltip whose dwell indicator child would
1952    /// otherwise reuse its cached_paint while the parent re-runs
1953    /// some per-frame logic.
1954    pub fn mark_subtree_needs_paint(&mut self, id: WidgetId) {
1955        if let Some(node) = self.nodes.get_mut(id) {
1956            node.dirty.needs_paint = true;
1957        }
1958        let children: Vec<WidgetId> = self.children(id).to_vec();
1959        for child in children {
1960            self.mark_subtree_needs_paint(child);
1961        }
1962    }
1963
1964    pub fn mark_needs_layout(&mut self, id: WidgetId) {
1965        if let Some(node) = self.nodes.get_mut(id) {
1966            node.dirty.needs_layout = true;
1967            node.dirty.needs_paint = true;
1968        }
1969    }
1970
1971    /// Mark a widget as needing its `build()` re-run.
1972    /// Also marks for layout and paint since rebuilt children need both.
1973    pub fn mark_needs_rebuild(&mut self, id: WidgetId) {
1974        if let Some(node) = self.nodes.get_mut(id) {
1975            node.dirty.needs_rebuild = true;
1976            node.dirty.needs_layout = true;
1977            node.dirty.needs_paint = true;
1978        }
1979    }
1980
1981    /// Collect widgets that need their `build()` re-run (data-driven rebuild).
1982    /// Only returns active widgets with `needs_rebuild == true`.
1983    ///
1984    /// Allocating wrapper around [`Self::needs_rebuild_iter`]. Prefer
1985    /// the iterator on hot paths.
1986    pub fn collect_needs_rebuild(&self) -> Vec<WidgetId> {
1987        self.needs_rebuild_iter().collect()
1988    }
1989
1990    /// Stream widgets that need `build()` re-run without allocating.
1991    ///
1992    /// `needs_rebuild` is set only by `BindingLevel::Rebuild` bindings —
1993    /// i.e. on composing widgets that explicitly want `build()` re-run
1994    /// when their data model changes. It is intentionally NOT gated on
1995    /// the widget currently having children: a data-driven widget that
1996    /// builds its children directly and starts EMPTY (e.g. the toast
1997    /// host with no toasts yet, an empty list that renders rows without
1998    /// a persistent container) must still rebuild to materialise its
1999    /// FIRST child. `rebuild_single_widget` handles a childless widget
2000    /// correctly (nothing to tear down, then it adopts `build()`'s
2001    /// output).
2002    pub fn needs_rebuild_iter(&self) -> impl Iterator<Item = WidgetId> + '_ {
2003        self.nodes
2004            .iter()
2005            .filter(|(_, n)| n.activation == ActivationState::Active && n.dirty.needs_rebuild)
2006            .map(|(id, _)| id)
2007    }
2008
2009    /// Check all widgets with visible_state bindings and return
2010    /// (id, is_currently_active, should_be_visible) tuples.
2011    ///
2012    /// Allocating wrapper around [`Self::visibility_checks_iter`].
2013    pub fn visibility_checks(&self) -> Vec<(WidgetId, bool, bool)> {
2014        self.visibility_checks_iter().collect()
2015    }
2016
2017    /// Stream widgets with `visible_state` bindings without
2018    /// allocating. Each entry is `(id, is_currently_active,
2019    /// should_be_visible)`.
2020    pub fn visibility_checks_iter(&self) -> impl Iterator<Item = (WidgetId, bool, bool)> + '_ {
2021        self.nodes.iter().filter_map(|(id, node)| {
2022            node.visible_state.as_ref().map(|state| {
2023                let is_active = node.activation == ActivationState::Active;
2024                let should_be_visible = state.get();
2025                (id, is_active, should_be_visible)
2026            })
2027        })
2028    }
2029
2030    /// Check if a widget is effectively enabled, walking up the parent chain.
2031    ///
2032    /// Returns `false` if the widget itself or any ancestor has `enabled_state`
2033    /// bound to `false`. This lets containers like `GroupBox` disable a whole
2034    /// subtree by binding a single signal on their content wrapper.
2035    pub fn is_enabled(&self, id: WidgetId) -> bool {
2036        let mut current = Some(id);
2037        while let Some(node_id) = current {
2038            if let Some(node) = self.nodes.get(node_id) {
2039                if let Some(ref state) = node.enabled_state
2040                    && !state.get()
2041                {
2042                    return false;
2043                }
2044                current = node.parent;
2045            } else {
2046                return true;
2047            }
2048        }
2049        true
2050    }
2051
2052    /// Set a per-child alignment override on a widget.
2053    pub fn set_alignment_override(&mut self, id: WidgetId, alignment: teksilo_tokens::Alignment) {
2054        if let Some(node) = self.get_mut(id) {
2055            node.alignment_override = Some(alignment);
2056        }
2057    }
2058
2059    /// Mark a widget as clipping its children (scroll area, overflow hidden).
2060    pub fn set_clips_children(&mut self, id: WidgetId, clips: bool) {
2061        if let Some(node) = self.get_mut(id) {
2062            node.clips_children = clips;
2063        }
2064    }
2065
2066    /// The OS-IME descriptor for the widget at `id`, or `None` if the node
2067    /// is not a text-input surface (the default) or the id is unknown. The
2068    /// platform IME layer queries this for the focused widget to decide
2069    /// whether to enable the OS input method and with which purpose.
2070    pub fn ime_context(&self, id: WidgetId) -> Option<crate::ime::ImeContext> {
2071        self.get(id).and_then(|n| n.ime)
2072    }
2073
2074    /// Set (or clear, with `None`) the OS-IME descriptor for the widget at
2075    /// `id`.
2076    pub fn set_ime_context(&mut self, id: WidgetId, ime: Option<crate::ime::ImeContext>) {
2077        if let Some(node) = self.get_mut(id) {
2078            node.ime = ime;
2079        }
2080    }
2081
2082    /// Apply a `HandlerSet` to an existing node, merging handlers and
2083    /// transferring node-level metadata (focusable, cursor, clips,
2084    /// context menu). The `scope` argument controls whether the
2085    /// handlers go into the rebuild-cleared `handlers` slot or the
2086    /// persistent `external_handlers` slot.
2087    pub(crate) fn apply_handler_set(
2088        &mut self,
2089        id: WidgetId,
2090        handler_set: crate::widget_builder::HandlerSet,
2091        scope: HandlerScope,
2092    ) {
2093        if let Some(node) = self.get_mut(id) {
2094            let target = match scope {
2095                HandlerScope::Own => &mut node.handlers,
2096                HandlerScope::External => &mut node.external_handlers,
2097            };
2098            let existing = std::mem::take(target);
2099            *target = existing.merge(handler_set.handlers);
2100            if let Some(focusable) = handler_set.focusable {
2101                node.node_focusable = Some(focusable);
2102            }
2103            if let Some(tab_index) = handler_set.tab_index {
2104                node.node_tab_index = Some(tab_index);
2105            }
2106            if let Some(cursor) = handler_set.cursor {
2107                node.node_cursor = Some(cursor);
2108            }
2109            if let Some(clips) = handler_set.clips_children {
2110                node.clips_children = clips;
2111            }
2112            if let Some(ime) = handler_set.ime {
2113                node.ime = Some(ime);
2114            }
2115            if let Some(pass_through) = handler_set.event_pass_through {
2116                node.event_pass_through = pass_through;
2117            }
2118            if let Some(dead_zone) = handler_set.gesture_dead_zone {
2119                node.gesture_dead_zone = dead_zone;
2120            }
2121            if let Some(role) = handler_set.long_press_role {
2122                node.long_press_role = role;
2123            }
2124            if let Some(action) = handler_set.touch_action {
2125                node.touch_action = action;
2126            }
2127            if let Some(claim) = handler_set.pan_claim {
2128                node.pan_claim = Some(claim);
2129            }
2130            if let Some(behavior) = handler_set.overscroll_behavior {
2131                node.overscroll_behavior = behavior;
2132            }
2133            if let Some(activation) = handler_set.drag_activation {
2134                node.drag_activation = activation;
2135            }
2136            if let Some(policy) = handler_set.multi_contact {
2137                node.multi_contact = policy;
2138            }
2139            if let Some(keyboard_capture) = handler_set.keyboard_capture {
2140                node.keyboard_capture = keyboard_capture;
2141            }
2142            if let Some(hit_transparent) = handler_set.hit_transparent {
2143                node.hit_transparent = hit_transparent;
2144            }
2145            if let Some(slop) = handler_set.hit_slop {
2146                node.hit_slop = Some(slop);
2147            }
2148            if let Some(no_slop) = handler_set.no_hit_slop {
2149                node.no_hit_slop = no_slop;
2150            }
2151            if handler_set.context_menu_factory.is_some() {
2152                node.context_menu_factory = handler_set.context_menu_factory;
2153            }
2154            if let Some(sig) = handler_set.focus_within {
2155                node.focus_within_signal = Some(sig);
2156            }
2157            if let Some(sig) = handler_set.hover_within {
2158                node.hover_within_signal = Some(sig);
2159            }
2160            // Mirror builder-level accessibility overrides + subtree mode
2161            // onto the persistent WidgetNode so the accessibility tree
2162            // walker (and the event dispatcher, for action callbacks) can
2163            // read them after handler extraction.
2164            if handler_set.access.is_some() {
2165                // Merged, not assigned: a node can already carry a
2166                // block from its builder chain, and replacing it
2167                // drops everything in it (see
2168                // `AccessibilityOverrides::merge_from`).
2169                match (&mut node.access_overrides, handler_set.access) {
2170                    (Some(existing), Some(incoming)) => existing.merge_from(*incoming),
2171                    (slot, incoming) => *slot = incoming,
2172                }
2173            }
2174            if let Some(mode) = handler_set.access_subtree {
2175                node.access_subtree = mode;
2176            }
2177        }
2178    }
2179
2180    /// Get a widget's alignment override, if any.
2181    pub fn alignment_override(&self, id: WidgetId) -> Option<teksilo_tokens::Alignment> {
2182        self.get(id)?.alignment_override
2183    }
2184
2185    /// Temporarily take the widget box out of a node (for rebuild).
2186    /// The node remains in the arena with a placeholder.
2187    pub fn take_widget(&mut self, id: WidgetId) -> Option<Box<dyn Widget>> {
2188        let node = self.nodes.get_mut(id)?;
2189        // Replace with a minimal placeholder
2190        let taken = std::mem::replace(&mut node.widget, Box::new(PlaceholderWidget));
2191        Some(taken)
2192    }
2193
2194    /// Restore a widget box that was previously taken out.
2195    pub fn restore_widget(&mut self, id: WidgetId, widget: Box<dyn Widget>) {
2196        if let Some(node) = self.nodes.get_mut(id) {
2197            node.widget = widget;
2198        }
2199    }
2200
2201    /// Walk up the parent chain from `id` and mark each ancestor as needing layout.
2202    /// Called when a relayout-level binding changes, since a child's size change
2203    /// may affect its parent's size, and so on up to the root.
2204    pub fn mark_ancestors_need_layout(&mut self, id: WidgetId) {
2205        let mut current = self.parent(id);
2206        while let Some(pid) = current {
2207            if let Some(node) = self.get_mut(pid) {
2208                node.dirty.needs_layout = true;
2209                node.dirty.needs_paint = true;
2210            }
2211            current = self.parent(pid);
2212        }
2213    }
2214
2215    /// Mark all widgets as needing layout and paint (e.g. after a theme change).
2216    /// Also clears per-widget paint caches since the visual output is stale.
2217    pub fn mark_all_dirty(&mut self) {
2218        for (_, node) in self.nodes.iter_mut() {
2219            node.dirty.needs_layout = true;
2220            node.dirty.needs_paint = true;
2221            node.cached_paint = None;
2222            node.cached_post_paint = None;
2223        }
2224    }
2225
2226    /// Mark every active node for repaint **without** touching layout, rebuild,
2227    /// or the per-widget paint caches. Used for a global visual change that
2228    /// leaves geometry untouched — the window's active-state flip (caret
2229    /// hiding, selection desaturation, `DimWhenInactive`). Lighter than
2230    /// [`Self::mark_all_dirty`]: the paint walker re-runs `paint()` for any
2231    /// node whose `needs_paint` is set and overwrites its cache, so there is no
2232    /// need to clear `cached_paint`; and skipping `needs_layout` avoids a
2233    /// pointless relayout pass. Dormant nodes are skipped — they don't paint,
2234    /// and they're re-marked on reactivation.
2235    pub fn mark_all_needs_paint_only(&mut self) {
2236        for (_, node) in self.nodes.iter_mut() {
2237            if node.activation == ActivationState::Active {
2238                node.dirty.needs_paint = true;
2239            }
2240        }
2241    }
2242
2243    /// Resolve the effective theme for a widget by walking ancestors and
2244    /// applying any theme overrides encountered along the way.
2245    /// The base theme is the tree-level default.
2246    pub fn resolve_theme<'a>(
2247        &self,
2248        id: WidgetId,
2249        base: &'a crate::styles::Theme,
2250    ) -> std::borrow::Cow<'a, crate::styles::Theme> {
2251        // Fast path: if no widget has a theme override, borrow the base
2252        // theme — no clone. This is the per-widget hot path during layout
2253        // and paint, so avoiding `Theme::clone()` (which clones the
2254        // typography token strings and bumps ~42 style-slot `Rc`s) here
2255        // saves that work on every node, every pass, in the common case.
2256        if self.theme_override_count == 0 {
2257            return std::borrow::Cow::Borrowed(base);
2258        }
2259
2260        // Collect ancestor chain from root to widget
2261        let mut chain = vec![id];
2262        let mut current = self.parent(id);
2263        while let Some(pid) = current {
2264            chain.push(pid);
2265            current = self.parent(pid);
2266        }
2267        chain.reverse(); // root first
2268
2269        let mut theme = base.clone();
2270        for nid in chain {
2271            if let Some(node) = self.nodes.get(nid)
2272                && let Some(ovr) = &node.theme_override
2273            {
2274                (ovr.func)(&mut theme);
2275            }
2276        }
2277        std::borrow::Cow::Owned(theme)
2278    }
2279}
2280
2281impl Default for WidgetArena {
2282    fn default() -> Self {
2283        Self::new()
2284    }
2285}
2286
2287#[cfg(test)]
2288mod tests {
2289    use super::*;
2290    use crate::test_widgets::FillWidget;
2291    use teksilo_canvas::SizeProposal;
2292
2293    fn key(w: Option<f32>, h: Option<f32>) -> ProposalKey {
2294        ProposalKey::from_proposal(SizeProposal {
2295            width: w,
2296            height: h,
2297        })
2298    }
2299
2300    #[test]
2301    fn activate_skips_a_child_gated_off_by_visible_state() {
2302        // Reactivating a subtree must not wake a child that its own widget
2303        // has gated off via `visible_when(false)` — e.g. a ComboBox's closed
2304        // dropdown panel, or a collapsed overlay. Regression for ghost
2305        // dropdown rows after a `visible_when` collapse→reappear cycle.
2306        let mut arena = WidgetArena::new();
2307        let parent = arena.insert(Box::new(FillWidget::new()));
2308        let visible_child = arena.insert_child(parent, Box::new(FillWidget::new()));
2309        let gated_child = arena.insert_child(parent, Box::new(FillWidget::new()));
2310        // The gated child is hidden by its own visibility gate.
2311        if let Some(node) = arena.get_mut(gated_child) {
2312            node.visible_state = Some(Prop::Static(false));
2313        }
2314
2315        arena.set_dormant(parent);
2316        assert!(!arena.is_active(gated_child));
2317
2318        arena.activate(parent);
2319        assert!(arena.is_active(parent), "the targeted node activates");
2320        assert!(
2321            arena.is_active(visible_child),
2322            "an ungated child activates with its parent"
2323        );
2324        assert!(
2325            !arena.is_active(gated_child),
2326            "a visible_when(false) child stays dormant when its parent reactivates"
2327        );
2328    }
2329
2330    #[test]
2331    fn activate_skips_a_child_parked_directly_by_set_dormant() {
2332        // The ungated twin of the test above, and the one that was missing.
2333        //
2334        // Widgets that pre-build hidden content register it as a child with
2335        // `ctx.add(..)` + `ctx.set_dormant(..)` and show it through an overlay:
2336        // `SplitButton` and `MenuBar` menus, `Popover`, `Snackbar`, the date
2337        // editors' calendars. Such a child carries no `visible_state`, so the
2338        // gate check alone let an ancestor's dormancy cycle wake it — and it
2339        // then rendered inline, with no overlay behind it, because the overlay
2340        // presentation never ran. Seen as export menu-item labels floating
2341        // under the title bar after leaving a mode that parked the shell.
2342        let mut arena = WidgetArena::new();
2343        let parent = arena.insert(Box::new(FillWidget::new()));
2344        let visible_child = arena.insert_child(parent, Box::new(FillWidget::new()));
2345        let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
2346        let menu_row = arena.insert_child(menu, Box::new(FillWidget::new()));
2347
2348        // The widget parks its own closed menu — no gate involved.
2349        arena.set_dormant(menu);
2350        assert!(!arena.is_active(menu));
2351
2352        // An ancestor now goes dormant and comes back.
2353        arena.set_dormant(parent);
2354        arena.activate(parent);
2355
2356        assert!(arena.is_active(parent), "the targeted node activates");
2357        assert!(
2358            arena.is_active(visible_child),
2359            "an ordinary child activates with its parent"
2360        );
2361        assert!(
2362            !arena.is_active(menu),
2363            "the ancestor's dormancy cycle woke a menu that was closed before it \
2364             started — its content is now on screen with no overlay behind it"
2365        );
2366        assert!(
2367            !arena.is_active(menu_row),
2368            "the closed menu's own subtree woke with it"
2369        );
2370
2371        // …and opening it still works: activating by id is how the overlay
2372        // shows this content, so it must clear the self-parked mark.
2373        arena.activate(menu);
2374        assert!(arena.is_active(menu), "the menu can still be opened");
2375        assert!(arena.is_active(menu_row), "…along with its rows");
2376    }
2377
2378    #[test]
2379    fn a_reopened_menu_parks_again_and_survives_the_next_cycle() {
2380        // The flag must be re-armed by every `set_dormant`, not just the first:
2381        // open the menu, close it, then put an ancestor through another
2382        // dormancy cycle. Without re-arming, the second cycle leaks.
2383        let mut arena = WidgetArena::new();
2384        let parent = arena.insert(Box::new(FillWidget::new()));
2385        let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
2386
2387        arena.set_dormant(menu);
2388        arena.activate(menu); // opened
2389        arena.set_dormant(menu); // dismissed
2390
2391        arena.set_dormant(parent);
2392        arena.activate(parent);
2393        assert!(
2394            !arena.is_active(menu),
2395            "a menu that was opened once no longer stays closed across a \
2396             dormancy cycle"
2397        );
2398    }
2399
2400    #[test]
2401    fn an_ancestor_cycle_does_not_strand_an_open_menu() {
2402        // The mirror risk of the fix: `park` marks only the node it is given,
2403        // so a menu that is *open* when an ancestor parks must come back with
2404        // that ancestor rather than being stranded closed.
2405        let mut arena = WidgetArena::new();
2406        let parent = arena.insert(Box::new(FillWidget::new()));
2407        let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
2408
2409        arena.set_dormant(menu);
2410        arena.activate(menu); // open when the ancestor parks
2411
2412        arena.set_dormant(parent);
2413        arena.activate(parent);
2414        assert!(
2415            arena.is_active(menu),
2416            "an open menu was stranded closed by its ancestor's dormancy cycle"
2417        );
2418    }
2419
2420    #[test]
2421    fn proposal_key_distinguishes_none_from_zero() {
2422        // `None` (ask for ideal) must not collide with `Some(0.0)` (give zero).
2423        assert_ne!(key(None, None), key(Some(0.0), None));
2424        assert_ne!(key(Some(0.0), None), key(None, Some(0.0)));
2425    }
2426
2427    #[test]
2428    fn proposal_key_canonicalizes_signed_zero_and_nan() {
2429        assert_eq!(key(Some(-0.0), None), key(Some(0.0), None));
2430        assert_eq!(key(Some(f32::NAN), None), key(Some(f32::NAN), None));
2431    }
2432
2433    #[test]
2434    fn proposal_key_separates_distinct_values_and_axes() {
2435        assert_ne!(key(Some(1.0), None), key(Some(2.0), None));
2436        // Same scalar on different axes must not collide.
2437        assert_ne!(key(Some(10.0), None), key(None, Some(10.0)));
2438    }
2439
2440    #[test]
2441    fn insert_and_retrieve() {
2442        let mut arena = WidgetArena::new();
2443        let id = arena.insert(Box::new(FillWidget::new()));
2444        assert!(arena.get(id).is_some());
2445        assert_eq!(arena.len(), 1);
2446    }
2447
2448    #[test]
2449    fn new_widget_is_dirty() {
2450        let mut arena = WidgetArena::new();
2451        let id = arena.insert(Box::new(FillWidget::new()));
2452        let node = arena.get(id).unwrap();
2453        assert!(node.dirty.needs_layout);
2454        assert!(node.dirty.needs_paint);
2455    }
2456
2457    #[test]
2458    fn roots_returns_parentless_widgets() {
2459        let mut arena = WidgetArena::new();
2460        let root = arena.insert(Box::new(FillWidget::new()));
2461        let _child = arena.insert_child(root, Box::new(FillWidget::new()));
2462        let roots = arena.roots();
2463        assert_eq!(roots.len(), 1);
2464        assert_eq!(roots[0], root);
2465    }
2466
2467    #[test]
2468    fn content_transform_node_claims_viewport_in_parent_space() {
2469        // A content-transform node (the SceneView pattern) is a fixed
2470        // viewport: its bounds are tested in PARENT space and the transform
2471        // only positions its content, so the whole visible viewport stays
2472        // hittable regardless of the content pan/zoom. Before the fix, the
2473        // bounds were tested in content space, so a content pan shifted the
2474        // hittable region off the viewport.
2475        use teksilo_canvas::{Point, Rect, Transform2D};
2476        let mut arena = WidgetArena::new();
2477        let id = arena.insert(Box::new(FillWidget::new()));
2478        {
2479            let node = arena.get_mut(id).unwrap();
2480            node.bounds = Rect::new(0.0, 0.0, 200.0, 100.0);
2481            node.clips_children = true;
2482            node.content_transform = true;
2483            // Content panned by (50, 30).
2484            node.transform_prop = Some(Prop::Static(Transform2D::translate(50.0, 30.0)));
2485        }
2486        // Points across the whole parent-space viewport hit, regardless of the
2487        // pan (these all missed before the fix).
2488        assert_eq!(arena.hit_test_at(Point::new(10.0, 10.0), None), Some(id));
2489        assert_eq!(arena.hit_test_at(Point::new(100.0, 50.0), None), Some(id));
2490        assert_eq!(arena.hit_test_at(Point::new(199.0, 99.0), None), Some(id));
2491        // Outside the viewport: miss.
2492        assert_eq!(arena.hit_test_at(Point::new(250.0, 50.0), None), None);
2493    }
2494
2495    #[test]
2496    fn self_transform_node_tests_bounds_in_local_space() {
2497        // Regression guard: a *self* transform wrapper (Scale / Rotate, NOT a
2498        // content transform) keeps the original semantics — its own bounds
2499        // move with the transform, so the point is inverse-transformed before
2500        // the bounds test. `clips_children` is irrelevant here (Scale clips
2501        // too); only `content_transform` selects the viewport path.
2502        use teksilo_canvas::{Point, Rect, Transform2D};
2503        let mut arena = WidgetArena::new();
2504        let id = arena.insert(Box::new(FillWidget::new()));
2505        {
2506            let node = arena.get_mut(id).unwrap();
2507            node.bounds = Rect::new(0.0, 0.0, 100.0, 100.0);
2508            node.clips_children = true; // Scale clips, but is NOT content_transform.
2509            node.content_transform = false;
2510            // Visually scaled to 50x50 around the origin.
2511            node.transform_prop = Some(Prop::Static(Transform2D::scale(0.5, 0.5)));
2512        }
2513        // Inside the scaled-down 50x50 visual → hit.
2514        assert_eq!(arena.hit_test_at(Point::new(25.0, 25.0), None), Some(id));
2515        // Past the scaled-down visual (but inside the un-scaled 100x100 bounds
2516        // in parent space) → miss, because the bounds test is in local space.
2517        assert_eq!(arena.hit_test_at(Point::new(75.0, 75.0), None), None);
2518    }
2519
2520    #[test]
2521    fn nested_content_transform_nodes_each_claim_their_viewport() {
2522        // A content-transform node embedded inside another (the nested-
2523        // SceneView case): each level tests its own viewport bounds in its
2524        // parent's space, and only the transform is applied when descending.
2525        // The inner viewport stays hittable regardless of either node's pan.
2526        use teksilo_canvas::{Point, Rect, Transform2D};
2527        let mut arena = WidgetArena::new();
2528        let outer = arena.insert(Box::new(FillWidget::new()));
2529        let inner = arena.insert_child(outer, Box::new(FillWidget::new()));
2530        {
2531            let n = arena.get_mut(outer).unwrap();
2532            n.bounds = Rect::new(0.0, 0.0, 200.0, 200.0);
2533            n.clips_children = true;
2534            n.content_transform = true;
2535            n.transform_prop = Some(Prop::Static(Transform2D::translate(20.0, 20.0)));
2536        }
2537        {
2538            let n = arena.get_mut(inner).unwrap();
2539            // Inner viewport expressed in the OUTER's content space.
2540            n.bounds = Rect::new(10.0, 10.0, 50.0, 50.0);
2541            n.clips_children = true;
2542            n.content_transform = true;
2543            n.transform_prop = Some(Prop::Static(Transform2D::translate(5.0, 5.0)));
2544        }
2545        // Screen (40,40) → outer-content (20,20) ∈ inner viewport → reaches inner.
2546        assert_eq!(arena.hit_test_at(Point::new(40.0, 40.0), None), Some(inner));
2547        // Screen (5,5) → outer-content (-15,-15) ∉ inner viewport → reaches outer.
2548        assert_eq!(arena.hit_test_at(Point::new(5.0, 5.0), None), Some(outer));
2549    }
2550
2551    /// Accepts only the right half of its bounds via `hit_shape`; the left
2552    /// half is rejected so a click there falls through to a sibling beneath.
2553    #[derive(Debug)]
2554    struct RightHalfWidget;
2555
2556    impl crate::widget::Widget for RightHalfWidget {
2557        fn layout_response(
2558            &self,
2559            proposal: teksilo_canvas::SizeProposal,
2560            _ctx: &crate::widget::LayoutContext,
2561        ) -> crate::widget::LayoutResponse {
2562            proposal.resolve(0.0, 0.0).into()
2563        }
2564
2565        fn hit_shape(
2566            &self,
2567            local_point: teksilo_canvas::Point,
2568            bounds: teksilo_canvas::Rect,
2569        ) -> bool {
2570            local_point.x >= bounds.x + bounds.width / 2.0
2571        }
2572    }
2573
2574    #[test]
2575    fn hit_shape_rejection_falls_through_to_sibling_underneath() {
2576        // Two overlapping siblings under a common parent. `lower` is a
2577        // full-rect FillWidget; `upper` (inserted later → painted on top,
2578        // hit-tested first) rejects its left half via `hit_shape`. A click in
2579        // the rejected left half must reach `lower` underneath; a click in the
2580        // accepted right half must hit `upper`.
2581        use teksilo_canvas::{Point, Rect};
2582        let mut arena = WidgetArena::new();
2583        let parent = arena.insert(Box::new(FillWidget::new()));
2584        let lower = arena.insert_child(parent, Box::new(FillWidget::new()));
2585        let upper = arena.insert_child(parent, Box::new(RightHalfWidget));
2586        for id in [parent, lower, upper] {
2587            arena.get_mut(id).unwrap().bounds = Rect::new(0.0, 0.0, 100.0, 100.0);
2588        }
2589        // Right half: upper accepts → hit upper.
2590        assert_eq!(arena.hit_test_at(Point::new(75.0, 50.0), None), Some(upper));
2591        // Left half: upper rejects via hit_shape → falls through to lower.
2592        assert_eq!(arena.hit_test_at(Point::new(25.0, 50.0), None), Some(lower));
2593    }
2594}