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::signal::{ObserverHandle, Prop, Signal};
10use crate::widget::{CursorIcon, Widget};
11use crate::widget_id::WidgetId;
12use teksilo_canvas::RenderFrame;
13
14/// Minimal placeholder widget used during composite rebuild and ID reservation.
15#[derive(Debug)]
16pub(crate) struct PlaceholderWidget;
17
18impl Widget for PlaceholderWidget {
19 fn layout_response(
20 &self,
21 _proposal: teksilo_canvas::SizeProposal,
22 _ctx: &crate::widget::LayoutContext,
23 ) -> crate::widget::LayoutResponse {
24 teksilo_canvas::Size::ZERO.into()
25 }
26}
27
28/// Activation state for a widget in the arena.
29#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum ActivationState {
31 Active,
32 Dormant,
33 Destroyed,
34}
35
36/// Where a `HandlerSet` should land on the node: handlers the widget
37/// attaches to itself (cleared on rebuild) vs handlers attached from
38/// outside (persist across rebuilds).
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub(crate) enum HandlerScope {
41 /// Handlers registered during the widget's own `build()` via
42 /// `BuildContext::apply_self_handlers`.
43 Own,
44 /// Handlers attached externally — at insertion time via
45 /// `WidgetBuilder::on_tap` et al., or by a composing parent's
46 /// `BuildContext::apply_handlers(child_id, ...)`.
47 External,
48}
49
50/// Dirty flags for a widget.
51#[derive(Debug, Clone, Copy, Default)]
52pub struct DirtyFlags {
53 pub needs_layout: bool,
54 pub needs_paint: bool,
55 /// When true, the widget's `build()` should be re-run to regenerate children.
56 /// Set by `BindingLevel::Rebuild` bindings (data-driven widgets).
57 pub needs_rebuild: bool,
58}
59
60/// A node in the widget arena storing a widget and its metadata.
61pub struct WidgetNode {
62 pub widget: Box<dyn Widget>,
63 pub parent: Option<WidgetId>,
64 pub children: Vec<WidgetId>,
65 pub activation: ActivationState,
66 /// Whether this node is dormant **on its own account** — parked by a
67 /// direct [`WidgetArena::set_dormant`] rather than swept along by an
68 /// ancestor going dormant.
69 ///
70 /// This is the ungated twin of `visible_state`, and [`WidgetArena::activate`]
71 /// honours the two identically: a self-parked child is left asleep when an
72 /// ancestor wakes, because the ancestor's dormancy was never why it was
73 /// asleep. Cleared the moment a caller activates this node *by id*, which is
74 /// exactly how pre-registered overlay content is shown.
75 ///
76 /// Without it, every widget that pre-builds hidden content as a child with
77 /// `ctx.add(..)` + `ctx.set_dormant(..)` — `SplitButton`'s dropdown,
78 /// `MenuBar`'s menus, `Popover`, `Snackbar`, the date editors' calendars —
79 /// spilled that content onto the screen as soon as any ancestor completed a
80 /// dormancy cycle, laid out inline with no overlay behind it.
81 pub(crate) self_dormant: bool,
82 pub dirty: DirtyFlags,
83 pub bounds: teksilo_canvas::Rect,
84 pub(crate) theme_override: Option<ThemeOverride>,
85 pub(crate) visible_state: Option<Prop<bool>>,
86 pub(crate) enabled_state: Option<Prop<bool>>,
87 /// Reactive Tab-key participation. When bound and evaluates to
88 /// `false`, the widget is excluded from Tab / Shift+Tab traversal
89 /// (`cycle_focus`) — but remains reachable via `request_focus`
90 /// and arrow-key navigation that calls `request_focus`. This
91 /// implements the ARIA roving-tabindex pattern (HTML
92 /// `tabindex="-1"` semantics). `None` means "always a Tab stop
93 /// when focusable" — the default. The selected `TabHeader` is the
94 /// canonical user.
95 pub(crate) tab_stop: Option<Prop<bool>>,
96 /// What a data view's `Space` should do when the row containing this node
97 /// holds the keyboard cursor.
98 ///
99 /// A `ListView` / `TreeView` row is deliberately not focusable — the
100 /// container is — and the view takes the row subtree out of the Tab order,
101 /// because a listbox is one Tab stop and a per-row stop would make the Tab
102 /// order track the virtualization window. That leaves a checkbox inside a
103 /// row with no keyboard route, so the row publishes one here and the view
104 /// calls it. Carrying the *action* rather than the target's id keeps the
105 /// views from having to know what kind of control it is.
106 ///
107 /// `StandardListItem` / `StandardTreeItem` set it on the checkbox they
108 /// embed, so the common path needs no wiring; a hand-written delegate
109 /// calls `BuildContext::set_keyboard_toggle`.
110 #[allow(clippy::type_complexity)]
111 pub(crate) keyboard_toggle: Option<std::rc::Rc<dyn Fn()>>,
112 /// User-bound signal that the framework sets to `true` whenever
113 /// the focused widget is a strict descendant of this node, and
114 /// `false` otherwise. Used by `Panel` / `Card` / composite
115 /// widgets that want a unified focus halo without per-child
116 /// `on_focus` plumbing. See `WidgetBuilder::focus_within`.
117 pub(crate) focus_within_signal: Option<Signal<bool>>,
118 /// Framework-managed signal, lazily attached to a focusable node, set to
119 /// `true` whenever the focus is this node **or** a descendant (i.e. the node
120 /// is an *inclusive* ancestor of the focused widget). Unlike
121 /// `focus_within_signal` (strict descendants), this includes the node being
122 /// focused itself — so a data view that holds focus directly reads `true`.
123 /// Powers focus-aware selection (`BuildContext::view_focus_active`).
124 pub(crate) view_focus_signal: Option<Signal<bool>>,
125 /// User-bound signal that the framework sets to `true` whenever
126 /// the hovered widget is a strict descendant of this node.
127 /// Symmetric to `focus_within_signal`. See
128 /// `WidgetBuilder::hover_within`.
129 pub(crate) hover_within_signal: Option<Signal<bool>>,
130 /// User-bound signal that the framework sets to `true` while this
131 /// node is `ActivationState::Active` and `false` while it is
132 /// `Dormant`. Opted into via `BuildContext::activation_signal`.
133 /// Unlike every other widget — which is hidden automatically when
134 /// the paint pass skips a dormant subtree — a widget that owns a
135 /// resource living *outside* the wgpu pass (a native OS subview: a
136 /// `WebView` engine surface) has no other way to learn it was parked
137 /// dormant by a `Switcher` / `visible_when` gate, so it cannot hide
138 /// that resource. This signal is that notification. Set only on an
139 /// actual Active↔Dormant transition. See `set_dormant` / `activate`.
140 pub(crate) activation_signal: Option<Signal<bool>>,
141 /// Framework-written mirror of [`WidgetArena::is_enabled`] for this node —
142 /// the AND of its own `enabled_state` and every ancestor's. Opted into via
143 /// `BuildContext::effective_enabled_signal`.
144 ///
145 /// This has to be a *node-resident* signal that the framework refreshes,
146 /// rather than a signal derived by walking ancestors at call time, because
147 /// a widget's `parent` is still `None` while its own `build()` runs — the
148 /// parent link is wired only after `build()` returns (see
149 /// `WidgetTree::insert_widget`). A signal derived during `build()` would
150 /// therefore capture an empty ancestor chain and report only the widget's
151 /// own `enabled` prop, forever. Refreshed in
152 /// `WidgetTree::flush_effective_enabled_signals`.
153 pub(crate) effective_enabled_signal: Option<Signal<bool>>,
154 pub(crate) alignment_override: Option<teksilo_tokens::Alignment>,
155 /// When true, the paint pass clips child rendering to this widget's bounds.
156 /// Set by scroll areas and overflow-hidden containers.
157 pub clips_children: bool,
158 /// Optional OS input-method (IME) descriptor. `Some(..)` declares this
159 /// node a text-input surface — the platform enables the OS IME (with the
160 /// descriptor's purpose) while the node is focused. `None` (the default)
161 /// means no OS IME: enabling IME changes how text arrives, so the safe
162 /// common-case default is off. The platform reads the focused node's
163 /// descriptor at focus-change time. See [`crate::ime`].
164 pub ime: Option<crate::ime::ImeContext>,
165 /// When true, hit-testing skips this node — pointer events fall
166 /// through to whatever sits behind it. Descendants are still
167 /// hit-tested normally (the recursion walks into children before
168 /// the pass-through check), so an interactive subtree under a
169 /// pass-through wrapper stays usable. Used by the debug inspector's
170 /// `HighlightLayer` and `HoverProbe` to paint over the user's
171 /// content without absorbing clicks. Default `false`.
172 pub event_pass_through: bool,
173 /// When `true`, a pointer press anywhere in this widget's subtree must
174 /// NOT arm a drag/swipe recognizer on any ancestor **above** this node —
175 /// the subtree is a *gesture dead zone* for ancestor gestures. Used so
176 /// interactive controls (buttons, a `⋮` menu) placed inside a draggable /
177 /// swipeable container (a dock-panel header, a card, a list row) can be
178 /// clicked without a few px of pointer jitter starting the ancestor's drag.
179 /// The boundary is honored by `arm_drag_observers`. Mirrors Electron's
180 /// `-webkit-app-region: no-drag`. Default `false`. See the `DeadZone`
181 /// wrapper widget.
182 pub gesture_dead_zone: bool,
183 /// When `true` and this widget holds keyboard focus, a `KeyDown` is
184 /// delivered straight to it **without** first running shortcut →
185 /// intent → action resolution. The node is a *keyboard capture*
186 /// surface: it wants every keystroke (including chords the host app
187 /// binds as `Shortcut`s — `Ctrl+C`, `Ctrl+W`, `Alt+<letter>`, …).
188 /// Used by a terminal emulator (which must forward `Ctrl+C` to the
189 /// child process, not trigger the app's copy shortcut), a game
190 /// viewport, or a vim-mode editor. Honored by `dispatch_event_impl`,
191 /// which skips the shortcut block for a focused capture node.
192 ///
193 /// **`Ctrl+Tab` / `Ctrl+Shift+Tab` are reserved**: `dispatch_event_impl`
194 /// cycles focus on that chord before dispatching to a focused capture
195 /// node, so no capture surface can trap the keyboard (WCAG 2.1.2).
196 /// Escape is not reserved — overlay back-navigation runs ahead of the
197 /// check only while an overlay is open, so a capture surface below no
198 /// overlay does see Escape. Default `false`.
199 pub keyboard_capture: bool,
200 /// When `true`, this widget AND its entire subtree are invisible to
201 /// hit-testing: the recursion returns immediately without descending
202 /// into children, so the point falls through to whatever sits
203 /// behind. Unlike [`event_pass_through`](Self::event_pass_through)
204 /// (which is per-node — descendants stay hittable), this excludes
205 /// the whole subtree. Use for purely decorative overlays whose
206 /// children are themselves widgets — a count badge over a button, a
207 /// watermark, a status dot — so they never steal clicks meant for
208 /// the control underneath. Default `false`.
209 pub hit_transparent: bool,
210 /// Optional opacity multiplier (0..1) applied to this widget's
211 /// entire subtree during paint. The render walker emits
212 /// `SetOpacity(value)` before walking the widget's own paint and
213 /// children, then `RestoreOpacity` afterwards — so the multiplier
214 /// composes with ancestor opacity scopes via the canvas's
215 /// already-stacked opacity model. Bound at `Repaint` level: opacity
216 /// changes never trigger relayout. `None` means "no opacity scope"
217 /// (the default for almost every widget). The `Fade` widget sets
218 /// this on its own node to drive an animated visibility tween.
219 pub(crate) opacity_prop: Option<Prop<f32>>,
220 /// Optional 2D affine transform applied to this widget's entire
221 /// subtree during paint. The render walker emits
222 /// `PushTransform(value)` before walking the widget's own paint
223 /// and children, then `PopTransform` afterwards — the renderer
224 /// composes it onto its transform stack so nested wrappers and
225 /// widget-internal canvas transforms compose correctly. Bound at
226 /// `Repaint` level by default (visual-only); a wrapper that wants
227 /// the transform to drive layout (e.g. `Scale::reflow(true)`)
228 /// must additionally bind its driver signal at `Relayout`.
229 /// `None` means "no transform scope" (the default for almost every
230 /// widget). The `Scale` and `Rotate` widgets set this on their own
231 /// node.
232 pub(crate) transform_prop: Option<Prop<teksilo_canvas::Transform2D>>,
233 /// Whether [`transform_prop`](Self::transform_prop) transforms this node's
234 /// **content** within a fixed parent-space viewport (`true`), versus
235 /// transforming the **node itself** (`false`, the default).
236 ///
237 /// `Scale` / `Rotate` are *self* transforms: the node's own bounds move
238 /// with the transform, so hit-testing inverse-applies the transform before
239 /// the bounds test (a click lands where the scaled/rotated visual is).
240 ///
241 /// `SceneView` is a *content* transform: its bounds are a fixed screen
242 /// viewport and the pan/zoom only moves its content, so hit-testing must
243 /// test the bounds in parent space (keeping the whole visible viewport
244 /// interactive at any pan) and apply the transform only when descending
245 /// into children. Set via `BuildContext::set_content_transform`.
246 pub(crate) content_transform: bool,
247 /// Optional Gaussian-equivalent blur radius applied to this widget's
248 /// entire subtree during paint. The render walker emits
249 /// `BeginBlurredSubtree { bounds, radius }` before walking the
250 /// widget's own paint and children, then `EndBlurredSubtree`
251 /// afterwards — the renderer redirects drawing into an intermediate
252 /// texture, runs a dual-Kawase blur chain at the requested radius,
253 /// and composites the blurred result back into the parent pass.
254 /// Bound at `Repaint` level: blur radius changes never trigger
255 /// relayout. `None` (or `Some(radius < 0.5)`) means "no blur scope"
256 /// — the walker skips the Begin/End pair entirely so disabled blur
257 /// has zero per-frame cost. The `Blur` widget sets this on its own
258 /// node.
259 pub(crate) blur_prop: Option<Prop<f32>>,
260 /// Cached paint output for this widget (excludes children).
261 /// Reused when `needs_paint` is false to avoid re-running `paint()`.
262 pub(crate) cached_paint: Option<RenderFrame>,
263 /// Cached foreground output for widgets that override
264 /// [`Widget::post_paint`] — the
265 /// draws emitted *after* this widget's children. Separate frame from
266 /// `cached_paint` because it lands at a different position in
267 /// `draw_order` (after the child subtree). Reused on the same
268 /// `needs_paint` gate.
269 pub(crate) cached_post_paint: Option<RenderFrame>,
270 /// The ambient raster scale `cached_paint` / `cached_post_paint`
271 /// were baked at (the paint walker's accumulated transform scale,
272 /// quantized). Glyph quads in those frames reference bitmaps of
273 /// that density; when the walker's current scale differs (a scene
274 /// zoom crossed a quantization bucket), the cached frames are
275 /// treated as `needs_paint` even though the widget itself is clean.
276 pub(crate) paint_raster_scale: f32,
277 /// The `WidgetTree::paint_epoch` at which this widget's bounds were
278 /// last observed inside the window viewport by the paint pass.
279 /// The animation scheduler uses this to pause looping animations
280 /// for offscreen widgets: an animation whose
281 /// `last_painted_epoch + 1 < tree.paint_epoch` is considered
282 /// off-screen and skipped. `0` means "not yet painted" — treated
283 /// as "always visible" to keep headless tests (no `render()` call)
284 /// from regressing.
285 pub last_painted_epoch: u64,
286
287 // --- V2 fields ---
288 /// Event handlers the widget attached to itself during its own
289 /// `build()` via `BuildContext::apply_self_handlers`. Cleared on
290 /// rebuild so accumulating `apply_self_handlers` calls across
291 /// rebuilds don't stack N-fold handler chains.
292 pub(crate) handlers: EventHandlers,
293 /// Event handlers attached *externally* — either via the
294 /// `WidgetBuilder` chain at the widget's creation site
295 /// (`SomeWidget::new().on_tap(...)`) or by a parent's
296 /// `BuildContext::apply_handlers(child_id, ...)`. These survive
297 /// rebuilds: the widget didn't register them and shouldn't decide
298 /// when they go away.
299 pub(crate) external_handlers: EventHandlers,
300 /// Focusable override set via HandlerSet. Takes precedence over widget.is_focusable().
301 pub(crate) node_focusable: Option<bool>,
302 /// Tab index override set via HandlerSet.
303 pub(crate) node_tab_index: Option<i32>,
304 /// Traversal-scope marker. When `Some(policy)`, `cycle_focus` treats this
305 /// node's subtree as an independent Tab group: `tab_index` numbering is
306 /// scoped to its descendants (so sibling scopes never interleave) and
307 /// `policy` governs what Tab does at the scope's ends. `None` (default)
308 /// means the node is transparent to traversal scoping. Set by the
309 /// `FocusScope` wrapper via `BuildContext::set_traversal_scope`. A node
310 /// carrying this marker is forced non-focusable (it is a boundary, never a
311 /// Tab stop). See [`crate::focus::TraversalScopePolicy`].
312 pub(crate) node_traversal_scope: Option<crate::focus::TraversalScopePolicy>,
313 /// Cursor override set via HandlerSet.
314 pub(crate) node_cursor: Option<CursorIcon>,
315 /// RAII observer handles for effects registered during build().
316 /// Dropped on rebuild or widget destruction.
317 pub(crate) effect_handles: Vec<ObserverHandle>,
318 /// Backend-event subscriptions registered during build() via
319 /// `BuildContext::subscribe_event`. Each entry pairs a subscription id
320 /// (used to remove the UI-side callback from `TreeAppContext`) with the
321 /// opaque source-side handle whose `Drop` removes the subscriber from
322 /// the source's internal registry.
323 pub(crate) subscription_handles: Vec<(SubscriptionId, SubscriptionHandle)>,
324 /// Parentless nodes this widget created during `build()` and still owns —
325 /// pre-built overlay content (a menu, a calendar, a tooltip's nested
326 /// cascade children) that is deliberately *not* a child.
327 ///
328 /// Such content cannot be a child: activation and the paint walk both
329 /// descend through `children`, so a dormant popup parked there wakes with
330 /// its host and paints inline at zero size. Keeping it parentless fixes
331 /// that and creates the opposite problem — no teardown walk reaches it, so
332 /// every rebuild of the host strands another copy in the arena for the
333 /// lifetime of the process. This list is the missing ownership edge:
334 /// [`WidgetTree::destroy_subtree`](crate::widget_tree::WidgetTree) reaps it
335 /// with the owner, and a rebuild reaps the previous generation. Recorded
336 /// via `BuildContext::add_detached`.
337 pub(crate) detached: Vec<WidgetId>,
338 /// Context menu factory — invoked on right-click to produce overlay content.
339 pub(crate) context_menu_factory: Option<crate::widget_builder::ContextMenuFactory>,
340 /// Intent-bound actions attached by this widget during `build()`.
341 /// Consulted during intent dispatch (source-widget → root walk).
342 /// Cleared on rebuild in the same pass that clears handlers.
343 pub(crate) actions: Vec<crate::action::Action>,
344 /// Builder-level accessibility overrides (`access_label`,
345 /// `access_role`, etc.). Mirrored from the wrapper's `HandlerSet`
346 /// at insertion via `apply_handler_set`. Applied by the
347 /// accessibility tree walker after the inner widget's
348 /// `accessibility(&self, builder)` runs. Action callbacks
349 /// (`actions`, `custom_actions` inside this struct) are dispatched
350 /// by `event_dispatch_impl.rs` when handling
351 /// `WidgetEvent::AccessAction`.
352 pub(crate) access_overrides: Option<Box<crate::widget_builder::AccessibilityOverrides>>,
353 /// Subtree visibility / merge mode (`access_exclude_subtree` /
354 /// `access_merge_subtree`). Mirrored from the wrapper's
355 /// `HandlerSet`.
356 pub(crate) access_subtree: crate::widget_builder::AccessSubtreeMode,
357}
358
359impl std::fmt::Debug for WidgetNode {
360 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
361 f.debug_struct("WidgetNode")
362 .field("widget", &self.widget)
363 .field("parent", &self.parent)
364 .field("children", &self.children)
365 .field("activation", &self.activation)
366 .field("dirty", &self.dirty)
367 .field("bounds", &self.bounds)
368 .field("has_gesture_arena", &self.handlers.gesture_arena.is_some())
369 .field("has_theme_override", &self.theme_override.is_some())
370 .field("has_visible_state", &self.visible_state.is_some())
371 .field("has_enabled_state", &self.enabled_state.is_some())
372 .finish()
373 }
374}
375
376impl WidgetNode {
377 /// Construct a fresh node wrapping `widget`, parented at `parent`
378 /// (`None` for a root). All other fields take their insertion defaults;
379 /// the caller wires up `children` / parent back-links afterward.
380 pub(crate) fn new(widget: Box<dyn Widget>, parent: Option<WidgetId>) -> Self {
381 WidgetNode {
382 widget,
383 parent,
384 children: Vec::new(),
385 activation: ActivationState::Active,
386 self_dormant: false,
387 dirty: DirtyFlags {
388 needs_layout: true,
389 needs_paint: true,
390 needs_rebuild: false,
391 },
392 bounds: teksilo_canvas::Rect::ZERO,
393 theme_override: None,
394 visible_state: None,
395 enabled_state: None,
396 tab_stop: None,
397 keyboard_toggle: None,
398 focus_within_signal: None,
399 view_focus_signal: None,
400 hover_within_signal: None,
401 activation_signal: None,
402 effective_enabled_signal: None,
403 alignment_override: None,
404 clips_children: false,
405 ime: None,
406 event_pass_through: false,
407 gesture_dead_zone: false,
408 keyboard_capture: false,
409 hit_transparent: false,
410 opacity_prop: None,
411 transform_prop: None,
412 content_transform: false,
413 blur_prop: None,
414 cached_paint: None,
415 cached_post_paint: None,
416 paint_raster_scale: 1.0,
417 last_painted_epoch: 0,
418 handlers: EventHandlers::new(),
419 external_handlers: EventHandlers::new(),
420 node_focusable: None,
421 node_tab_index: None,
422 node_traversal_scope: None,
423 node_cursor: None,
424 effect_handles: Vec::new(),
425 subscription_handles: Vec::new(),
426 detached: Vec::new(),
427 context_menu_factory: None,
428 actions: Vec::new(),
429 access_overrides: None,
430 access_subtree: crate::widget_builder::AccessSubtreeMode::default(),
431 }
432 }
433
434 /// Does EITHER handler slot (own or external) have a handler of the
435 /// requested kind? Use this when deciding whether to build a gesture
436 /// arena, mark the node as a drop target, etc.
437 pub(crate) fn any_handler<F>(&self, f: F) -> bool
438 where
439 F: Fn(&EventHandlers) -> bool,
440 {
441 f(&self.handlers) || f(&self.external_handlers)
442 }
443}
444
445/// Flat arena storage for all widgets, using SlotMap for O(1) access.
446pub struct WidgetArena {
447 nodes: SlotMap<WidgetId, WidgetNode>,
448 /// Number of nodes with theme overrides. When zero, resolve_theme is O(1).
449 pub(crate) theme_override_count: usize,
450 /// Cached root widget IDs (widgets with no parent).
451 cached_roots: Vec<WidgetId>,
452 /// Whether the cached_roots list needs rebuilding.
453 roots_dirty: bool,
454 /// Per-pass memoization of `Widget::layout_response`, keyed by
455 /// `(WidgetId, ProposalKey)`. Cleared once at the start of every layout
456 /// pass (see `clear_layout_cache`). Height-for-width negotiation queries
457 /// each child along the main axis and again along the cross axis, so
458 /// without this the cost compounds super-linearly with nesting depth;
459 /// with it, each `(id, proposal)` is computed at most once per pass.
460 /// `RefCell` because layout runs through shared `&WidgetArena` borrows.
461 layout_cache: std::cell::RefCell<
462 std::collections::HashMap<(WidgetId, ProposalKey), crate::widget::LayoutResponse>,
463 >,
464 /// True while [`measure_intrinsic`](Self::measure_intrinsic) is running.
465 /// In this mode `cached_layout_response` measures even dormant widgets
466 /// (and their dormant subtrees) and bypasses the cache, so an adaptive
467 /// container can size an item it intends to keep hidden without that size
468 /// leaking into the normal per-pass cache.
469 measuring: std::cell::Cell<bool>,
470 /// Active↔Dormant transitions of nodes carrying an `activation_signal`,
471 /// recorded by [`set_dormant`](Self::set_dormant) / [`activate`](Self::activate)
472 /// and drained by `WidgetTree::flush_activation_signals` *after* the
473 /// mutation completes. Signals are fired at the tree level, never from
474 /// inside the arena recursion — mirroring how `focus_within` /
475 /// `hover_within` are updated from `WidgetTree` methods rather than mid
476 /// mutation, so an observer (e.g. a `WebView`'s `set_visible`, which on a
477 /// real backend is an OS call) never runs while the arena is being walked.
478 /// Only nodes with a signal contribute, so the buffer is empty for the
479 /// overwhelming majority of trees.
480 pending_activation_changes: Vec<(WidgetId, bool)>,
481 /// Every node that installed an `effective_enabled_signal`, so the
482 /// per-pass refresh visits only opted-in nodes instead of the whole arena.
483 /// Unlike `pending_activation_changes` this is NOT a change queue: an
484 /// ancestor's `enabled` prop is a `Signal` that can flip at any time
485 /// without the arena being told, so there is no single mutation site to
486 /// record a transition at. The refresh recomputes and diffs instead —
487 /// see `WidgetTree::flush_effective_enabled_signals`. Dead ids are pruned
488 /// there, so a destroyed widget cannot leak.
489 effective_enabled_watchers: Vec<WidgetId>,
490}
491
492/// Hashable key for a [`teksilo_canvas::SizeProposal`] used by the per-pass
493/// layout cache. Each axis is encoded to a `u64`: `None` → a sentinel
494/// distinct from any finite `f32`, `Some(v)` → the canonicalized `f32` bits
495/// (`-0.0` folded to `0.0`, all NaNs folded to one pattern) so two equal
496/// proposals always hash and compare equal.
497#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
498struct ProposalKey([u64; 2]);
499
500impl ProposalKey {
501 fn from_proposal(p: teksilo_canvas::SizeProposal) -> Self {
502 fn axis_bits(v: Option<f32>) -> u64 {
503 match v {
504 // `f32::to_bits()` widens into 0..=u32::MAX, so u64::MAX is a
505 // safe sentinel that no `Some(_)` can collide with.
506 None => u64::MAX,
507 Some(f) => {
508 let canon = if f == 0.0 {
509 0.0
510 } else if f.is_nan() {
511 f32::NAN
512 } else {
513 f
514 };
515 canon.to_bits() as u64
516 }
517 }
518 }
519 Self([axis_bits(p.width), axis_bits(p.height)])
520 }
521}
522
523impl WidgetArena {
524 pub fn new() -> Self {
525 Self {
526 nodes: SlotMap::with_key(),
527 theme_override_count: 0,
528 cached_roots: Vec::new(),
529 roots_dirty: true,
530 layout_cache: std::cell::RefCell::new(std::collections::HashMap::new()),
531 measuring: std::cell::Cell::new(false),
532 pending_activation_changes: Vec::new(),
533 effective_enabled_watchers: Vec::new(),
534 }
535 }
536
537 /// Clear the per-pass layout memoization cache. Called once at the start of
538 /// each layout pass — geometry (and therefore `layout_response` results)
539 /// may change between passes, so the cache is valid only within one pass.
540 pub(crate) fn clear_layout_cache(&self) {
541 self.layout_cache.borrow_mut().clear();
542 }
543
544 /// Compute a widget's layout response, memoized per `(id, proposal)` for
545 /// the current layout pass. Returns `None` if the id is missing or
546 /// dormant. Widgets that opt out via `Widget::cacheable_layout() == false`
547 /// (e.g. the inspector's bounds tracker, which deliberately mutates signals
548 /// in `layout_response`) bypass the cache so their side effect fires on
549 /// every call.
550 ///
551 /// The key is `(id, proposal)` only: `layout_response` also reads the
552 /// `LayoutContext` (resolved theme, layout direction, text backend), but
553 /// those are a stable function of `id` within a single pass, so the pair
554 /// uniquely determines the input.
555 pub(crate) fn cached_layout_response(
556 &self,
557 id: WidgetId,
558 proposal: teksilo_canvas::SizeProposal,
559 ctx: &crate::widget::LayoutContext,
560 ) -> Option<crate::widget::LayoutResponse> {
561 let node = self.nodes.get(id)?;
562 let measuring = self.measuring.get();
563 if node.activation != ActivationState::Active && !measuring {
564 return None;
565 }
566 // While measuring intrinsic sizes (incl. of dormant subtrees), bypass
567 // the cache entirely so a dormant widget's size never pollutes the
568 // normal per-pass cache.
569 if measuring || !node.widget.cacheable_layout() {
570 return Some(node.widget.layout_response(proposal, ctx));
571 }
572 let key = (id, ProposalKey::from_proposal(proposal));
573 // Scope the shared borrow so it is released before `layout_response`
574 // runs — that call recurses into children, which borrow the same
575 // `layout_cache` (read, then write) and would otherwise alias.
576 {
577 if let Some(cached) = self.layout_cache.borrow().get(&key) {
578 return Some(*cached);
579 }
580 }
581 let resp = node.widget.layout_response(proposal, ctx);
582 self.layout_cache.borrow_mut().insert(key, resp);
583 Some(resp)
584 }
585
586 /// Measure a widget's intrinsic `layout_response` size for `proposal`,
587 /// **regardless of activation** — including dormant/collapsed widgets and
588 /// their dormant subtrees. Returns `None` only if the id is absent.
589 ///
590 /// Adaptive containers (e.g. an overflow [`Toolbar`](crate) that collapses
591 /// items into a menu) use this to size an item they intend to keep hidden,
592 /// so they can decide when to show it again as space grows — something
593 /// `child_layout_response` cannot do, since it returns `None` for inactive
594 /// widgets.
595 ///
596 /// Runs uncached (a dormant widget's size never enters the per-pass cache)
597 /// and is re-entrant-safe (saves/restores the measuring flag). Calls
598 /// `layout_response`, which must be idempotent (see
599 /// [`Widget::cacheable_layout`]).
600 pub(crate) fn measure_intrinsic(
601 &self,
602 id: WidgetId,
603 proposal: teksilo_canvas::SizeProposal,
604 ctx: &crate::widget::LayoutContext,
605 ) -> Option<teksilo_canvas::Size> {
606 if !self.nodes.contains_key(id) {
607 return None;
608 }
609 let prev = self.measuring.replace(true);
610 // `cached_layout_response` (and every nested child query during this
611 // call) sees `measuring == true`, so it bypasses the active check and
612 // the cache for the whole subtree.
613 let resp = self.cached_layout_response(id, proposal, ctx);
614 self.measuring.set(prev);
615 resp.map(|r| r.size)
616 }
617
618 /// Insert a widget into the arena as a root-level widget.
619 pub fn insert(&mut self, widget: Box<dyn Widget>) -> WidgetId {
620 self.roots_dirty = true;
621 let children = widget.children();
622 let id = self.nodes.insert(WidgetNode::new(widget, None));
623 // Set up parent-child for declared children
624 for &child_id in &children {
625 if let Some(child_node) = self.nodes.get_mut(child_id) {
626 child_node.parent = Some(id);
627 }
628 }
629 if let Some(node) = self.nodes.get_mut(id) {
630 node.children = children;
631 }
632 id
633 }
634
635 /// Insert a widget as a child of the given parent.
636 pub fn insert_child(&mut self, parent: WidgetId, widget: Box<dyn Widget>) -> WidgetId {
637 assert!(
638 self.nodes.contains_key(parent),
639 "insert_child() called with invalid parent WidgetId {parent:?}"
640 );
641 self.roots_dirty = true;
642 let children = widget.children();
643 let id = self.nodes.insert(WidgetNode::new(widget, Some(parent)));
644 // Set up parent-child for declared children
645 for &child_id in &children {
646 if let Some(child_node) = self.nodes.get_mut(child_id) {
647 child_node.parent = Some(id);
648 }
649 }
650 if let Some(node) = self.nodes.get_mut(id) {
651 node.children = children;
652 }
653 if let Some(parent_node) = self.nodes.get_mut(parent) {
654 parent_node.children.push(id);
655 }
656 id
657 }
658
659 pub fn get(&self, id: WidgetId) -> Option<&WidgetNode> {
660 self.nodes.get(id)
661 }
662
663 pub fn get_mut(&mut self, id: WidgetId) -> Option<&mut WidgetNode> {
664 self.nodes.get_mut(id)
665 }
666
667 pub fn children(&self, id: WidgetId) -> &[WidgetId] {
668 self.nodes
669 .get(id)
670 .map(|n| n.children.as_slice())
671 .unwrap_or(&[])
672 }
673
674 pub fn parent(&self, id: WidgetId) -> Option<WidgetId> {
675 self.nodes.get(id).and_then(|n| n.parent)
676 }
677
678 pub fn bounds(&self, id: WidgetId) -> teksilo_canvas::Rect {
679 self.nodes
680 .get(id)
681 .map(|n| n.bounds)
682 .unwrap_or(teksilo_canvas::Rect::ZERO)
683 }
684
685 /// The accumulated 2D affine transform that maps `id`'s pre-transform
686 /// local-space points to screen space — equivalent to the renderer's
687 /// `transform_stack` top by the time it begins painting `id`. Used by
688 /// hit-testing and any consumer that needs to project a node's
689 /// pre-transform bounds into screen space (e.g. teksilo-scene's a11y
690 /// bounds projection of view-transformed scene items).
691 ///
692 /// **Composition order.** Mirrors `crates/teksilo-render/src/renderer.rs`'s
693 /// `PushTransform` handling: each push composes as
694 /// `new_top = device_t.then(prev_top)`, so the deepest (innermost)
695 /// transform is applied **first** to a local point and outer ancestors
696 /// compose afterward. Walking root→leaf, each ancestor's
697 /// `transform_prop` is folded in via `t.then(effective)` (NOT
698 /// `effective.then(t)`).
699 ///
700 /// Returns `Transform2D::IDENTITY` if no ancestor sets a non-identity
701 /// transform, which is the common case (90%+ of widgets).
702 pub fn effective_transform(&self, id: WidgetId) -> teksilo_canvas::Transform2D {
703 // Collect leaf→root, then iterate root→leaf. Composition is
704 // `t_new.then(effective_so_far)` so the outer ancestor is applied
705 // *after* the deeper push — matching the renderer's stack semantic
706 // (`device_t.then(prev_top)` at PushTransform).
707 let mut chain: Vec<WidgetId> = Vec::new();
708 let mut current = Some(id);
709 while let Some(c) = current {
710 chain.push(c);
711 current = self.parent(c);
712 }
713 let mut effective = teksilo_canvas::Transform2D::IDENTITY;
714 for node_id in chain.iter().rev() {
715 if let Some(node) = self.nodes.get(*node_id)
716 && let Some(p) = node.transform_prop.as_ref()
717 {
718 let t = p.get();
719 if !t.is_identity() {
720 effective = t.then(&effective);
721 }
722 }
723 }
724 effective
725 }
726
727 /// Convert a **window-space** pointer position into the **widget-local**
728 /// coordinate space of `id`'s event handlers — i.e. relative to `id`'s
729 /// top-left, after undoing any transform scopes between the window and
730 /// `id`. This is the single conversion the dispatcher applies before
731 /// handing a position to `on_tap` / `on_drag` / `on_pointer_event`, so
732 /// every handler sees positions in its own local space.
733 ///
734 /// The transform handling mirrors `Self::hit_test_recursive` so the
735 /// position a handler receives is in the same space the hit-test used
736 /// to pick it:
737 /// * A **content** transform node (`content_transform`, e.g.
738 /// `SceneView`) owns its transform and maps its content itself. The
739 /// framework feeds such a node positions in its **parent-effective**
740 /// space (the same space `hit_test_recursive` passes through
741 /// `inv(transform)`), with **no** bounds-origin subtraction — the
742 /// node's `view_transform` already accounts for its placement.
743 /// * Any other node (the 90%+ identity case, plus `Scale` / `Rotate`
744 /// self-transforms) receives widget-local coordinates: undo the full
745 /// transform chain including its own, then subtract its bounds
746 /// origin so the result is relative to its top-left.
747 ///
748 /// In the common no-transform case this collapses to
749 /// `window_point - bounds.origin`.
750 pub fn local_pointer_position(
751 &self,
752 id: WidgetId,
753 window_point: teksilo_canvas::Point,
754 ) -> teksilo_canvas::Point {
755 let content_transform = self.get(id).map(|n| n.content_transform).unwrap_or(false);
756 if content_transform {
757 // Parent-effective space, no origin subtraction (the node's
758 // own transform consumes these coordinates).
759 let to_parent = self
760 .parent(id)
761 .map(|p| self.effective_transform(p))
762 .unwrap_or(teksilo_canvas::Transform2D::IDENTITY);
763 return match to_parent.inverse() {
764 Some(inv) => inv.apply_point(window_point),
765 None => window_point,
766 };
767 }
768 let in_local = match self.effective_transform(id).inverse() {
769 Some(inv) => inv.apply_point(window_point),
770 // Degenerate transform: fall back to the raw point rather than
771 // dropping the event.
772 None => window_point,
773 };
774 let bounds = self.bounds(id);
775 teksilo_canvas::Point::new(in_local.x - bounds.x, in_local.y - bounds.y)
776 }
777
778 /// Get all root-level widget IDs (widgets with no parent).
779 pub fn roots(&self) -> Vec<WidgetId> {
780 if self.roots_dirty {
781 // Fall back to scanning when cache is stale.
782 // refresh_roots() should be called from layout() for the fast path.
783 return self
784 .nodes
785 .iter()
786 .filter(|(_, node)| node.parent.is_none())
787 .map(|(id, _)| id)
788 .collect();
789 }
790 self.cached_roots.clone()
791 }
792
793 /// Refresh the cached roots list. Call once per frame from layout().
794 pub fn refresh_roots(&mut self) {
795 if self.roots_dirty {
796 self.cached_roots = self
797 .nodes
798 .iter()
799 .filter(|(_, node)| node.parent.is_none())
800 .map(|(id, _)| id)
801 .collect();
802 self.roots_dirty = false;
803 }
804 }
805
806 /// Walk the active widget tree at `point` and return the deepest
807 /// widget under it (the front-most hit, last child wins). Honors
808 /// `event_pass_through` (such nodes pass through to whatever sits
809 /// behind them but their descendants are still hit-testable). Does
810 /// not consider overlays — for the full pointer-routing hit-test
811 /// see `WidgetTree::hit_test`.
812 ///
813 /// `exclude`: if `Some(id)`, that widget (and any descendants
814 /// within its subtree) are skipped during the walk. Used by the
815 /// debug inspector's picker tool to ignore the picker overlay
816 /// itself, and by drag-and-drop to ignore the drag preview.
817 pub fn hit_test_at(
818 &self,
819 point: teksilo_canvas::Point,
820 exclude: Option<WidgetId>,
821 ) -> Option<WidgetId> {
822 for &root in self.roots().iter().rev() {
823 if let Some(hit) = self.hit_test_recursive(root, point, exclude) {
824 return Some(hit);
825 }
826 }
827 None
828 }
829
830 /// Hit-test starting from a specific subtree root rather than the
831 /// arena's top-level roots. Same semantics as
832 /// [`hit_test_at`](Self::hit_test_at) but scoped — useful when
833 /// callers want to ignore everything outside a known subtree
834 /// (e.g. the inspector's picker hit-tests inside the user-root
835 /// subtree so it never resolves to its own chrome).
836 pub fn hit_test_in_subtree(
837 &self,
838 start: WidgetId,
839 point: teksilo_canvas::Point,
840 ) -> Option<WidgetId> {
841 self.hit_test_recursive(start, point, None)
842 }
843
844 /// Like [`hit_test_in_subtree`](Self::hit_test_in_subtree) but also
845 /// excludes a widget (and its descendants) from the walk. Lets the
846 /// overlay / drag-and-drop hit-test reuse the single canonical recursion
847 /// in `hit_test_recursive` instead of duplicating it.
848 pub fn hit_test_in_subtree_excluding(
849 &self,
850 start: WidgetId,
851 point: teksilo_canvas::Point,
852 exclude: Option<WidgetId>,
853 ) -> Option<WidgetId> {
854 self.hit_test_recursive(start, point, exclude)
855 }
856
857 fn hit_test_recursive(
858 &self,
859 id: WidgetId,
860 point: teksilo_canvas::Point,
861 exclude: Option<WidgetId>,
862 ) -> Option<WidgetId> {
863 if !self.is_active(id) || Some(id) == exclude {
864 return None;
865 }
866 // Decorative subtree: skip this node and ALL its descendants so
867 // the point falls through to whatever is painted behind. Checked
868 // before descending into children (the difference from
869 // `event_pass_through`, which is applied only after the children
870 // miss).
871 if self.get(id).map(|n| n.hit_transparent).unwrap_or(false) {
872 return None;
873 }
874 // The input point arrives in this node's parent-effective space. A
875 // `set_transform` scope is composed by the render walker around this
876 // node's subtree, so hit-testing mirrors it by inverse-applying the
877 // transform once. *Which* rectangle the transform applies to depends
878 // on whether it's a **content** transform or a **self** transform
879 // (see `WidgetNode::content_transform`):
880 //
881 // * A **content** transform (`content_transform`, e.g. `SceneView`) is
882 // a fixed viewport: its bounds are a rectangle in PARENT space and
883 // the transform pans / zooms only its CONTENT. Test the bounds
884 // against the parent-space point; inverse-transform only for
885 // descending into children, so the whole visible viewport stays
886 // interactive regardless of pan / zoom. (Without this, panning the
887 // content shifts the hittable region off the viewport — clicks /
888 // wheel over the visible scene fall through to whatever is behind.)
889 // * A **self** transform (`Scale` / `Rotate`, whose own bounds move
890 // with the transform) inverse-transforms first, then tests its
891 // bounds in the resulting local space (a click lands where the
892 // scaled / rotated visual actually is).
893 //
894 // Identity / missing transforms collapse both paths to the scalar
895 // case, so the hot path stays cheap. `content_transform` is
896 // `SceneView`-only today, so this only changes SceneView hit-testing;
897 // `Scale` / `Rotate` (also `clips_children`) keep the self-transform
898 // path.
899 let transform = self
900 .get(id)
901 .and_then(|n| n.transform_prop.as_ref())
902 .map(|p| p.get())
903 .filter(|t| !t.is_identity());
904 let content_transform = self.get(id).map(|n| n.content_transform).unwrap_or(false);
905 // A degenerate transform (collapsed axis) hides the entire subtree
906 // visually; `inverse()` returning None mirrors that for hit-testing.
907 let child_point = match transform {
908 Some(t) => t.inverse()?.apply_point(point),
909 None => point,
910 };
911 // Content-transform nodes test their (parent-space) viewport against
912 // the incoming point; everything else tests in the inverse-transformed
913 // local space.
914 let bounds_point = if content_transform {
915 point
916 } else {
917 child_point
918 };
919 let bounds = self.bounds(id);
920 if !bounds.contains(bounds_point) {
921 return None;
922 }
923 // Shape rejection: a widget with a non-rectangular silhouette (an
924 // ellipse / cloud scene node, a circular handle) can reject a point
925 // that is inside its bounding box but outside its actual shape via
926 // `Widget::hit_shape`. Returning None here lets the caller's
927 // reverse-sibling loop fall through to whatever is painted
928 // underneath — the same path `event_pass_through` takes, but
929 // shape-aware (only the rejected sub-region falls through, not the
930 // whole widget). Default `hit_shape` returns true, so rectangular
931 // widgets take this branch for free with no behavior change.
932 if let Some(node) = self.get(id)
933 && !node.widget.hit_shape(bounds_point, bounds)
934 {
935 return None;
936 }
937 let pass_through = self.get(id).map(|n| n.event_pass_through).unwrap_or(false);
938 let children: Vec<WidgetId> = self.children(id).to_vec();
939 for &child in children.iter().rev() {
940 if let Some(hit) = self.hit_test_recursive(child, child_point, exclude) {
941 return Some(hit);
942 }
943 }
944 if pass_through {
945 return None;
946 }
947 Some(id)
948 }
949
950 /// Iterate over all active widget IDs.
951 ///
952 /// Allocating wrapper around [`Self::active_ids_iter`]. Hot-path
953 /// callers that hold `&self` for the whole iteration should call
954 /// the iterator directly to avoid the per-call `Vec` allocation;
955 /// callers that need an owned snapshot (because they mutate
956 /// arena state inside the loop) should use
957 /// [`Self::fill_active_ids`] with a reusable buffer.
958 pub fn active_ids(&self) -> Vec<WidgetId> {
959 self.active_ids_iter().collect()
960 }
961
962 /// Stream all active widget IDs without allocating. The iterator
963 /// borrows the arena, so the caller cannot mutate it while
964 /// iterating — for that case use [`Self::fill_active_ids`].
965 pub fn active_ids_iter(&self) -> impl Iterator<Item = WidgetId> + '_ {
966 self.nodes
967 .iter()
968 .filter(|(_, node)| node.activation == ActivationState::Active)
969 .map(|(id, _)| id)
970 }
971
972 /// Fill `out` with every active widget ID. Clears `out` first so
973 /// callers can reuse a long-lived buffer across calls. Use this
974 /// when the iteration site needs an owned snapshot independent
975 /// of the arena borrow (typically because it mutates per-widget
976 /// state with `arena.get_mut(id)` inside the loop).
977 pub fn fill_active_ids(&self, out: &mut Vec<WidgetId>) {
978 out.clear();
979 out.extend(self.active_ids_iter());
980 }
981
982 /// Set a widget subtree to dormant state (state preserved, not rendered).
983 /// Recursively dormants all children.
984 ///
985 /// The node named here is marked self-parked (`WidgetNode::self_dormant`);
986 /// the descendants swept along by the recursion are not, since their
987 /// dormancy belongs to this ancestor rather than to them. That distinction
988 /// is what lets [`activate`](Self::activate) put the subtree back exactly as
989 /// it found it instead of waking content that was already closed.
990 pub fn set_dormant(&mut self, id: WidgetId) {
991 self.park(id, true);
992 }
993
994 /// [`set_dormant`](Self::set_dormant)'s body, plus whether `id` is being
995 /// parked on its own account or dragged along by an ancestor.
996 ///
997 /// A node already self-parked stays that way when an ancestor sweeps over
998 /// it — the flag is only ever set here, never cleared, so nesting two
999 /// dormancy cycles cannot lose the inner one.
1000 fn park(&mut self, id: WidgetId, on_its_own_account: bool) {
1001 if let Some(node) = self.nodes.get_mut(id) {
1002 let was_active = node.activation == ActivationState::Active;
1003 node.activation = ActivationState::Dormant;
1004 if on_its_own_account {
1005 node.self_dormant = true;
1006 }
1007 // Record the Active→Dormant transition for nodes that opted into an
1008 // activation signal; the signal is fired later by
1009 // `WidgetTree::flush_activation_signals`, not here — see the
1010 // `pending_activation_changes` field docs.
1011 if was_active && node.activation_signal.is_some() {
1012 self.pending_activation_changes.push((id, false));
1013 }
1014 }
1015 let children: Vec<WidgetId> = self.children(id).to_vec();
1016 for child in children {
1017 self.park(child, false);
1018 }
1019 }
1020
1021 /// Activate a dormant widget subtree (triggers relayout and repaint).
1022 /// Recursively activates all children, **except** those a descendant
1023 /// widget has independently gated off via `visible_when(false)`.
1024 ///
1025 /// The directly-targeted `id` is always activated (the caller asked for
1026 /// it). When recursing, a child whose own `visible_state` currently
1027 /// evaluates to `false` is left dormant along with its subtree: it is
1028 /// hidden by its own gate, not by the ancestor's dormancy, so a parent
1029 /// reactivation must not wake it. This is what keeps a `ComboBox`'s
1030 /// closed dropdown panel, a collapsed overlay, or any `visible_when`-
1031 /// gated child from leaking back to the screen when an ancestor (e.g. a
1032 /// `Toolbar` item reappearing from overflow) is re-activated. The
1033 /// per-pass visibility reconciliation
1034 /// ([`visibility_checks_iter`](Self::visibility_checks_iter)) still owns
1035 /// the eventual activate/dormant transitions when the gate flips.
1036 pub fn activate(&mut self, id: WidgetId) {
1037 if let Some(node) = self.nodes.get_mut(id) {
1038 // Only Dormant→Active is a real "show" transition. Guard on
1039 // `== Dormant` (not `!= Active`) so a `Destroyed` node — or any
1040 // future non-Active state — is never resurrected or signalled.
1041 let was_dormant = node.activation == ActivationState::Dormant;
1042 node.activation = ActivationState::Active;
1043 node.self_dormant = false;
1044 node.dirty.needs_layout = true;
1045 node.dirty.needs_paint = true;
1046 if was_dormant && node.activation_signal.is_some() {
1047 self.pending_activation_changes.push((id, true));
1048 }
1049 }
1050 let children: Vec<WidgetId> = self.children(id).to_vec();
1051 for child in children {
1052 let asleep_on_its_own_account = self
1053 .nodes
1054 .get(child)
1055 .map(|n| {
1056 n.self_dormant
1057 || n.visible_state
1058 .as_ref()
1059 .map(|vs| !vs.get())
1060 .unwrap_or(false)
1061 })
1062 .unwrap_or(false);
1063 if asleep_on_its_own_account {
1064 continue;
1065 }
1066 self.activate(child);
1067 }
1068 }
1069
1070 /// Destroy a widget and remove it from the arena entirely.
1071 /// Recursively destroys all children. State is gone.
1072 pub fn destroy(&mut self, id: WidgetId) {
1073 self.roots_dirty = true;
1074 let children: Vec<WidgetId> = self.children(id).to_vec();
1075 for child in children {
1076 self.destroy(child);
1077 }
1078 self.remove_node(id);
1079 }
1080
1081 /// Remove a *single* node: unlink it from its parent's child list and drop
1082 /// it from the arena. Does **not** recurse into its children.
1083 ///
1084 /// The caller owns the recursion. This exists for
1085 /// [`WidgetTree::destroy_subtree`](crate::widget_tree::WidgetTree) /
1086 /// the reconciling rebuild path, which walks the subtree itself so it can
1087 /// honour re-parenting — a child re-homed into the surviving tree must NOT
1088 /// be torn down via this node's now-stale `children` list. Using
1089 /// [`destroy`](Self::destroy) there would re-recurse that stale list and
1090 /// destroy the re-homed survivor.
1091 pub fn remove_node(&mut self, id: WidgetId) {
1092 self.roots_dirty = true;
1093 if let Some(parent_id) = self.parent(id)
1094 && let Some(parent) = self.nodes.get_mut(parent_id)
1095 {
1096 parent.children.retain(|&c| c != id);
1097 }
1098 self.nodes.remove(id);
1099 }
1100
1101 /// Drain the buffered Active↔Dormant transitions recorded since the last
1102 /// call. Each `(id, active)` is fed to `WidgetTree::flush_activation_signals`
1103 /// which fires the node's `activation_signal` — at the tree level, outside
1104 /// any arena mutation.
1105 pub(crate) fn take_activation_changes(&mut self) -> Vec<(WidgetId, bool)> {
1106 std::mem::take(&mut self.pending_activation_changes)
1107 }
1108
1109 /// Record that `id` installed an `effective_enabled_signal`. Idempotent —
1110 /// the signal is install-or-reuse, so a rebuild re-registering the same
1111 /// node must not grow the list.
1112 pub(crate) fn watch_effective_enabled(&mut self, id: WidgetId) {
1113 if !self.effective_enabled_watchers.contains(&id) {
1114 self.effective_enabled_watchers.push(id);
1115 }
1116 }
1117
1118 /// The nodes carrying an `effective_enabled_signal`, for the per-pass
1119 /// refresh. Cloned so the caller can recompute `is_enabled` (an immutable
1120 /// ancestor walk) without holding a borrow on the arena.
1121 pub(crate) fn effective_enabled_watchers(&self) -> Vec<WidgetId> {
1122 self.effective_enabled_watchers.clone()
1123 }
1124
1125 /// Drop watchers whose node is gone (destroyed / rebuilt away).
1126 pub(crate) fn prune_effective_enabled_watchers(&mut self) {
1127 self.effective_enabled_watchers
1128 .retain(|id| self.nodes.contains_key(*id));
1129 }
1130
1131 pub fn is_active(&self, id: WidgetId) -> bool {
1132 self.nodes
1133 .get(id)
1134 .map(|n| n.activation == ActivationState::Active)
1135 .unwrap_or(false)
1136 }
1137
1138 pub fn len(&self) -> usize {
1139 self.nodes.len()
1140 }
1141
1142 pub fn is_empty(&self) -> bool {
1143 self.nodes.is_empty()
1144 }
1145
1146 pub fn mark_all_clean(&mut self) {
1147 for (_, node) in self.nodes.iter_mut() {
1148 node.dirty = DirtyFlags::default();
1149 }
1150 }
1151
1152 pub fn any_needs_layout(&self) -> bool {
1153 self.nodes
1154 .values()
1155 .any(|n| n.activation == ActivationState::Active && n.dirty.needs_layout)
1156 }
1157
1158 pub fn any_needs_paint(&self) -> bool {
1159 self.nodes
1160 .values()
1161 .any(|n| n.activation == ActivationState::Active && n.dirty.needs_paint)
1162 }
1163
1164 pub fn mark_needs_paint(&mut self, id: WidgetId) {
1165 if let Some(node) = self.nodes.get_mut(id) {
1166 node.dirty.needs_paint = true;
1167 }
1168 }
1169
1170 /// Recursively mark a widget and all its descendants needs_paint.
1171 /// Used by callers that want a fresh paint of an entire subtree
1172 /// — e.g. a rich tooltip whose dwell indicator child would
1173 /// otherwise reuse its cached_paint while the parent re-runs
1174 /// some per-frame logic.
1175 pub fn mark_subtree_needs_paint(&mut self, id: WidgetId) {
1176 if let Some(node) = self.nodes.get_mut(id) {
1177 node.dirty.needs_paint = true;
1178 }
1179 let children: Vec<WidgetId> = self.children(id).to_vec();
1180 for child in children {
1181 self.mark_subtree_needs_paint(child);
1182 }
1183 }
1184
1185 pub fn mark_needs_layout(&mut self, id: WidgetId) {
1186 if let Some(node) = self.nodes.get_mut(id) {
1187 node.dirty.needs_layout = true;
1188 node.dirty.needs_paint = true;
1189 }
1190 }
1191
1192 /// Mark a widget as needing its `build()` re-run.
1193 /// Also marks for layout and paint since rebuilt children need both.
1194 pub fn mark_needs_rebuild(&mut self, id: WidgetId) {
1195 if let Some(node) = self.nodes.get_mut(id) {
1196 node.dirty.needs_rebuild = true;
1197 node.dirty.needs_layout = true;
1198 node.dirty.needs_paint = true;
1199 }
1200 }
1201
1202 /// Collect widgets that need their `build()` re-run (data-driven rebuild).
1203 /// Only returns active widgets with `needs_rebuild == true`.
1204 ///
1205 /// Allocating wrapper around [`Self::needs_rebuild_iter`]. Prefer
1206 /// the iterator on hot paths.
1207 pub fn collect_needs_rebuild(&self) -> Vec<WidgetId> {
1208 self.needs_rebuild_iter().collect()
1209 }
1210
1211 /// Stream widgets that need `build()` re-run without allocating.
1212 ///
1213 /// `needs_rebuild` is set only by `BindingLevel::Rebuild` bindings —
1214 /// i.e. on composing widgets that explicitly want `build()` re-run
1215 /// when their data model changes. It is intentionally NOT gated on
1216 /// the widget currently having children: a data-driven widget that
1217 /// builds its children directly and starts EMPTY (e.g. the toast
1218 /// host with no toasts yet, an empty list that renders rows without
1219 /// a persistent container) must still rebuild to materialise its
1220 /// FIRST child. `rebuild_single_widget` handles a childless widget
1221 /// correctly (nothing to tear down, then it adopts `build()`'s
1222 /// output).
1223 pub fn needs_rebuild_iter(&self) -> impl Iterator<Item = WidgetId> + '_ {
1224 self.nodes
1225 .iter()
1226 .filter(|(_, n)| n.activation == ActivationState::Active && n.dirty.needs_rebuild)
1227 .map(|(id, _)| id)
1228 }
1229
1230 /// Check all widgets with visible_state bindings and return
1231 /// (id, is_currently_active, should_be_visible) tuples.
1232 ///
1233 /// Allocating wrapper around [`Self::visibility_checks_iter`].
1234 pub fn visibility_checks(&self) -> Vec<(WidgetId, bool, bool)> {
1235 self.visibility_checks_iter().collect()
1236 }
1237
1238 /// Stream widgets with `visible_state` bindings without
1239 /// allocating. Each entry is `(id, is_currently_active,
1240 /// should_be_visible)`.
1241 pub fn visibility_checks_iter(&self) -> impl Iterator<Item = (WidgetId, bool, bool)> + '_ {
1242 self.nodes.iter().filter_map(|(id, node)| {
1243 node.visible_state.as_ref().map(|state| {
1244 let is_active = node.activation == ActivationState::Active;
1245 let should_be_visible = state.get();
1246 (id, is_active, should_be_visible)
1247 })
1248 })
1249 }
1250
1251 /// Check if a widget is effectively enabled, walking up the parent chain.
1252 ///
1253 /// Returns `false` if the widget itself or any ancestor has `enabled_state`
1254 /// bound to `false`. This lets containers like `GroupBox` disable a whole
1255 /// subtree by binding a single signal on their content wrapper.
1256 pub fn is_enabled(&self, id: WidgetId) -> bool {
1257 let mut current = Some(id);
1258 while let Some(node_id) = current {
1259 if let Some(node) = self.nodes.get(node_id) {
1260 if let Some(ref state) = node.enabled_state
1261 && !state.get()
1262 {
1263 return false;
1264 }
1265 current = node.parent;
1266 } else {
1267 return true;
1268 }
1269 }
1270 true
1271 }
1272
1273 /// Set a per-child alignment override on a widget.
1274 pub fn set_alignment_override(&mut self, id: WidgetId, alignment: teksilo_tokens::Alignment) {
1275 if let Some(node) = self.get_mut(id) {
1276 node.alignment_override = Some(alignment);
1277 }
1278 }
1279
1280 /// Mark a widget as clipping its children (scroll area, overflow hidden).
1281 pub fn set_clips_children(&mut self, id: WidgetId, clips: bool) {
1282 if let Some(node) = self.get_mut(id) {
1283 node.clips_children = clips;
1284 }
1285 }
1286
1287 /// The OS-IME descriptor for the widget at `id`, or `None` if the node
1288 /// is not a text-input surface (the default) or the id is unknown. The
1289 /// platform IME layer queries this for the focused widget to decide
1290 /// whether to enable the OS input method and with which purpose.
1291 pub fn ime_context(&self, id: WidgetId) -> Option<crate::ime::ImeContext> {
1292 self.get(id).and_then(|n| n.ime)
1293 }
1294
1295 /// Set (or clear, with `None`) the OS-IME descriptor for the widget at
1296 /// `id`.
1297 pub fn set_ime_context(&mut self, id: WidgetId, ime: Option<crate::ime::ImeContext>) {
1298 if let Some(node) = self.get_mut(id) {
1299 node.ime = ime;
1300 }
1301 }
1302
1303 /// Apply a `HandlerSet` to an existing node, merging handlers and
1304 /// transferring node-level metadata (focusable, cursor, clips,
1305 /// context menu). The `scope` argument controls whether the
1306 /// handlers go into the rebuild-cleared `handlers` slot or the
1307 /// persistent `external_handlers` slot.
1308 pub(crate) fn apply_handler_set(
1309 &mut self,
1310 id: WidgetId,
1311 handler_set: crate::widget_builder::HandlerSet,
1312 scope: HandlerScope,
1313 ) {
1314 if let Some(node) = self.get_mut(id) {
1315 let target = match scope {
1316 HandlerScope::Own => &mut node.handlers,
1317 HandlerScope::External => &mut node.external_handlers,
1318 };
1319 let existing = std::mem::take(target);
1320 *target = existing.merge(handler_set.handlers);
1321 if let Some(focusable) = handler_set.focusable {
1322 node.node_focusable = Some(focusable);
1323 }
1324 if let Some(tab_index) = handler_set.tab_index {
1325 node.node_tab_index = Some(tab_index);
1326 }
1327 if let Some(cursor) = handler_set.cursor {
1328 node.node_cursor = Some(cursor);
1329 }
1330 if let Some(clips) = handler_set.clips_children {
1331 node.clips_children = clips;
1332 }
1333 if let Some(ime) = handler_set.ime {
1334 node.ime = Some(ime);
1335 }
1336 if let Some(pass_through) = handler_set.event_pass_through {
1337 node.event_pass_through = pass_through;
1338 }
1339 if let Some(dead_zone) = handler_set.gesture_dead_zone {
1340 node.gesture_dead_zone = dead_zone;
1341 }
1342 if let Some(keyboard_capture) = handler_set.keyboard_capture {
1343 node.keyboard_capture = keyboard_capture;
1344 }
1345 if let Some(hit_transparent) = handler_set.hit_transparent {
1346 node.hit_transparent = hit_transparent;
1347 }
1348 if handler_set.context_menu_factory.is_some() {
1349 node.context_menu_factory = handler_set.context_menu_factory;
1350 }
1351 if let Some(sig) = handler_set.focus_within {
1352 node.focus_within_signal = Some(sig);
1353 }
1354 if let Some(sig) = handler_set.hover_within {
1355 node.hover_within_signal = Some(sig);
1356 }
1357 // Mirror builder-level accessibility overrides + subtree mode
1358 // onto the persistent WidgetNode so the accessibility tree
1359 // walker (and the event dispatcher, for action callbacks) can
1360 // read them after handler extraction.
1361 if handler_set.access.is_some() {
1362 node.access_overrides = handler_set.access;
1363 }
1364 if let Some(mode) = handler_set.access_subtree {
1365 node.access_subtree = mode;
1366 }
1367 }
1368 }
1369
1370 /// Get a widget's alignment override, if any.
1371 pub fn alignment_override(&self, id: WidgetId) -> Option<teksilo_tokens::Alignment> {
1372 self.get(id)?.alignment_override
1373 }
1374
1375 /// Temporarily take the widget box out of a node (for rebuild).
1376 /// The node remains in the arena with a placeholder.
1377 pub fn take_widget(&mut self, id: WidgetId) -> Option<Box<dyn Widget>> {
1378 let node = self.nodes.get_mut(id)?;
1379 // Replace with a minimal placeholder
1380 let taken = std::mem::replace(&mut node.widget, Box::new(PlaceholderWidget));
1381 Some(taken)
1382 }
1383
1384 /// Restore a widget box that was previously taken out.
1385 pub fn restore_widget(&mut self, id: WidgetId, widget: Box<dyn Widget>) {
1386 if let Some(node) = self.nodes.get_mut(id) {
1387 node.widget = widget;
1388 }
1389 }
1390
1391 /// Walk up the parent chain from `id` and mark each ancestor as needing layout.
1392 /// Called when a relayout-level binding changes, since a child's size change
1393 /// may affect its parent's size, and so on up to the root.
1394 pub fn mark_ancestors_need_layout(&mut self, id: WidgetId) {
1395 let mut current = self.parent(id);
1396 while let Some(pid) = current {
1397 if let Some(node) = self.get_mut(pid) {
1398 node.dirty.needs_layout = true;
1399 node.dirty.needs_paint = true;
1400 }
1401 current = self.parent(pid);
1402 }
1403 }
1404
1405 /// Mark all widgets as needing layout and paint (e.g. after a theme change).
1406 /// Also clears per-widget paint caches since the visual output is stale.
1407 pub fn mark_all_dirty(&mut self) {
1408 for (_, node) in self.nodes.iter_mut() {
1409 node.dirty.needs_layout = true;
1410 node.dirty.needs_paint = true;
1411 node.cached_paint = None;
1412 node.cached_post_paint = None;
1413 }
1414 }
1415
1416 /// Mark every active node for repaint **without** touching layout, rebuild,
1417 /// or the per-widget paint caches. Used for a global visual change that
1418 /// leaves geometry untouched — the window's active-state flip (caret
1419 /// hiding, selection desaturation, `DimWhenInactive`). Lighter than
1420 /// [`Self::mark_all_dirty`]: the paint walker re-runs `paint()` for any
1421 /// node whose `needs_paint` is set and overwrites its cache, so there is no
1422 /// need to clear `cached_paint`; and skipping `needs_layout` avoids a
1423 /// pointless relayout pass. Dormant nodes are skipped — they don't paint,
1424 /// and they're re-marked on reactivation.
1425 pub fn mark_all_needs_paint_only(&mut self) {
1426 for (_, node) in self.nodes.iter_mut() {
1427 if node.activation == ActivationState::Active {
1428 node.dirty.needs_paint = true;
1429 }
1430 }
1431 }
1432
1433 /// Resolve the effective theme for a widget by walking ancestors and
1434 /// applying any theme overrides encountered along the way.
1435 /// The base theme is the tree-level default.
1436 pub fn resolve_theme<'a>(
1437 &self,
1438 id: WidgetId,
1439 base: &'a crate::styles::Theme,
1440 ) -> std::borrow::Cow<'a, crate::styles::Theme> {
1441 // Fast path: if no widget has a theme override, borrow the base
1442 // theme — no clone. This is the per-widget hot path during layout
1443 // and paint, so avoiding `Theme::clone()` (which clones the
1444 // typography token strings and bumps ~34 style-slot `Rc`s) here
1445 // saves that work on every node, every pass, in the common case.
1446 if self.theme_override_count == 0 {
1447 return std::borrow::Cow::Borrowed(base);
1448 }
1449
1450 // Collect ancestor chain from root to widget
1451 let mut chain = vec![id];
1452 let mut current = self.parent(id);
1453 while let Some(pid) = current {
1454 chain.push(pid);
1455 current = self.parent(pid);
1456 }
1457 chain.reverse(); // root first
1458
1459 let mut theme = base.clone();
1460 for nid in chain {
1461 if let Some(node) = self.nodes.get(nid)
1462 && let Some(ovr) = &node.theme_override
1463 {
1464 (ovr.func)(&mut theme);
1465 }
1466 }
1467 std::borrow::Cow::Owned(theme)
1468 }
1469}
1470
1471impl Default for WidgetArena {
1472 fn default() -> Self {
1473 Self::new()
1474 }
1475}
1476
1477#[cfg(test)]
1478mod tests {
1479 use super::*;
1480 use crate::test_widgets::FillWidget;
1481 use teksilo_canvas::SizeProposal;
1482
1483 fn key(w: Option<f32>, h: Option<f32>) -> ProposalKey {
1484 ProposalKey::from_proposal(SizeProposal {
1485 width: w,
1486 height: h,
1487 })
1488 }
1489
1490 #[test]
1491 fn activate_skips_a_child_gated_off_by_visible_state() {
1492 // Reactivating a subtree must not wake a child that its own widget
1493 // has gated off via `visible_when(false)` — e.g. a ComboBox's closed
1494 // dropdown panel, or a collapsed overlay. Regression for ghost
1495 // dropdown rows after a `visible_when` collapse→reappear cycle.
1496 let mut arena = WidgetArena::new();
1497 let parent = arena.insert(Box::new(FillWidget::new()));
1498 let visible_child = arena.insert_child(parent, Box::new(FillWidget::new()));
1499 let gated_child = arena.insert_child(parent, Box::new(FillWidget::new()));
1500 // The gated child is hidden by its own visibility gate.
1501 if let Some(node) = arena.get_mut(gated_child) {
1502 node.visible_state = Some(Prop::Static(false));
1503 }
1504
1505 arena.set_dormant(parent);
1506 assert!(!arena.is_active(gated_child));
1507
1508 arena.activate(parent);
1509 assert!(arena.is_active(parent), "the targeted node activates");
1510 assert!(
1511 arena.is_active(visible_child),
1512 "an ungated child activates with its parent"
1513 );
1514 assert!(
1515 !arena.is_active(gated_child),
1516 "a visible_when(false) child stays dormant when its parent reactivates"
1517 );
1518 }
1519
1520 #[test]
1521 fn activate_skips_a_child_parked_directly_by_set_dormant() {
1522 // The ungated twin of the test above, and the one that was missing.
1523 //
1524 // Widgets that pre-build hidden content register it as a child with
1525 // `ctx.add(..)` + `ctx.set_dormant(..)` and show it through an overlay:
1526 // `SplitButton` and `MenuBar` menus, `Popover`, `Snackbar`, the date
1527 // editors' calendars. Such a child carries no `visible_state`, so the
1528 // gate check alone let an ancestor's dormancy cycle wake it — and it
1529 // then rendered inline, with no overlay behind it, because the overlay
1530 // presentation never ran. Seen as export menu-item labels floating
1531 // under the title bar after leaving a mode that parked the shell.
1532 let mut arena = WidgetArena::new();
1533 let parent = arena.insert(Box::new(FillWidget::new()));
1534 let visible_child = arena.insert_child(parent, Box::new(FillWidget::new()));
1535 let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
1536 let menu_row = arena.insert_child(menu, Box::new(FillWidget::new()));
1537
1538 // The widget parks its own closed menu — no gate involved.
1539 arena.set_dormant(menu);
1540 assert!(!arena.is_active(menu));
1541
1542 // An ancestor now goes dormant and comes back.
1543 arena.set_dormant(parent);
1544 arena.activate(parent);
1545
1546 assert!(arena.is_active(parent), "the targeted node activates");
1547 assert!(
1548 arena.is_active(visible_child),
1549 "an ordinary child activates with its parent"
1550 );
1551 assert!(
1552 !arena.is_active(menu),
1553 "the ancestor's dormancy cycle woke a menu that was closed before it \
1554 started — its content is now on screen with no overlay behind it"
1555 );
1556 assert!(
1557 !arena.is_active(menu_row),
1558 "the closed menu's own subtree woke with it"
1559 );
1560
1561 // …and opening it still works: activating by id is how the overlay
1562 // shows this content, so it must clear the self-parked mark.
1563 arena.activate(menu);
1564 assert!(arena.is_active(menu), "the menu can still be opened");
1565 assert!(arena.is_active(menu_row), "…along with its rows");
1566 }
1567
1568 #[test]
1569 fn a_reopened_menu_parks_again_and_survives_the_next_cycle() {
1570 // The flag must be re-armed by every `set_dormant`, not just the first:
1571 // open the menu, close it, then put an ancestor through another
1572 // dormancy cycle. Without re-arming, the second cycle leaks.
1573 let mut arena = WidgetArena::new();
1574 let parent = arena.insert(Box::new(FillWidget::new()));
1575 let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
1576
1577 arena.set_dormant(menu);
1578 arena.activate(menu); // opened
1579 arena.set_dormant(menu); // dismissed
1580
1581 arena.set_dormant(parent);
1582 arena.activate(parent);
1583 assert!(
1584 !arena.is_active(menu),
1585 "a menu that was opened once no longer stays closed across a \
1586 dormancy cycle"
1587 );
1588 }
1589
1590 #[test]
1591 fn an_ancestor_cycle_does_not_strand_an_open_menu() {
1592 // The mirror risk of the fix: `park` marks only the node it is given,
1593 // so a menu that is *open* when an ancestor parks must come back with
1594 // that ancestor rather than being stranded closed.
1595 let mut arena = WidgetArena::new();
1596 let parent = arena.insert(Box::new(FillWidget::new()));
1597 let menu = arena.insert_child(parent, Box::new(FillWidget::new()));
1598
1599 arena.set_dormant(menu);
1600 arena.activate(menu); // open when the ancestor parks
1601
1602 arena.set_dormant(parent);
1603 arena.activate(parent);
1604 assert!(
1605 arena.is_active(menu),
1606 "an open menu was stranded closed by its ancestor's dormancy cycle"
1607 );
1608 }
1609
1610 #[test]
1611 fn proposal_key_distinguishes_none_from_zero() {
1612 // `None` (ask for ideal) must not collide with `Some(0.0)` (give zero).
1613 assert_ne!(key(None, None), key(Some(0.0), None));
1614 assert_ne!(key(Some(0.0), None), key(None, Some(0.0)));
1615 }
1616
1617 #[test]
1618 fn proposal_key_canonicalizes_signed_zero_and_nan() {
1619 assert_eq!(key(Some(-0.0), None), key(Some(0.0), None));
1620 assert_eq!(key(Some(f32::NAN), None), key(Some(f32::NAN), None));
1621 }
1622
1623 #[test]
1624 fn proposal_key_separates_distinct_values_and_axes() {
1625 assert_ne!(key(Some(1.0), None), key(Some(2.0), None));
1626 // Same scalar on different axes must not collide.
1627 assert_ne!(key(Some(10.0), None), key(None, Some(10.0)));
1628 }
1629
1630 #[test]
1631 fn insert_and_retrieve() {
1632 let mut arena = WidgetArena::new();
1633 let id = arena.insert(Box::new(FillWidget::new()));
1634 assert!(arena.get(id).is_some());
1635 assert_eq!(arena.len(), 1);
1636 }
1637
1638 #[test]
1639 fn new_widget_is_dirty() {
1640 let mut arena = WidgetArena::new();
1641 let id = arena.insert(Box::new(FillWidget::new()));
1642 let node = arena.get(id).unwrap();
1643 assert!(node.dirty.needs_layout);
1644 assert!(node.dirty.needs_paint);
1645 }
1646
1647 #[test]
1648 fn roots_returns_parentless_widgets() {
1649 let mut arena = WidgetArena::new();
1650 let root = arena.insert(Box::new(FillWidget::new()));
1651 let _child = arena.insert_child(root, Box::new(FillWidget::new()));
1652 let roots = arena.roots();
1653 assert_eq!(roots.len(), 1);
1654 assert_eq!(roots[0], root);
1655 }
1656
1657 #[test]
1658 fn content_transform_node_claims_viewport_in_parent_space() {
1659 // A content-transform node (the SceneView pattern) is a fixed
1660 // viewport: its bounds are tested in PARENT space and the transform
1661 // only positions its content, so the whole visible viewport stays
1662 // hittable regardless of the content pan/zoom. Before the fix, the
1663 // bounds were tested in content space, so a content pan shifted the
1664 // hittable region off the viewport.
1665 use teksilo_canvas::{Point, Rect, Transform2D};
1666 let mut arena = WidgetArena::new();
1667 let id = arena.insert(Box::new(FillWidget::new()));
1668 {
1669 let node = arena.get_mut(id).unwrap();
1670 node.bounds = Rect::new(0.0, 0.0, 200.0, 100.0);
1671 node.clips_children = true;
1672 node.content_transform = true;
1673 // Content panned by (50, 30).
1674 node.transform_prop = Some(Prop::Static(Transform2D::translate(50.0, 30.0)));
1675 }
1676 // Points across the whole parent-space viewport hit, regardless of the
1677 // pan (these all missed before the fix).
1678 assert_eq!(arena.hit_test_at(Point::new(10.0, 10.0), None), Some(id));
1679 assert_eq!(arena.hit_test_at(Point::new(100.0, 50.0), None), Some(id));
1680 assert_eq!(arena.hit_test_at(Point::new(199.0, 99.0), None), Some(id));
1681 // Outside the viewport: miss.
1682 assert_eq!(arena.hit_test_at(Point::new(250.0, 50.0), None), None);
1683 }
1684
1685 #[test]
1686 fn self_transform_node_tests_bounds_in_local_space() {
1687 // Regression guard: a *self* transform wrapper (Scale / Rotate, NOT a
1688 // content transform) keeps the original semantics — its own bounds
1689 // move with the transform, so the point is inverse-transformed before
1690 // the bounds test. `clips_children` is irrelevant here (Scale clips
1691 // too); only `content_transform` selects the viewport path.
1692 use teksilo_canvas::{Point, Rect, Transform2D};
1693 let mut arena = WidgetArena::new();
1694 let id = arena.insert(Box::new(FillWidget::new()));
1695 {
1696 let node = arena.get_mut(id).unwrap();
1697 node.bounds = Rect::new(0.0, 0.0, 100.0, 100.0);
1698 node.clips_children = true; // Scale clips, but is NOT content_transform.
1699 node.content_transform = false;
1700 // Visually scaled to 50x50 around the origin.
1701 node.transform_prop = Some(Prop::Static(Transform2D::scale(0.5, 0.5)));
1702 }
1703 // Inside the scaled-down 50x50 visual → hit.
1704 assert_eq!(arena.hit_test_at(Point::new(25.0, 25.0), None), Some(id));
1705 // Past the scaled-down visual (but inside the un-scaled 100x100 bounds
1706 // in parent space) → miss, because the bounds test is in local space.
1707 assert_eq!(arena.hit_test_at(Point::new(75.0, 75.0), None), None);
1708 }
1709
1710 #[test]
1711 fn nested_content_transform_nodes_each_claim_their_viewport() {
1712 // A content-transform node embedded inside another (the nested-
1713 // SceneView case): each level tests its own viewport bounds in its
1714 // parent's space, and only the transform is applied when descending.
1715 // The inner viewport stays hittable regardless of either node's pan.
1716 use teksilo_canvas::{Point, Rect, Transform2D};
1717 let mut arena = WidgetArena::new();
1718 let outer = arena.insert(Box::new(FillWidget::new()));
1719 let inner = arena.insert_child(outer, Box::new(FillWidget::new()));
1720 {
1721 let n = arena.get_mut(outer).unwrap();
1722 n.bounds = Rect::new(0.0, 0.0, 200.0, 200.0);
1723 n.clips_children = true;
1724 n.content_transform = true;
1725 n.transform_prop = Some(Prop::Static(Transform2D::translate(20.0, 20.0)));
1726 }
1727 {
1728 let n = arena.get_mut(inner).unwrap();
1729 // Inner viewport expressed in the OUTER's content space.
1730 n.bounds = Rect::new(10.0, 10.0, 50.0, 50.0);
1731 n.clips_children = true;
1732 n.content_transform = true;
1733 n.transform_prop = Some(Prop::Static(Transform2D::translate(5.0, 5.0)));
1734 }
1735 // Screen (40,40) → outer-content (20,20) ∈ inner viewport → reaches inner.
1736 assert_eq!(arena.hit_test_at(Point::new(40.0, 40.0), None), Some(inner));
1737 // Screen (5,5) → outer-content (-15,-15) ∉ inner viewport → reaches outer.
1738 assert_eq!(arena.hit_test_at(Point::new(5.0, 5.0), None), Some(outer));
1739 }
1740
1741 /// Accepts only the right half of its bounds via `hit_shape`; the left
1742 /// half is rejected so a click there falls through to a sibling beneath.
1743 #[derive(Debug)]
1744 struct RightHalfWidget;
1745
1746 impl crate::widget::Widget for RightHalfWidget {
1747 fn layout_response(
1748 &self,
1749 proposal: teksilo_canvas::SizeProposal,
1750 _ctx: &crate::widget::LayoutContext,
1751 ) -> crate::widget::LayoutResponse {
1752 proposal.resolve(0.0, 0.0).into()
1753 }
1754
1755 fn hit_shape(
1756 &self,
1757 local_point: teksilo_canvas::Point,
1758 bounds: teksilo_canvas::Rect,
1759 ) -> bool {
1760 local_point.x >= bounds.x + bounds.width / 2.0
1761 }
1762 }
1763
1764 #[test]
1765 fn hit_shape_rejection_falls_through_to_sibling_underneath() {
1766 // Two overlapping siblings under a common parent. `lower` is a
1767 // full-rect FillWidget; `upper` (inserted later → painted on top,
1768 // hit-tested first) rejects its left half via `hit_shape`. A click in
1769 // the rejected left half must reach `lower` underneath; a click in the
1770 // accepted right half must hit `upper`.
1771 use teksilo_canvas::{Point, Rect};
1772 let mut arena = WidgetArena::new();
1773 let parent = arena.insert(Box::new(FillWidget::new()));
1774 let lower = arena.insert_child(parent, Box::new(FillWidget::new()));
1775 let upper = arena.insert_child(parent, Box::new(RightHalfWidget));
1776 for id in [parent, lower, upper] {
1777 arena.get_mut(id).unwrap().bounds = Rect::new(0.0, 0.0, 100.0, 100.0);
1778 }
1779 // Right half: upper accepts → hit upper.
1780 assert_eq!(arena.hit_test_at(Point::new(75.0, 50.0), None), Some(upper));
1781 // Left half: upper rejects via hit_shape → falls through to lower.
1782 assert_eq!(arena.hit_test_at(Point::new(25.0, 50.0), None), Some(lower));
1783 }
1784}