Skip to main content

teksilo_core/
build_context.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! BuildContext — context available during Widget::build().
5//!
6//! Provides Signal-based APIs for creating reactive state, registering
7//! effects, and adding child widgets during the build lifecycle.
8
9use crate::binding::BindingRegistry;
10use crate::event_source::{SubscriptionHandle, SubscriptionId};
11use crate::signal::{ObserverHandle, Signal};
12use crate::widget_id::WidgetId;
13
14/// Context available during Widget::build().
15pub struct BuildContext<'a> {
16    pub(crate) tree: &'a mut crate::widget_tree::WidgetTree,
17    pub(crate) composite_id: Option<WidgetId>,
18    /// RAII handles for effects registered during this build cycle.
19    /// Transferred to the arena node's `effect_handles` after build returns.
20    pub(crate) effect_handles: Vec<ObserverHandle>,
21    /// Backend-event subscription handles registered during this build
22    /// cycle via `subscribe_event`. Transferred to the arena node's
23    /// `subscription_handles` after build returns.
24    pub(crate) subscription_handles: Vec<(SubscriptionId, SubscriptionHandle)>,
25    /// The `SubscriptionId`s the **previous** build of this same widget used, in the
26    /// order it created them. Empty on a first mount.
27    ///
28    /// A subscription's id is what crosses the thread boundary: the publisher-side
29    /// wrapper captures it by value and posts it, and the UI thread looks it up some
30    /// frames later. Minting a fresh id on every rebuild therefore silently destroys
31    /// every event already in flight, because `rebuild_single_widget` removes the
32    /// previous build's callbacks before `build()` runs and the queued event then names
33    /// an id nothing answers to. Re-using the ids here makes a subscription's identity
34    /// span the rebuilds of one widget, so an event posted before a rebuild is delivered
35    /// to the closure the *new* build installed.
36    ///
37    /// Matched **by position**, which is what makes it cheap and predictable: the Nth
38    /// `subscribe_event`/`subscribe_event_with_ctx` call of this build re-uses the id of
39    /// the Nth call of the last one. A build that subscribes fewer times simply leaves
40    /// the surplus ids unclaimed and they stay torn down; one that subscribes more
41    /// allocates fresh ids for the extras.
42    pub(crate) reusable_sub_ids: Vec<SubscriptionId>,
43}
44
45impl<'a> BuildContext<'a> {
46    /// The WidgetId of the widget being built.
47    pub fn self_id(&self) -> WidgetId {
48        self.composite_id
49            .expect("self_id() called outside of build()")
50    }
51
52    /// Add a widget to the tree.
53    pub fn add(&mut self, widget: impl crate::widget::Widget + 'static) -> WidgetId {
54        self.tree.add(widget)
55    }
56
57    /// Add a pre-boxed widget to the tree.
58    pub fn add_boxed(&mut self, widget: Box<dyn crate::widget::Widget>) -> WidgetId {
59        self.tree.add_boxed(widget)
60    }
61
62    /// Add a **parentless** widget this one owns: pre-built overlay content
63    /// (a dropdown menu, a date picker's calendar, a tooltip's nested cascade
64    /// children) that must not be reached by the child walk.
65    ///
66    /// Use this — never a bare [`add`](Self::add) — for anything built ahead of
67    /// time and parked with [`set_dormant`](Self::set_dormant) to be shown later
68    /// through an overlay. The two differ only in bookkeeping: `add` hands back
69    /// a node nothing owns, so the builder's own teardown cannot reach it and
70    /// every rebuild strands another copy in the arena; this records the
71    /// ownership edge, so the node dies with its owner and the previous
72    /// generation dies with each rebuild.
73    ///
74    /// Content that *can* be a child should be returned from `build()` as one
75    /// instead. This exists for content that cannot: activation and the paint
76    /// walk both descend through `children`, so a dormant popup parked there
77    /// wakes with its host and paints inline at zero size.
78    pub fn add_detached(&mut self, widget: impl crate::widget::Widget + 'static) -> WidgetId {
79        self.add_detached_boxed(Box::new(widget))
80    }
81
82    /// Insert a child whose subtree is **not built until `reveal` first turns
83    /// true**, and is retained from then on. Returns the host's id immediately.
84    ///
85    /// The shape this replaces is `ctx.add(panel)` followed by
86    /// `ctx.set_dormant(id)` — correct, but it builds content the user may never
87    /// open, on every rebuild of the owner. In a virtualized collection the
88    /// owner is a per-row delegate, so that cost is multiplied by the row count:
89    /// on a 40-row table whose cells each carried a four-item menu, the eager
90    /// form cost 325–552 ms per rebuild against 42–46 ms without the column at
91    /// all, and ~85% of it was the `add` rather than constructing the widget
92    /// value. See [`DeferredSubtree`](crate::deferred_subtree::DeferredSubtree)
93    /// for the full contract.
94    ///
95    /// Pass the same signal the content's `visible_when` gate uses. Everything
96    /// downstream of the returned id — `set_dormant` / `activate`,
97    /// `visible_when`, `OverlayRequest::content_id`, descendant checks,
98    /// dismissal — is unchanged; only when the subtree below it exists moves.
99    pub fn add_deferred(
100        &mut self,
101        reveal: crate::signal::Signal<bool>,
102        widget: impl crate::widget::Widget + 'static,
103    ) -> WidgetId {
104        self.add_deferred_boxed(reveal, Box::new(widget))
105    }
106
107    /// [`add_deferred`](Self::add_deferred) for an already-boxed widget.
108    pub fn add_deferred_boxed(
109        &mut self,
110        reveal: crate::signal::Signal<bool>,
111        widget: Box<dyn crate::widget::Widget>,
112    ) -> WidgetId {
113        self.add(crate::deferred_subtree::DeferredSubtree::new(
114            Some(reveal),
115            widget,
116        ))
117    }
118
119    /// [`add_deferred`](Self::add_deferred) for content the **framework**
120    /// materializes, kept as a child of the builder.
121    ///
122    /// The parented twin of
123    /// [`add_detached_deferred_on_demand`](Self::add_detached_deferred_on_demand),
124    /// for the two rich-tooltip attach paths: they have always parented their
125    /// body on the anchor's owner, and reparenting them to `detached` would move
126    /// which teardown reaps them. Only *when* the body is built changes.
127    ///
128    /// Worth the separate entry point because a rich tooltip is not one widget:
129    /// `RichTooltipWidget::build` eagerly pre-creates a nested tooltip for every
130    /// `:key` link in its body, recursively, so one attached tip expands into a
131    /// cascade. Built eagerly on a data view's row delegate, 29 rows of
132    /// Skribisto's Overview carried 1,305 tooltip widgets inside a 22,737-node
133    /// subtree, and tearing that down cost 5.3 s per arrow-key press — the
134    /// destroy, not the build.
135    pub fn add_deferred_on_demand(
136        &mut self,
137        widget: impl crate::widget::Widget + 'static,
138    ) -> WidgetId {
139        self.add(crate::deferred_subtree::DeferredSubtree::new(
140            None,
141            Box::new(widget),
142        ))
143    }
144
145    /// [`add_deferred`](Self::add_deferred) for content the **framework**
146    /// materializes rather than a widget's own open signal.
147    ///
148    /// The tooltip case: a tooltip body has no open signal a widget could hand
149    /// over — the tree decides, when a dwell matures. `WidgetTree` forces such
150    /// a host just before it consults `Widget::tooltip_has_content`, so the
151    /// body exists by the time anything asks it a question.
152    pub fn add_detached_deferred_on_demand(
153        &mut self,
154        widget: impl crate::widget::Widget + 'static,
155    ) -> WidgetId {
156        self.add_detached(crate::deferred_subtree::DeferredSubtree::new(
157            None,
158            Box::new(widget),
159        ))
160    }
161
162    /// [`add_deferred`](Self::add_deferred), inserted detached — the shape
163    /// overlay content wants, so it is owned by the builder and dies with it
164    /// rather than outliving every menu the user ever opened.
165    pub fn add_detached_deferred_boxed(
166        &mut self,
167        reveal: crate::signal::Signal<bool>,
168        widget: Box<dyn crate::widget::Widget>,
169    ) -> WidgetId {
170        self.add_detached(crate::deferred_subtree::DeferredSubtree::new(
171            Some(reveal),
172            widget,
173        ))
174    }
175
176    /// [`add_detached_deferred_boxed`](Self::add_detached_deferred_boxed) for an
177    /// unboxed widget.
178    pub fn add_detached_deferred(
179        &mut self,
180        reveal: crate::signal::Signal<bool>,
181        widget: impl crate::widget::Widget + 'static,
182    ) -> WidgetId {
183        self.add_detached_deferred_boxed(reveal, Box::new(widget))
184    }
185
186    /// [`add_detached`](Self::add_detached) for an already-boxed widget.
187    pub fn add_detached_boxed(&mut self, widget: Box<dyn crate::widget::Widget>) -> WidgetId {
188        let id = self.tree.add_boxed(widget);
189        let owner = self.self_id();
190        self.tree.record_detached(owner, id);
191        id
192    }
193
194    /// Add a Level 2 widget as a child of another widget.
195    pub fn add_child(
196        &mut self,
197        parent: WidgetId,
198        widget: impl crate::widget::Widget + 'static,
199    ) -> WidgetId {
200        self.tree.add_child(parent, widget)
201    }
202
203    // --- Signal APIs ---
204
205    /// Create a new mutable signal.
206    pub fn signal<T: 'static>(&mut self, value: T) -> Signal<T> {
207        Signal::new(value)
208    }
209
210    /// Create a new `Signal<f32>` that supports `animate_to()`.
211    /// Registered with the animation scheduler automatically. The owning
212    /// widget (`self_id()`) is recorded so that the scheduler can pause
213    /// the animation when the widget is offscreen, dormant, or rebuilt.
214    pub fn animated_signal(&mut self, value: f32) -> Signal<f32> {
215        let signal = Signal::new_animated(value);
216        let owner = self.self_id();
217        self.tree.register_animated_signal(&signal, owner);
218        signal
219    }
220
221    /// Register a pre-existing `Signal<f32>` for animation support.
222    /// Use this when the signal was created outside of `build()` (e.g. in the
223    /// widget constructor) and needs to be registered with the animation scheduler.
224    pub fn register_animated_signal(&mut self, signal: &Signal<f32>) {
225        let owner = self.self_id();
226        self.tree.register_animated_signal(signal, owner);
227    }
228
229    /// Read the OS-level `prefers-reduced-motion` preference. Widgets
230    /// that use looping or decorative animations (spinners, sprite
231    /// icons, marquee text, etc.) should skip starting them when this
232    /// returns `true` so the UI respects accessibility settings and —
233    /// as a bonus — draws no CPU/GPU.
234    pub fn prefers_reduced_motion(&self) -> bool {
235        self.tree.prefers_reduced_motion()
236    }
237
238    /// Build an [`AnimationSpec`](crate::animation_builder::AnimationSpec)
239    /// — the fluent ergonomic façade over `Signal<f32>::animate_to`.
240    /// Captures the theme's `MotionTokens` and the platform
241    /// reduced-motion preference at build time, returns a clonable
242    /// spec that event-handler closures can drive without
243    /// re-threading durations and easing.
244    ///
245    /// ```ignore
246    /// let knob_anim = ctx.animate().fast().standard();
247    /// handlers = handlers.on_tap(move |_, _| {
248    ///     knob_anim.to_or_snap(&knob_position, target);
249    /// });
250    /// ```
251    pub fn animate(&self) -> crate::animation_builder::AnimationSpec {
252        crate::animation_builder::AnimationSpec::from_motion(
253            self.theme().motion.clone(),
254            self.prefers_reduced_motion(),
255        )
256    }
257
258    /// Opt into the shader-driven animated-quad pipeline. The widget
259    /// paint() emits ONE `canvas.draw_animated_quad(bounds, handle.slot(),
260    /// class)` call; the renderer samples per-slot state from its
261    /// uniform buffer each frame and the widget's paint() does not
262    /// re-run for animation ticks — only on layout changes. The
263    /// returned handle is stable for the widget-mount lifetime and
264    /// should be stashed on `self` to thread to `paint()`.
265    ///
266    /// For decorative motion that isn't a quad (scroll-offset tweens,
267    /// sidebar slide, toggle knob), keep using `ctx.animated_signal` +
268    /// `signal.animate_looping` — both paths coexist.
269    pub fn animated_quad(
270        &mut self,
271        kind: crate::animated_quad::AnimatedQuadKind,
272    ) -> crate::animated_quad::AnimatedQuadHandle {
273        let owner = self.self_id();
274        self.tree.register_animated_quad(owner, kind)
275    }
276
277    /// The per-frame delta-seconds signal. Observe it via
278    /// `ctx.effect(&ctx.frame_tick(), |delta| ...)` to run code once per
279    /// frame **the tree was explicitly asked to pump**. Merely observing
280    /// this signal does not keep the event loop awake — widgets must
281    /// call [`request_frame`](Self::request_frame) (typically from an
282    /// event handler or from inside the tick closure itself) to schedule
283    /// the next wake-up. This preserves Teksilo's draw-when-needed model.
284    pub fn frame_tick(&self) -> Signal<f32> {
285        self.tree.frame_tick()
286    }
287
288    /// Ask the tree to pump exactly one more frame. See
289    /// [`frame_tick`](Self::frame_tick) for the observer side.
290    pub fn request_frame(&self) {
291        self.tree.request_frame();
292    }
293
294    /// Request that the AccessKit tree be re-walked after this build pass.
295    /// Use when `build()` restructured its subtree in a way that changes the
296    /// accessibility tree (relayout alone no longer re-walks AT). `SceneView`
297    /// calls this each build, since it may have materialised or destroyed
298    /// scene widgets or applied a11y-only scene mutations.
299    pub fn request_accessibility_update(&self) {
300        self.tree.request_accessibility_update();
301    }
302
303    /// Clone the shared "frame requested" flag. Stash it on widget
304    /// state and call `.set(true)` from inside a frame-tick effect
305    /// closure to chain-request another frame without needing
306    /// mutable access to the tree. Used by widgets with continuous
307    /// frame needs (caret blink, drag auto-scroll, smooth
308    /// animations driven from a tick closure).
309    ///
310    /// **Prefer [`subscribe_frame_tick`](Self::subscribe_frame_tick)**
311    /// for visual-only continuous animations (Pulse, Cycle, …): the
312    /// scheduler-backed path automatically pauses the chain when the
313    /// owner widget is hidden, while this raw handle keeps the event
314    /// loop pumping at full frame rate regardless of visibility.
315    pub fn frame_request_handle(&self) -> std::rc::Rc<std::cell::Cell<bool>> {
316        self.tree.frame_request_handle()
317    }
318
319    /// Subscribe the widget being built to the per-frame-effect
320    /// scheduler. The returned RAII guard removes the subscription on
321    /// drop — store it on `self` so its lifetime tracks the widget's.
322    ///
323    /// While at least one subscriber's owner is visible, the framework
324    /// auto-arms `frame_tick_requested` after every render. When all
325    /// subscribers are hidden (e.g. parked inside a non-selected
326    /// `Switcher` branch), no re-arm happens and the chain dies, so
327    /// the event loop sleeps. On a hidden→visible transition the
328    /// `visible_when` binding's relayout dirty triggers a repaint that
329    /// paints the subscriber, which the post-render arm then detects
330    /// and resumes the chain.
331    ///
332    /// Replaces the widget-managed `frame_request.set(true)` re-arm
333    /// pattern for visual-only continuous animations. The widget's
334    /// `frame_tick` effect closure no longer needs to call
335    /// `frame_request.set(true)` itself — the scheduler handles it.
336    pub fn subscribe_frame_tick(&self) -> crate::frame_tick_scheduler::FrameTickSubscription {
337        let sub = self.tree.subscribe_frame_tick(self.self_id());
338        // Bootstrap: ensure at least one frame runs after registration
339        // so the first paint happens. The post-render re-arm takes over
340        // from there. This is also the resume nudge for the case where
341        // a widget rebuilds (e.g. due to a state change) while still
342        // hidden — the parent's relayout dirty will trigger paint, and
343        // post-render arm will pick up the chain.
344        self.tree.request_frame();
345        sub
346    }
347
348    /// Like [`subscribe_frame_tick`](Self::subscribe_frame_tick), but the
349    /// widget only needs to wake **at most once per `interval`** while
350    /// visible. Same visibility gate and RAII guard; between wakes the
351    /// event loop sleeps to the interval deadline rather than rendering
352    /// identical 60 fps frames. Use when the widget's visible output
353    /// changes far less often than 60 Hz — e.g. `Cycle`'s once-per-period
354    /// index advance, or a seconds-granular clock.
355    pub fn subscribe_frame_tick_throttled(
356        &self,
357        interval: std::time::Duration,
358    ) -> crate::frame_tick_scheduler::FrameTickSubscription {
359        let sub = self
360            .tree
361            .subscribe_frame_tick_throttled(self.self_id(), interval);
362        // Bootstrap the first frame after registration (see
363        // `subscribe_frame_tick`).
364        self.tree.request_frame();
365        sub
366    }
367
368    /// Clone the shared wake-at deadline cell. Stash it on widget
369    /// state and set `Some(instant)` from a frame-tick effect to
370    /// schedule a one-shot deadline wake-up without keeping the event
371    /// loop in `Poll` mode. See `WidgetTree::wake_at_handle` for
372    /// the underlying mechanism.
373    pub fn wake_at_handle(&self) -> std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>> {
374        self.tree.wake_at_handle()
375    }
376
377    /// Register a scoped effect tied to this build cycle.
378    /// The effect fires whenever the signal changes. It is automatically
379    /// cleaned up on rebuild or widget destruction.
380    pub fn effect<T: Clone + 'static>(&mut self, signal: &Signal<T>, f: impl Fn(&T) + 'static) {
381        let handle = signal.observe(f);
382        self.effect_handles.push(handle);
383    }
384
385    /// Register a pre-existing observer handle for lifecycle management.
386    /// The handle will be dropped (and the observer removed) on rebuild
387    /// or widget destruction.
388    pub fn own_handle(&mut self, handle: ObserverHandle) {
389        self.effect_handles.push(handle);
390    }
391
392    /// Get the binding registry.
393    pub fn binding_registry(&self) -> &BindingRegistry {
394        self.tree.binding_registry()
395    }
396
397    /// Get the current theme.
398    pub fn theme(&self) -> &crate::styles::Theme {
399        self.tree.theme()
400    }
401
402    /// Reactive handle on the current theme. Fires observers when
403    /// `tree.set_theme(...)` is called. Build implementations that want
404    /// theme-driven values to update without a rebuild should use this
405    /// instead of cloning tokens from `self.theme()` — for example,
406    /// `ctx.theme_signal().map(|t| t.colors.primary)` or combining with
407    /// interaction state via `zip(...)`.
408    pub fn theme_signal(&self) -> crate::signal::Signal<crate::styles::Theme> {
409        self.tree.theme_signal().clone()
410    }
411
412    /// Current combined text-scale factor (`user × OS`, `1.0` = 100 %). One-shot
413    /// read for build-time sizing; for a value that updates without a rebuild,
414    /// bind [`text_scale_signal`](Self::text_scale_signal) instead.
415    pub fn text_scale(&self) -> f32 {
416        self.tree.effective_text_scale()
417    }
418
419    /// Reactive handle on the combined text-scale factor. Fires when the user
420    /// scale, theme, or OS text-scale preference changes. Build implementations
421    /// that derive a build-time dimension from the scale (e.g. `Calendar`'s
422    /// fixed cell sizes) bind this — typically at `Rebuild` level so the change
423    /// recomputes the constants — since a scale change relayouts but does not
424    /// rebuild on its own.
425    pub fn text_scale_signal(&self) -> crate::signal::Signal<f32> {
426        self.tree.text_scale_signal()
427    }
428
429    /// Whether the host window is currently active (`focused AND not
430    /// occluded`). One-shot read for build-time use; for a value that reacts
431    /// to focus changes, bind [`window_active_signal`](Self::window_active_signal).
432    pub fn window_active(&self) -> bool {
433        self.tree.is_window_active()
434    }
435
436    /// Reactive handle on window-active state. Fires when the host window gains
437    /// or loses active status (`focused AND not occluded`). Build
438    /// implementations that show/hide appearance with window focus — caret
439    /// effects, the selection-colour swap in text fields, `DimWhenInactive` —
440    /// bind this, typically at `RepaintOnly` level (an active-state flip never
441    /// affects geometry). Starts `true`.
442    pub fn window_active_signal(&self) -> crate::signal::Signal<bool> {
443        self.tree.window_active_signal()
444    }
445
446    /// Reactive handle on the current locale. Fires observers when
447    /// `tree.set_locale(...)` is called.
448    pub fn locale_signal(&self) -> crate::signal::Signal<Option<String>> {
449        self.tree.locale_signal().clone()
450    }
451
452    /// The [`WindowState`](crate::window::WindowState) for the window
453    /// hosting this tree. `None` only for trees built outside of an
454    /// app (tests, headless scenarios). Use this to bind widgets to
455    /// window-level signals like `placement`, `size`, `focused`.
456    pub fn window(&self) -> Option<&crate::window::WindowState> {
457        self.tree.window_state()
458    }
459
460    /// Retrieve an application-scoped value of type `T` registered via
461    /// `TeksiloAppBuilder::app_state`. Returns `None` if no value of
462    /// that type was registered. The returned reference borrows from
463    /// the framework for the duration of the build pass.
464    pub fn app_state<T: 'static>(&self) -> Option<&T> {
465        self.tree.app_context().app_state::<T>()
466    }
467
468    /// Borrow the [`AppEventPoster`](crate::AppEventPoster) installed by the
469    /// framework, if any. Mirrors [`EventContext::poster`](crate::widget::EventContext::poster).
470    /// Used by integrations that wire a platform callback (e.g. a native menu
471    /// item) to post a typed payload back to the UI loop. Returns `None` for
472    /// trees built outside an app (tests / headless).
473    pub fn poster(&self) -> Option<&std::sync::Arc<dyn crate::AppEventPoster>> {
474        self.tree.app_context().poster()
475    }
476
477    /// Bind a widget's visibility to a boolean prop or compatibility state binding.
478    pub fn visible_when(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
479        self.tree.visible_when(id, state);
480    }
481
482    /// Enqueue a one-shot action to run shortly after this build, with a real
483    /// [`EventContext`](crate::widget::EventContext) — the only place a widget
484    /// can read the OS parent window handle (`ctx.parent_window_handle()`),
485    /// `app_state`, and `poster` *together*, after it is mounted under its
486    /// window. The action runs at most once per enqueue (the app loop drains
487    /// the queue each iteration); a widget that rebuilds must guard against
488    /// enqueuing twice. Built for widgets owning a native OS resource that
489    /// needs a window handle to initialise (a `WebView`'s engine subview);
490    /// ordinary widgets never need it.
491    pub fn run_after_mount(&mut self, f: impl FnOnce(&mut crate::widget::EventContext) + 'static) {
492        self.tree.queue_mount_action(Box::new(f));
493    }
494
495    /// Observe a node's framework activation as a `Signal<bool>` — `true`
496    /// while active, `false` while parked dormant by a `Switcher` /
497    /// `visible_when` gate. Initialised to the node's current state and
498    /// updated only on an actual Active↔Dormant transition.
499    ///
500    /// Ordinary widgets never need this: dormant subtrees are simply not
501    /// painted, so they vanish for free. It exists for the one case where
502    /// "not painted" ≠ "hidden" — a widget owning a native OS resource
503    /// that renders *outside* the wgpu pass (a `WebView`'s engine subview).
504    /// Such a widget does `ctx.effect(&ctx.activation_signal(id), move |a|
505    /// handle.set_visible(*a))` to hide/show the native surface in lockstep.
506    pub fn activation_signal(&mut self, id: WidgetId) -> Signal<bool> {
507        self.tree.activation_signal(id)
508    }
509
510    /// Reactive `Signal<bool>` that is `true` while the *focus scope* containing
511    /// the widget being built — its nearest focusable ancestor, e.g. the
512    /// enclosing `ListView` / `TreeView` — holds keyboard focus. Items outside
513    /// any focusable scope read a constant `true`.
514    ///
515    /// Drives **focus-aware selection**: a selected row renders with the active
516    /// `Selected` chrome while its view has focus and the muted
517    /// `SelectedInactive` chrome when focus moves elsewhere — the standard
518    /// desktop affordance (Qt `SH_ItemView_...`, macOS inactive selection) that
519    /// shows where the keyboard is. The scope is resolved at build time but the
520    /// signal stays live across focus changes.
521    pub fn view_focus_active(&mut self) -> Signal<bool> {
522        // Prefer the scope a containing data view explicitly established for its
523        // rows (deterministic, parenting-independent); else resolve by walking
524        // to the nearest focusable ancestor.
525        if let Some(scope) = self.tree.current_view_focus() {
526            return scope;
527        }
528        let id = self.self_id();
529        self.tree.view_focus_active_for(id)
530    }
531
532    /// Mark the widget being built as a **focus scope** for the rows/items it
533    /// builds next: any descendant's [`view_focus_active`](Self::view_focus_active)
534    /// (and `StandardItem`'s focus-aware selection / focus ring) reads *this*
535    /// widget's keyboard focus. A data view calls this around its row loop, then
536    /// [`end_view_focus`](Self::end_view_focus). Deterministic — unaffected by
537    /// arena parenting, which may not be wired while docked/virtualized rows build.
538    pub fn begin_view_focus(&mut self) -> Signal<bool> {
539        let id = self.self_id();
540        self.tree.begin_view_focus(id)
541    }
542
543    /// Like [`begin_view_focus`](Self::begin_view_focus) but keys the scope on
544    /// an explicit `node_id` rather than the widget being built. A view whose
545    /// rows are built by a **separate body-pane widget** (TableView /
546    /// TreeTableView / GridView) passes its own focusable root id so descendant
547    /// items resolve the *root's* keyboard focus — not the pane's, which is a
548    /// child of the root and so never holds focus itself.
549    pub fn begin_view_focus_for(&mut self, node_id: WidgetId) -> Signal<bool> {
550        self.tree.begin_view_focus(node_id)
551    }
552
553    /// End the focus scope opened by [`begin_view_focus`](Self::begin_view_focus).
554    pub fn end_view_focus(&mut self) {
555        self.tree.end_view_focus();
556    }
557
558    /// Input-modality "focus-visible" signal — `true` after keyboard input,
559    /// `false` after pointer input (the standard `:focus-visible` rule). Pair
560    /// with [`view_focus_active`](Self::view_focus_active) to draw a focus
561    /// ring only during keyboard navigation, not on mouse clicks.
562    pub fn focus_visible(&self) -> Signal<bool> {
563        self.tree.focus_visible_signal()
564    }
565
566    /// Bind an opacity multiplier (0..1) to a widget. The render walker
567    /// emits `SetOpacity(value)` before painting the widget's subtree
568    /// and `RestoreOpacity` afterwards, so the multiplier composes
569    /// correctly with ancestor opacity scopes. Bound at `RepaintOnly`:
570    /// opacity changes never trigger relayout. Used by the `Fade`
571    /// wrapper to animate a child between hidden and fully visible.
572    pub fn set_opacity(&mut self, id: WidgetId, opacity: impl Into<crate::signal::Prop<f32>>) {
573        self.tree.set_opacity(id, opacity);
574    }
575
576    /// Bind a 2D affine transform to a widget. The render walker emits
577    /// `PushTransform(value)` before painting the widget's subtree and
578    /// `PopTransform` afterwards, so the transform composes onto the
579    /// renderer's stack with any ancestor transform scopes and with
580    /// the widget's own canvas-level transforms. Bound at `RepaintOnly`:
581    /// visual-only transforms never trigger relayout. Used by `Scale`
582    /// and `Rotate`; reflow-driving wrappers (e.g. `Scale::reflow(true)`)
583    /// must additionally bind their driver signal to themselves at
584    /// `Relayout` to make layout track the value.
585    pub fn set_transform(
586        &mut self,
587        id: WidgetId,
588        transform: impl Into<crate::signal::Prop<teksilo_canvas::Transform2D>>,
589    ) {
590        self.tree.set_transform(id, transform);
591    }
592
593    /// Bind a 2D affine **content** transform to a widget — the transform
594    /// positions the widget's content within its fixed parent-space viewport
595    /// (its bounds) rather than transforming the widget itself. Renders the
596    /// same `PushTransform` / `PopTransform` scope as
597    /// [`set_transform`](Self::set_transform), but hit-testing treats the
598    /// bounds as a fixed viewport so the whole visible area stays interactive
599    /// at any pan / zoom. Used by `SceneView` for its pan/zoom view transform.
600    pub fn set_content_transform(
601        &mut self,
602        id: WidgetId,
603        transform: impl Into<crate::signal::Prop<teksilo_canvas::Transform2D>>,
604    ) {
605        self.tree.set_content_transform(id, transform);
606    }
607
608    /// Bind a Gaussian-equivalent blur radius to a widget. The render
609    /// walker emits `BeginBlurredSubtree { bounds, radius }` before
610    /// painting the widget's subtree and `EndBlurredSubtree` afterwards;
611    /// the renderer redirects drawing into an intermediate texture, runs
612    /// a dual-Kawase blur chain at the requested radius, and composites
613    /// the blurred result back into the parent pass at the widget's
614    /// bounds. Bound at `RepaintOnly`: blur radius changes never trigger
615    /// relayout. Sub-perceptual radii (< 0.5) skip the Begin/End pair
616    /// entirely so animated enable/disable patterns have zero per-frame
617    /// cost when fully off. Used by the `Blur` wrapper.
618    pub fn set_blur(&mut self, id: WidgetId, radius: impl Into<crate::signal::Prop<f32>>) {
619        self.tree.set_blur(id, radius);
620    }
621
622    /// Bind a widget's enabled state to a boolean prop or compatibility state binding.
623    pub fn enabled_when(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
624        self.tree.enabled_when(id, state);
625    }
626
627    /// Reactive view of "is this widget effectively enabled?" — the AND
628    /// of the widget's own `enabled_state` and every ancestor's. The
629    /// arena's [`crate::arena::WidgetArena::is_enabled`] is the
630    /// non-reactive equivalent; this method gives composite widgets a
631    /// `Signal<bool>` they can `.map(...)` / `.zip(...)` against to
632    /// derive other reactive UI state (cursor, custom paint, helper
633    /// signals).
634    ///
635    /// Leaves like `IconWidget` / `TextWidget` / `RectWidget` do NOT
636    /// need this — they get the bool directly via
637    /// [`crate::widget::PaintContext::effective_enabled`] at paint time.
638    /// This method is for composites that need the value at build time
639    /// or want to chain signals.
640    ///
641    /// The signal is node-resident and framework-refreshed (install-or-reuse,
642    /// like [`Self::activation_signal`]), so it tracks ancestors correctly even
643    /// though a widget's parent is not yet wired while its own `build()` runs.
644    /// It is a *mutable* signal, so — unlike the old derived implementation —
645    /// it can be passed to [`Self::effect`].
646    ///
647    /// Returns a signal reading `true` for any node whose entire ancestor
648    /// chain (including itself) has no `enabled_state` bound.
649    pub fn effective_enabled_signal(&mut self, id: WidgetId) -> Signal<bool> {
650        self.tree.effective_enabled_signal(id)
651    }
652
653    /// Bind a widget's Tab-key participation to a boolean prop or
654    /// compatibility state binding. When false, the widget is removed
655    /// from Tab / Shift+Tab traversal but remains reachable via
656    /// `request_focus` and arrow-key navigation. Implements the ARIA
657    /// roving-tabindex pattern (HTML `tabindex="-1"` semantics).
658    pub fn set_tab_stop(&mut self, id: WidgetId, state: impl Into<crate::signal::Prop<bool>>) {
659        self.tree.set_tab_stop(id, state);
660    }
661
662    /// Declare the widget being built as a **traversal-scope boundary** for
663    /// Tab / Shift+Tab navigation. Descendants' `tab_index` values become
664    /// scoped to this node — they never collide with sibling scopes — and the
665    /// `policy` controls what happens at the scope's ends:
666    ///
667    /// - [`TraversalScopePolicy::Continue`](crate::focus::TraversalScopePolicy::Continue)
668    ///   — Tab flows out into the enclosing scope's next member (groups
669    ///   numbering only).
670    /// - [`TraversalScopePolicy::Cycle`](crate::focus::TraversalScopePolicy::Cycle)
671    ///   — Tab wraps within the scope, never exits. For **modal dialogs only**:
672    ///   a popover or menu is non-modal, and the framework closes one the
673    ///   keyboard walks out of rather than containing focus in it. Trapping such
674    ///   an overlay stops that dismissal from ever firing.
675    ///
676    /// This node is automatically excluded from being a Tab stop itself.
677    /// Prefer the `FocusScope` wrapper widget in `teksilo-widgets` over
678    /// calling this directly.
679    pub fn set_traversal_scope(&mut self, policy: crate::focus::TraversalScopePolicy) {
680        let id = self.self_id();
681        self.tree.set_traversal_scope(id, policy);
682    }
683
684    /// Attach a tooltip to a widget.
685    pub fn attach_tooltip(
686        &mut self,
687        anchor_id: WidgetId,
688        content_id: WidgetId,
689        delay: std::time::Duration,
690    ) {
691        self.tree.attach_tooltip(anchor_id, content_id, delay);
692        self.claim_tooltip_description(anchor_id);
693    }
694
695    /// Attach a tooltip with an explicit
696    /// [`TooltipPlacement`](crate::overlay::TooltipPlacement) — use `Side`
697    /// for anchors stacked vertically (menu items, a vertical tab strip,
698    /// list/tree rows) so the tooltip opens beside the anchor instead of
699    /// covering the next sibling.
700    pub fn attach_tooltip_with_placement(
701        &mut self,
702        anchor_id: WidgetId,
703        content_id: WidgetId,
704        delay: std::time::Duration,
705        placement: crate::overlay::TooltipPlacement,
706    ) {
707        self.tree
708            .attach_tooltip_with_placement(anchor_id, content_id, delay, placement);
709        self.claim_tooltip_description(anchor_id);
710    }
711
712    /// Attach a tooltip that auto-promotes to sticky after a dwell
713    /// timer. Non-None `sticky_after` enables the sticky-on-dwell UX:
714    /// once the tooltip has been shown for `sticky_after`, the tree
715    /// flags the entry sticky and swaps the overlay's dismiss
716    /// behavior to `EscapeOrClickOutside`.
717    pub fn attach_tooltip_with_sticky(
718        &mut self,
719        anchor_id: WidgetId,
720        content_id: WidgetId,
721        delay: std::time::Duration,
722        sticky_after: Option<std::time::Duration>,
723    ) {
724        self.tree
725            .attach_tooltip_with_sticky(anchor_id, content_id, delay, sticky_after);
726        self.claim_tooltip_description(anchor_id);
727    }
728
729    /// Variant of [`attach_tooltip_with_sticky`](Self::attach_tooltip_with_sticky)
730    /// that takes a shared `Rc<Cell<Option<Instant>>>` "sink" the
731    /// tree updates whenever the tooltip is shown / dismissed. The
732    /// tooltip widget reads from this sink to compute its own dwell
733    /// progress reliably, without needing a paint-gap heuristic.
734    pub fn attach_tooltip_with_sticky_sink(
735        &mut self,
736        anchor_id: WidgetId,
737        content_id: WidgetId,
738        delay: std::time::Duration,
739        sticky_after: Option<std::time::Duration>,
740        shown_at_sink: std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>,
741    ) {
742        self.tree.attach_tooltip_with_sticky_sink(
743            anchor_id,
744            content_id,
745            delay,
746            sticky_after,
747            shown_at_sink,
748        );
749        self.claim_tooltip_description(anchor_id);
750    }
751
752    /// Variant of [`attach_tooltip_with_sticky_sink`](Self::attach_tooltip_with_sticky_sink)
753    /// that also carries a [`TooltipPlacement`](crate::overlay::TooltipPlacement).
754    /// The full-featured path used by rich + composite tooltips that want
755    /// `Side` placement in a vertical context (menu items, list/tree rows).
756    pub fn attach_tooltip_with_sticky_sink_placement(
757        &mut self,
758        anchor_id: WidgetId,
759        content_id: WidgetId,
760        delay: std::time::Duration,
761        sticky_after: Option<std::time::Duration>,
762        shown_at_sink: std::rc::Rc<std::cell::Cell<Option<std::time::Instant>>>,
763        placement: crate::overlay::TooltipPlacement,
764    ) {
765        self.tree.attach_tooltip_with_sticky_sink_placement(
766            anchor_id,
767            content_id,
768            delay,
769            sticky_after,
770            shown_at_sink,
771            placement,
772        );
773        self.claim_tooltip_description(anchor_id);
774    }
775
776    /// Name this widget as the one the tooltip just attached describes.
777    ///
778    /// Every `attach_tooltip*` wrapper ends with this, so a composing control
779    /// gets it for free: `Button`, `Toggle` and the two dozen widgets shaped
780    /// like them hang the overlay off an inner chrome node -- the thing with
781    /// the right bounds to open against -- while their role, their name and
782    /// their focusability sit on their own outer node, which is the node an
783    /// assistive technology lands on and therefore the node a description has
784    /// to be on.
785    ///
786    /// A widget anchoring its tooltip on itself claims itself, which is what
787    /// it already had. A widget attaching *many* tooltips in one build -- a
788    /// list body pane, one per visible row -- claims itself for every one of
789    /// them, which is a claim that cannot be granted; the accessibility walk
790    /// is where that is noticed, because it is the only place the whole set
791    /// is visible at once.
792    fn claim_tooltip_description(&mut self, anchor_id: WidgetId) {
793        let owner = self.self_id();
794        self.tree.set_tooltip_description_owner(anchor_id, owner);
795    }
796
797    /// Promote a shown tooltip to "sticky": removes its auto-dismiss
798    /// on pointer-leave and swaps the overlay's dismiss behavior to
799    /// `EscapeOrClickOutside`. Used by rich tooltips that implement a
800    /// dwell timer.
801    pub fn promote_tooltip_to_sticky(&mut self, content_id: WidgetId) {
802        self.tree.promote_tooltip_to_sticky(content_id);
803    }
804
805    /// Set a widget as dormant (inactive). Used to pre-create overlay content
806    /// that will be activated later via `EventContext::activate()`.
807    pub fn set_dormant(&mut self, id: WidgetId) {
808        self.tree.set_dormant(id);
809    }
810
811    /// Destroy a widget and its entire subtree, removing them from the
812    /// arena and dropping any per-widget subscription / effect handles.
813    ///
814    /// Use this to clean up dormant subtrees that the current widget
815    /// created during a prior build and that live outside its regular
816    /// arena children — e.g., a pre-built popup panel inserted via
817    /// `ctx.add(..)` + `ctx.set_dormant(..)` that becomes stale after a
818    /// rebuild. Regular arena children of the composite (i.e. widgets
819    /// whose ids are returned from `build`) are destroyed automatically
820    /// by the framework's rebuild path and do not need this call.
821    ///
822    /// If an overlay currently references `id` as its content, the
823    /// overlay is dismissed first so the manager does not retain a
824    /// stale content reference.
825    pub fn destroy_subtree(&mut self, id: WidgetId) {
826        let overlay_id = self.tree.overlay_manager().find_by_content(id);
827        if let Some(overlay_id) = overlay_id {
828            self.tree.dismiss_overlay(overlay_id);
829        }
830        self.tree.destroy_subtree(id);
831    }
832
833    /// Apply a `HandlerSet` to the composite widget being built (self).
834    /// This transfers attached event handlers, focusable flag, cursor, etc.
835    /// to the widget's arena node, replacing `event()` and `is_focusable()` overrides.
836    pub fn apply_self_handlers(&mut self, handler_set: crate::widget_builder::HandlerSet) {
837        let id = self.self_id();
838        self.tree.apply_self_handler_set(id, handler_set);
839    }
840
841    /// Move keyboard focus to `id`. Mirrors
842    /// `EventContext::request_focus` for use during `build()` — e.g.
843    /// when a composing widget pre-builds an editor and needs focus to
844    /// land on it as soon as the subtree is wired in.
845    pub fn focus(&mut self, id: WidgetId) {
846        self.tree.focus(id);
847    }
848
849    /// Find the first focusable widget within the subtree rooted at
850    /// `root` in depth-first order. Returns `None` when the subtree has
851    /// no focusable descendant or `root` is not in the arena.
852    pub fn first_focusable_descendant(&self, root: WidgetId) -> Option<WidgetId> {
853        self.tree.first_focusable_descendant(root)
854    }
855
856    /// Move keyboard focus **into** the subtree rooted at `id`: its first
857    /// focusable descendant in tab order, or `id` itself when it is the only
858    /// focusable thing there. Returns whether focus ended up inside `id`.
859    ///
860    /// The build-time twin of
861    /// [`EventContext::request_focus_into`](crate::widget::EventContext::request_focus_into),
862    /// and safe here for the same reason [`focus`](Self::focus) is: `add` builds
863    /// a child's whole subtree synchronously, so by the time a composing widget
864    /// holds a child's id the focusable descendants of that child already exist.
865    ///
866    /// **Idempotent, and that is the point.** `build` runs again on every
867    /// rebuild, so a bare `focus` here would drag focus back into this subtree
868    /// every time the owner rebuilt for an unrelated reason — a table body pane
869    /// rebuilds on selection, on filtering and on scroll. This is a no-op while
870    /// focus already sits inside `id`, so it expresses "focus belongs in here"
871    /// rather than "focus here now".
872    ///
873    /// A subtree with nothing focusable leaves focus exactly where it was: an
874    /// empty region never traps it.
875    ///
876    /// ⚠ **Ancestor-chain side effects do not run**, and that is a property of
877    /// focusing from `build` at all, not of this method — [`focus`](Self::focus)
878    /// has it too. A node added during `build` is not parented until the build
879    /// that produced it *returns*, so at this moment `id`'s chain stops at
880    /// whatever the caller has already inserted: `focus_within` signals on
881    /// enclosing nodes never flip, and `scroll_focused_into_view` finds no
882    /// scroll container to reveal the target in. Everything **below** `id` is
883    /// linked (children are parented as each is inserted), so the walk that
884    /// picks the focusable descendant, and every later key dispatch — which
885    /// happens after the pass, on a whole tree — are unaffected.
886    ///
887    /// Reach for [`EventContext::request_focus_into`](crate::widget::EventContext::request_focus_into)
888    /// where the difference matters: it is queued and drained after dispatch,
889    /// against a complete tree.
890    pub fn focus_into(&mut self, id: WidgetId) -> bool {
891        if let Some(focused) = self.tree.focused()
892            && (focused == id || self.tree.is_descendant_of(focused, id))
893        {
894            return true;
895        }
896        match self.tree.first_focusable_descendant(id) {
897            Some(target) => {
898                self.tree.focus(target);
899                true
900            }
901            None => false,
902        }
903    }
904
905    // --- Actions & shortcuts ---
906
907    /// Attach an [`Action`](crate::action::Action) to the widget being
908    /// built. Actions are consulted during intent dispatch as the
909    /// framework walks source-widget → root; the first matching,
910    /// enabled action wins (subject to the `IntentResponse` returned
911    /// by its handler).
912    ///
913    /// Actions are cleared on rebuild, mirroring event handlers.
914    pub fn register_action(&mut self, action: crate::action::Action) {
915        let id = self.self_id();
916        self.tree.push_action(id, action);
917    }
918
919    /// Declare that the widget being built **edits text**.
920    ///
921    /// Every text widget should call this. It is what lets an application take
922    /// a text chord — `Ctrl+Z`, `Ctrl+C` — for itself without silently breaking
923    /// the widget it took it from: the host asks
924    /// [`focused_text_surface`](crate::widget_tree::WidgetTree::focused_text_surface)
925    /// and either drives this surface or steps aside so the widget keeps its own
926    /// keys. See [`crate::text_surface`] for the whole argument.
927    ///
928    /// Owned by the registering widget and torn down on its rebuild or destroy,
929    /// like [`register_action_global`](Self::register_action_global). Calling it
930    /// twice from one widget re-points rather than duplicating, so a rebuild
931    /// that hands over a fresh handle is correct.
932    pub fn register_text_surface(
933        &mut self,
934        surface: std::rc::Rc<dyn crate::text_surface::TextSurface>,
935    ) {
936        let id = self.self_id();
937        self.tree.push_text_surface(id, surface);
938    }
939
940    /// A cloneable view of this tree's registered text surfaces.
941    ///
942    /// Take it once, during `build`, and hold it: a view-model refreshed from a
943    /// frame tick has no `&WidgetTree` to consult, and that is exactly when it
944    /// needs to know whether the caret is in a text widget.
945    pub fn text_surfaces(&self) -> crate::text_surface::TextSurfaces {
946        self.tree.text_surfaces()
947    }
948
949    /// Register a **window-global** [`Action`](crate::action::Action), owned by
950    /// the widget being built. Unlike [`register_action`](Self::register_action)
951    /// — which only fires when this widget is on the intent's source→root walk —
952    /// a global action is consulted as a dispatch *fallback*, so it is reachable
953    /// no matter where the intent originated: a menu-bar dropdown (which renders
954    /// in an overlay, not under the registering widget), deep content, or a
955    /// global shortcut anchored at the root when nothing is focused.
956    ///
957    /// This is the action-side counterpart to
958    /// [`register_shortcut_global`](Self::register_shortcut_global): use it for
959    /// app-wide commands (`app.save`, `view.toggle_sidebar`) whose handler lives
960    /// at the app root but whose triggers (menu, toolbar, shortcut) are scattered
961    /// across the tree and chrome. Ownership applies: the action is torn down
962    /// when this widget rebuilds or is destroyed.
963    pub fn register_action_global(&mut self, action: crate::action::Action) {
964        let id = self.self_id();
965        self.tree.push_global_action(id, action);
966    }
967
968    /// Register a [`Shortcut`](crate::shortcut::Shortcut) in the
969    /// tree's registry, owned by the widget being built.
970    ///
971    /// If the shortcut builder left `scope` at the default
972    /// ([`ShortcutScope::Global`](crate::shortcut::ShortcutScope::Global)),
973    /// this method rewrites it to `Scoped(self_id)` so the shortcut
974    /// only fires when focus is inside the registering widget's
975    /// subtree — the ergonomic default for widget-declared shortcuts.
976    /// Callers that want an explicit global shortcut should use
977    /// [`BuildContext::register_shortcut_global`] instead; callers
978    /// that want to scope to a specific child should set
979    /// `.scope_to(child_id)` on the builder themselves.
980    ///
981    /// Ownership: the shortcut is removed from the registry when the
982    /// widget is destroyed or rebuilt. User overrides survive across
983    /// rebuilds (graveyard semantics).
984    pub fn register_shortcut(&mut self, mut shortcut: crate::shortcut::Shortcut) {
985        let id = self.self_id();
986        if shortcut.scope == crate::shortcut::ShortcutScope::Global {
987            shortcut.scope = crate::shortcut::ShortcutScope::Scoped(id);
988        }
989        self.tree
990            .shortcut_registry_mut()
991            .register_owned(shortcut, id);
992    }
993
994    /// Register a [`Shortcut`](crate::shortcut::Shortcut) with
995    /// explicit global scope, owned by the widget being built. Unlike
996    /// [`BuildContext::register_shortcut`], this does not rewrite the
997    /// scope — the shortcut fires regardless of focus position.
998    ///
999    /// Ownership still applies: the shortcut is torn down when this
1000    /// widget goes away.
1001    pub fn register_shortcut_global(&mut self, mut shortcut: crate::shortcut::Shortcut) {
1002        let id = self.self_id();
1003        shortcut.scope = crate::shortcut::ShortcutScope::Global;
1004        self.tree
1005            .shortcut_registry_mut()
1006            .register_owned(shortcut, id);
1007    }
1008
1009    /// Pre-declare shortcuts on behalf of a not-yet-mounted child
1010    /// (e.g. a `Switcher` walking its `Pending` slots' static
1011    /// declarations before they're inserted). Each shortcut is owned
1012    /// by the *calling* widget and its declared scope is preserved
1013    /// as-is — unlike [`register_shortcut`](Self::register_shortcut),
1014    /// no rewrite from `Global` to `Scoped(self)` happens, because
1015    /// the child intended its own scope.
1016    ///
1017    /// When the child is eventually mounted, the framework's
1018    /// insert-time walk of `Widget::declare_shortcuts` re-registers
1019    /// the same ids owned by the *child*; the registry's idempotent
1020    /// upsert moves ownership cleanly. If the child never mounts, the
1021    /// pre-declared entries stay alive (owned by the parent) so
1022    /// settings UIs still see them, and they get torn down when the
1023    /// parent goes away.
1024    pub fn register_pending_shortcuts(
1025        &mut self,
1026        shortcuts: impl IntoIterator<Item = crate::shortcut::Shortcut>,
1027    ) {
1028        let id = self.self_id();
1029        let registry = self.tree.shortcut_registry_mut();
1030        for shortcut in shortcuts {
1031            registry.register_owned(shortcut, id);
1032        }
1033    }
1034
1035    /// Read-through access to the tree's shortcut registry. Consumers
1036    /// (menus, tooltips) look up the effective keystroke for a given
1037    /// id here, and observe
1038    /// [`ShortcutRegistry::version`](crate::shortcut::ShortcutRegistry::version)
1039    /// to refresh when the user rebinds.
1040    pub fn shortcut_registry(&self) -> &crate::shortcut::ShortcutRegistry {
1041        self.tree.shortcut_registry()
1042    }
1043
1044    /// Effective view of a shortcut by id, merged with any user
1045    /// override. Returns `None` when no default has been registered
1046    /// for `id`. Typical caller pattern: call from `paint()` so
1047    /// late-registered shortcuts are still picked up without a
1048    /// dedicated build-phase query.
1049    pub fn effective_shortcut<'b>(
1050        &'b self,
1051        id: &str,
1052    ) -> Option<crate::shortcut::EffectiveShortcut<'b>> {
1053        self.shortcut_registry().effective(id)
1054    }
1055
1056    /// Convenience accessor for the reactive version signal. Widgets
1057    /// that render shortcut-derived state (menu labels, tooltips)
1058    /// observe this so the UI refreshes when the user rebinds or a
1059    /// new shortcut is registered.
1060    pub fn shortcut_version(&self) -> &Signal<u64> {
1061        self.shortcut_registry().version()
1062    }
1063
1064    /// A reactive, **per-id** handle to a shortcut's effective primary
1065    /// keystroke — the granular alternative to [`Self::shortcut_version`].
1066    /// Bind this to render one shortcut's accelerator as a *leaf* value
1067    /// (a menu item's trailing label, a tooltip) that refreshes in place
1068    /// when the user rebinds *that* id, without observing — and rebuilding
1069    /// on — every unrelated registry mutation. The signal is created on
1070    /// first request, seeded with the current value, and kept live by the
1071    /// registry across register / unregister / rebind of that id.
1072    pub fn effective_shortcut_signal(
1073        &mut self,
1074        id: &'static str,
1075    ) -> Signal<Option<crate::shortcut::KeyStroke>> {
1076        self.tree
1077            .shortcut_registry_mut()
1078            .effective_primary_signal(id)
1079    }
1080
1081    /// Apply a `HandlerSet` to a child widget created during this build.
1082    /// Use this to attach event handlers to children without wrapping them
1083    /// in `WidgetWithHandlers`.
1084    pub fn apply_handlers(
1085        &mut self,
1086        id: crate::widget_id::WidgetId,
1087        handler_set: crate::widget_builder::HandlerSet,
1088    ) {
1089        // A composing parent attaches handlers to a child — from the
1090        // child's perspective these are external and must survive the
1091        // child's own rebuilds.
1092        self.tree.apply_external_handler_set(id, handler_set);
1093    }
1094
1095    /// Wire an accessibility `labelled_by` relation from an already-mounted
1096    /// child (`id`) to its label (`label_id`), so assistive tech announces the
1097    /// field by its visible label (WCAG 3.3.2 / EN 301 549 11.5.2.7). Unlike
1098    /// the `.access_labelled_by(..)` builder method, this operates *after* the
1099    /// child is mounted (so a container like `FormLayout` can pair a label and
1100    /// a boxed field once both ids are resolved) and preserves any
1101    /// accessibility overrides the child already carries.
1102    pub fn access_labelled_by(
1103        &mut self,
1104        id: crate::widget_id::WidgetId,
1105        label_id: crate::widget_id::WidgetId,
1106    ) {
1107        self.tree.push_access_labelled_by(id, label_id);
1108    }
1109
1110    /// Wire an accessibility `described_by` relation from an already-mounted
1111    /// child (`id`) to a description/error node (`target_id`) — the
1112    /// post-mount, override-preserving counterpart of the
1113    /// `.access_described_by(..)` builder method (WCAG 3.3.1).
1114    pub fn access_described_by(
1115        &mut self,
1116        id: crate::widget_id::WidgetId,
1117        target_id: crate::widget_id::WidgetId,
1118    ) {
1119        self.tree.push_access_described_by(id, target_id);
1120    }
1121
1122    /// Subscribe to events from the registered application event source.
1123    /// The callback runs on the UI thread when the source publishes an
1124    /// event with a matching origin.
1125    ///
1126    /// The subscription is scoped to the current widget's lifetime: when
1127    /// the widget is rebuilt or destroyed, the framework drops the source
1128    /// handle (unregistering from the source) and removes the UI-side
1129    /// callback.
1130    ///
1131    /// # Panics
1132    ///
1133    /// Panics if no event source has been registered on the
1134    /// `TeksiloAppBuilder`. In debug builds, also asserts that the `Origin`
1135    /// and `Event` types match the registered source.
1136    /// The id this subscription should carry: the one the previous build used at this
1137    /// same position, or a fresh one.
1138    ///
1139    /// ⚠ **Position is the whole matching rule**, and it is deliberate. The alternative
1140    /// — matching on the origin — cannot be written here: `origin` reaches the adapter
1141    /// as `Box<dyn Any>`, with no `Eq` and no `Hash` to compare it by, and requiring
1142    /// either would change every `EventSource` in existence. Position is stable for the
1143    /// shape widgets actually have, where `build()` runs the same subscribe calls in the
1144    /// same order every time.
1145    ///
1146    /// What a widget that subscribes *conditionally* gets: if the origin at position N
1147    /// differs between two builds, an event still in flight from the old origin is
1148    /// delivered to the new build's callback rather than being dropped. That is safe by
1149    /// construction rather than by luck — an app registers exactly one `EventSource`, so
1150    /// every subscription in the tree shares one origin type and one event type, and the
1151    /// payload downcast cannot mismatch. The callback receives the whole event and can
1152    /// read its origin, which is what `Origin::LongOperation(..)` handlers already do.
1153    fn next_subscription_id(
1154        &self,
1155        app_context: &crate::event_source::TreeAppContext,
1156    ) -> SubscriptionId {
1157        // `subscription_handles` is pushed to once per subscribe call and starts empty
1158        // for each build, so its length *is* this call's position within the build.
1159        self.reusable_sub_ids
1160            .get(self.subscription_handles.len())
1161            .copied()
1162            .unwrap_or_else(|| app_context.allocate_subscription_id())
1163    }
1164
1165    pub fn subscribe_event<O, E, F>(&mut self, origin: O, callback: F)
1166    where
1167        O: 'static,
1168        E: 'static,
1169        F: Fn(&E) + 'static,
1170    {
1171        use std::any::{Any, TypeId};
1172        use std::sync::Arc;
1173
1174        let app_context = self.tree.app_context.clone();
1175
1176        let adapter = app_context.event_source.as_ref().expect(
1177            "BuildContext::subscribe_event called but no event source was registered \
1178             on TeksiloAppBuilder. Call .event_source(source) on the builder first.",
1179        );
1180
1181        debug_assert_eq!(
1182            adapter.origin_type,
1183            TypeId::of::<O>(),
1184            "subscribe_event origin type mismatch: source uses {}, subscribe call used {}",
1185            adapter.origin_type_name,
1186            std::any::type_name::<O>(),
1187        );
1188        debug_assert_eq!(
1189            adapter.event_type,
1190            TypeId::of::<E>(),
1191            "subscribe_event event type mismatch: source uses {}, subscribe call used {}",
1192            adapter.event_type_name,
1193            std::any::type_name::<E>(),
1194        );
1195
1196        let sub_id = self.next_subscription_id(&app_context);
1197
1198        // The UI-side callback that runs after an event posted from the
1199        // source thread is delivered back to the UI thread. It downcasts
1200        // the type-erased payload back to `&E` and invokes the user's `F`.
1201        let stored_callback: Box<dyn Fn(&dyn Any)> = Box::new(move |event_any| {
1202            let event = event_any
1203                .downcast_ref::<E>()
1204                .expect("subscription event downcast failed — framework bug");
1205            callback(event);
1206        });
1207        app_context
1208            .subscription_callbacks
1209            .borrow_mut()
1210            .insert(sub_id, stored_callback);
1211
1212        // Build the wrapper that the source will invoke from its
1213        // publisher thread. It carries only the sub_id (Copy) and an
1214        // Arc-clone of the poster (Send + Sync), boxes the typed event
1215        // as Any+Send, and posts an AppEvent::SubscriptionEvent through
1216        // the proxy. Tests that run without a registered poster post
1217        // events into a test queue and dispatch them back into the tree
1218        // via `tree.app_context().dispatch_subscription_event`.
1219        let poster = app_context
1220            .poster
1221            .as_ref()
1222            .expect(
1223                "BuildContext::subscribe_event called but no AppEventPoster \
1224                 is installed on the tree. teksilo-app installs one when an \
1225                 event source is registered on the builder; tests must \
1226                 supply a TestPoster via TreeAppContext::with_source_and_poster.",
1227            )
1228            .clone();
1229        let wrapper: Arc<dyn Fn(Box<dyn Any + Send>) + Send + Sync> =
1230            Arc::new(move |erased_event| {
1231                poster.post_subscription_event(sub_id, erased_event);
1232            });
1233
1234        let handle = (adapter.subscribe_fn)(Box::new(origin), wrapper);
1235        self.subscription_handles.push((sub_id, handle));
1236    }
1237
1238    /// Like [`subscribe_event`](Self::subscribe_event), but the UI-side
1239    /// callback additionally receives a fresh
1240    /// [`EventContext`](crate::widget::EventContext) bound to this widget's
1241    /// window. That lets it react to a backend event *imperatively* — update /
1242    /// replace / dismiss a toast, present a modal, `send_intent`, navigate —
1243    /// none of which a plain (context-free) `subscribe_event` callback can do
1244    /// (it can only poke `Signal`s).
1245    ///
1246    /// This is the supported bridge for **long-operation progress**: a Qleany
1247    /// `Origin::LongOperation(Progress | Completed | Cancelled | Failed)` event
1248    /// crosses from the operation's background thread to the UI thread and the
1249    /// callback drives an evolving progress toast (percentage in the body, a
1250    /// Cancel action, a success/error replacement on completion) — see the
1251    /// `toast_demo` example.
1252    ///
1253    /// The event is delivered on the UI thread through the same
1254    /// `AppEvent::SubscriptionEvent` path as `subscribe_event`; teksilo-app
1255    /// mints the `EventContext` from this widget's window tree just before the
1256    /// call (mirroring `teksilo-async`'s `spawn_local_with` completion path).
1257    /// The subscription is torn down with the widget, exactly like
1258    /// `subscribe_event`.
1259    ///
1260    /// The `<O, E>` type match against the registered event source is a
1261    /// `debug_assert` (as in [`subscribe_event`](Self::subscribe_event)); a
1262    /// mismatched call site in a release build is not caught here but panics
1263    /// later at the payload downcast.
1264    ///
1265    /// Registering from a windowless tree (headless / tests) is allowed but
1266    /// records `None` for the window — the app-side router then has no tree to
1267    /// mint an `EventContext` from and cannot deliver it, so such a subscription
1268    /// never fires in a running app. Ordinary application widgets always have a
1269    /// window; headless code that wants to observe events should use
1270    /// [`subscribe_event`](Self::subscribe_event) and drive `Signal`s instead.
1271    pub fn subscribe_event_with_ctx<O, E, F>(&mut self, origin: O, callback: F)
1272    where
1273        O: 'static,
1274        E: 'static,
1275        F: Fn(&E, &mut crate::widget::EventContext) + 'static,
1276    {
1277        use std::any::{Any, TypeId};
1278        use std::rc::Rc;
1279        use std::sync::Arc;
1280
1281        let window_id = self.window().map(|w| w.id());
1282
1283        let app_context = self.tree.app_context.clone();
1284
1285        let adapter = app_context.event_source.as_ref().expect(
1286            "BuildContext::subscribe_event_with_ctx called but no event source was registered \
1287             on TeksiloAppBuilder. Call .event_source(source) on the builder first.",
1288        );
1289
1290        debug_assert_eq!(
1291            adapter.origin_type,
1292            TypeId::of::<O>(),
1293            "subscribe_event_with_ctx origin type mismatch: source uses {}, subscribe call used {}",
1294            adapter.origin_type_name,
1295            std::any::type_name::<O>(),
1296        );
1297        debug_assert_eq!(
1298            adapter.event_type,
1299            TypeId::of::<E>(),
1300            "subscribe_event_with_ctx event type mismatch: source uses {}, subscribe call used {}",
1301            adapter.event_type_name,
1302            std::any::type_name::<E>(),
1303        );
1304
1305        // Re-used across this widget's rebuilds exactly as in `subscribe_event` — the
1306        // context-bearing path keeps its callbacks in a second map but crosses the very
1307        // same queue, so it loses in-flight events the very same way. See
1308        // [`Self::next_subscription_id`].
1309        let sub_id = self.next_subscription_id(&app_context);
1310
1311        // The UI-side callback, invoked after an event posted from the source
1312        // thread is delivered back to the UI thread and a fresh `EventContext`
1313        // has been minted. Downcasts the type-erased payload back to `&E` and
1314        // forwards it plus the context to the user's `F`. Stored behind `Rc` so
1315        // dispatch can drop the map borrow before invoking it (re-entrancy).
1316        let stored_callback: Rc<dyn Fn(&dyn Any, &mut crate::widget::EventContext)> =
1317            Rc::new(move |event_any, ctx| {
1318                let event = event_any
1319                    .downcast_ref::<E>()
1320                    .expect("subscription event downcast failed — framework bug");
1321                callback(event, ctx);
1322            });
1323        app_context
1324            .subscription_ctx_callbacks
1325            .borrow_mut()
1326            .insert(sub_id, (window_id, stored_callback));
1327
1328        // Same publisher-thread wrapper as `subscribe_event`: carry only the
1329        // sub_id (Copy) + an Arc-clone of the poster, box the typed event, and
1330        // post an `AppEvent::SubscriptionEvent`. The dispatch side (teksilo-app)
1331        // routes context-bearing sub_ids through the fresh-`EventContext` path.
1332        let poster = app_context
1333            .poster
1334            .as_ref()
1335            .expect(
1336                "BuildContext::subscribe_event_with_ctx called but no AppEventPoster \
1337                 is installed on the tree. teksilo-app installs one when an \
1338                 event source is registered on the builder.",
1339            )
1340            .clone();
1341        let wrapper: Arc<dyn Fn(Box<dyn Any + Send>) + Send + Sync> =
1342            Arc::new(move |erased_event| {
1343                poster.post_subscription_event(sub_id, erased_event);
1344            });
1345
1346        let handle = (adapter.subscribe_fn)(Box::new(origin), wrapper);
1347        self.subscription_handles.push((sub_id, handle));
1348    }
1349}
1350
1351#[cfg(test)]
1352mod effect_tests {
1353    use super::*;
1354    use crate::widget::{LayoutContext, Widget};
1355    use crate::widget_id::WidgetId;
1356    use crate::widget_tree::WidgetTree;
1357    use teksilo_canvas::SizeProposal;
1358
1359    /// A leaf widget that registers an effect on one signal to mirror its
1360    /// value into another. Produces no children.
1361    #[derive(Debug)]
1362    struct LeafWithEffect {
1363        source: Signal<i32>,
1364        mirror: Signal<i32>,
1365    }
1366
1367    impl Widget for LeafWithEffect {
1368        fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
1369            let mirror = self.mirror.clone();
1370            ctx.effect(&self.source, move |v| mirror.set(*v));
1371            Vec::new()
1372        }
1373
1374        fn layout_response(
1375            &self,
1376            proposal: SizeProposal,
1377            _ctx: &LayoutContext,
1378        ) -> crate::widget::LayoutResponse {
1379            proposal.resolve(0.0, 0.0).into()
1380        }
1381    }
1382
1383    /// A widget that observes the per-frame tick signal and accumulates the
1384    /// deltas it receives into a shared counter, so a test can verify both
1385    /// that the tick fires at all and that the delta value is non-zero.
1386    #[derive(Debug)]
1387    struct FrameTickListener {
1388        ticks: Signal<u32>,
1389        last_delta: Signal<f32>,
1390    }
1391
1392    impl Widget for FrameTickListener {
1393        fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
1394            let ticks = self.ticks.clone();
1395            let last_delta = self.last_delta.clone();
1396            let tick = ctx.frame_tick();
1397            ctx.effect(&tick, move |delta| {
1398                ticks.set(ticks.get() + 1);
1399                last_delta.set(*delta);
1400            });
1401            Vec::new()
1402        }
1403
1404        fn layout_response(
1405            &self,
1406            proposal: SizeProposal,
1407            _ctx: &LayoutContext,
1408        ) -> crate::widget::LayoutResponse {
1409            proposal.resolve(0.0, 0.0).into()
1410        }
1411    }
1412
1413    #[test]
1414    fn frame_tick_stays_silent_until_explicit_request() {
1415        // The draw-when-needed contract: a widget that merely observes
1416        // frame_tick must NOT keep the tree awake. Only an explicit
1417        // `request_frame()` call pumps a tick.
1418        let mut tree = WidgetTree::new();
1419        let ticks = Signal::new(0_u32);
1420        let last_delta = Signal::new(-1.0_f32);
1421        tree.add(FrameTickListener {
1422            ticks: ticks.clone(),
1423            last_delta: last_delta.clone(),
1424        });
1425
1426        // Flush the initial layout-dirty flag from widget insertion.
1427        tree.layout(teksilo_canvas::SizeProposal::exact(400.0, 300.0));
1428        assert!(
1429            !tree.frame_requested(),
1430            "observing frame_tick does not set the request flag"
1431        );
1432
1433        tree.tick_animations(std::time::Duration::from_millis(16));
1434        assert_eq!(
1435            ticks.get(),
1436            0,
1437            "an un-requested tick_animations must not fire frame_tick observers"
1438        );
1439        assert_eq!(last_delta.get(), -1.0);
1440    }
1441
1442    #[test]
1443    fn frame_tick_fires_once_per_request() {
1444        let mut tree = WidgetTree::new();
1445        let ticks = Signal::new(0_u32);
1446        let last_delta = Signal::new(-1.0_f32);
1447        let id = tree.add(FrameTickListener {
1448            ticks: ticks.clone(),
1449            last_delta: last_delta.clone(),
1450        });
1451
1452        // Flush initial layout-dirty flag so assertions reflect only
1453        // the frame-tick contract.
1454        tree.layout(teksilo_canvas::SizeProposal::exact(400.0, 300.0));
1455
1456        tree.request_frame();
1457        assert!(tree.needs_redraw(), "explicit request marks the tree dirty");
1458        assert!(tree.frame_requested());
1459
1460        tree.tick_animations(std::time::Duration::from_millis(16));
1461        assert_eq!(ticks.get(), 1);
1462        assert!((last_delta.get() - 0.016).abs() < 0.001);
1463        assert!(
1464            !tree.frame_requested(),
1465            "request flag must be cleared after the tick fired"
1466        );
1467
1468        // Second request fires exactly one more tick.
1469        tree.request_frame();
1470        tree.tick_animations(std::time::Duration::from_millis(16));
1471        assert_eq!(ticks.get(), 2);
1472
1473        // Without a request, further ticks silently advance time.
1474        tree.tick_animations(std::time::Duration::from_millis(16));
1475        assert_eq!(ticks.get(), 2);
1476
1477        tree.destroy_subtree(id);
1478        tree.request_frame();
1479        tree.tick_animations(std::time::Duration::from_millis(16));
1480        assert_eq!(
1481            ticks.get(),
1482            2,
1483            "destroyed widget's observer must not resurrect"
1484        );
1485    }
1486
1487    #[test]
1488    fn frame_tick_delta_clamped_against_huge_pauses() {
1489        let mut tree = WidgetTree::new();
1490        let ticks = Signal::new(0_u32);
1491        let last_delta = Signal::new(-1.0_f32);
1492        tree.add(FrameTickListener {
1493            ticks: ticks.clone(),
1494            last_delta: last_delta.clone(),
1495        });
1496
1497        tree.request_frame();
1498        tree.tick_animations(std::time::Duration::from_secs(5));
1499        assert_eq!(ticks.get(), 1);
1500        assert!(
1501            (last_delta.get() - 0.1).abs() < 1e-4,
1502            "frame delta must clamp at 0.1s even after a multi-second pause"
1503        );
1504    }
1505
1506    #[test]
1507    fn leaf_widget_effect_fires_and_is_cleaned_up_on_destroy() {
1508        // Regression guard: before the insert_widget / add_child fix,
1509        // effect_handles for a leaf widget (Vec::new() from build()) were
1510        // dropped the moment BuildContext went out of scope, silently
1511        // unregistering the observer. After the fix, the handle is
1512        // transferred to the arena node and the effect fires on signal
1513        // changes until the widget is destroyed.
1514        let mut tree = WidgetTree::new();
1515        let source = Signal::new(0_i32);
1516        let mirror = Signal::new(0_i32);
1517
1518        let id = tree.add(LeafWithEffect {
1519            source: source.clone(),
1520            mirror: mirror.clone(),
1521        });
1522
1523        // The effect should be live after insertion.
1524        source.set(42);
1525        assert_eq!(
1526            mirror.get(),
1527            42,
1528            "leaf widget effect must survive build() and fire on signal change"
1529        );
1530
1531        source.set(7);
1532        assert_eq!(mirror.get(), 7);
1533
1534        // Destroying the widget drops its effect_handles, which in turn
1535        // drops each ObserverHandle and unregisters the observer.
1536        tree.destroy_subtree(id);
1537        source.set(100);
1538        assert_eq!(
1539            mirror.get(),
1540            7,
1541            "effect must be unregistered after widget destruction"
1542        );
1543    }
1544}
1545
1546#[cfg(test)]
1547mod focus_into_tests {
1548    use super::*;
1549    use crate::widget::{LayoutContext, Widget};
1550    use crate::widget_builder::HandlerSet;
1551    use crate::widget_id::WidgetId;
1552    use crate::widget_tree::WidgetTree;
1553    use teksilo_canvas::SizeProposal;
1554
1555    /// A leaf that is focusable when asked, so the walk has something real to
1556    /// find — or nothing at all.
1557    #[derive(Debug)]
1558    struct Leaf {
1559        focusable: bool,
1560    }
1561
1562    impl Widget for Leaf {
1563        fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
1564            if self.focusable {
1565                ctx.apply_self_handlers(HandlerSet::new().focusable(true));
1566            }
1567            Vec::new()
1568        }
1569        fn layout_response(
1570            &self,
1571            proposal: SizeProposal,
1572            _ctx: &LayoutContext,
1573        ) -> crate::widget::LayoutResponse {
1574            proposal.resolve(10.0, 10.0).into()
1575        }
1576    }
1577
1578    /// Holds `focusable` focusable leaves and publishes their ids.
1579    #[derive(Debug)]
1580    struct Panel {
1581        focusable: usize,
1582        leaves: Signal<Vec<WidgetId>>,
1583    }
1584
1585    impl Widget for Panel {
1586        fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
1587            let kids: Vec<WidgetId> = (0..2)
1588                .map(|i| {
1589                    ctx.add(Leaf {
1590                        focusable: i < self.focusable,
1591                    })
1592                })
1593                .collect();
1594            self.leaves.set(kids.clone());
1595            kids
1596        }
1597        fn layout_response(
1598            &self,
1599            proposal: SizeProposal,
1600            _ctx: &LayoutContext,
1601        ) -> crate::widget::LayoutResponse {
1602            proposal.resolve(10.0, 10.0).into()
1603        }
1604    }
1605
1606    /// Calls `focus_into(panel)` on every one of *its own* builds, which is how
1607    /// a composing widget uses it. Rebuilt on demand through `tick` — and
1608    /// rebuilding it leaves the panel and its leaves alive, which is the whole
1609    /// point: that is the situation the idempotence has to survive.
1610    #[derive(Debug)]
1611    struct Driver {
1612        panel: Signal<Option<WidgetId>>,
1613        tick: Signal<u64>,
1614        moved: Signal<bool>,
1615    }
1616
1617    impl Widget for Driver {
1618        fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
1619            self.tick.bind_to(
1620                ctx.self_id(),
1621                ctx.binding_registry(),
1622                crate::binding::BindingLevel::Rebuild,
1623            );
1624            if let Some(panel) = self.panel.get() {
1625                let moved = ctx.focus_into(panel);
1626                self.moved.set(moved);
1627            }
1628            Vec::new()
1629        }
1630        fn layout_response(
1631            &self,
1632            proposal: SizeProposal,
1633            _ctx: &LayoutContext,
1634        ) -> crate::widget::LayoutResponse {
1635            proposal.resolve(0.0, 0.0).into()
1636        }
1637    }
1638
1639    struct Probe {
1640        tree: WidgetTree,
1641        leaves: Vec<WidgetId>,
1642        tick: Signal<u64>,
1643        moved: Signal<bool>,
1644    }
1645
1646    impl Probe {
1647        fn rebuild_driver(&mut self) {
1648            self.tick.set(self.tick.get() + 1);
1649            self.tree.layout(SizeProposal::exact(100.0, 100.0));
1650        }
1651    }
1652
1653    /// A panel with `focusable` focusable leaves, plus a sibling driver that
1654    /// calls `focus_into` on it from `build`. `outside` is focusable and lives
1655    /// outside the panel, so "focus did not move" is observable.
1656    fn probe(focusable: usize) -> (Probe, WidgetId) {
1657        let leaves = Signal::new(Vec::new());
1658        let panel_id = Signal::new(None);
1659        let tick = Signal::new(0_u64);
1660        let moved = Signal::new(false);
1661
1662        let mut tree = WidgetTree::new();
1663        let outside = tree.add(Leaf { focusable: true });
1664        let panel = tree.add(Panel {
1665            focusable,
1666            leaves: leaves.clone(),
1667        });
1668        panel_id.set(Some(panel));
1669        tree.add(Driver {
1670            panel: panel_id,
1671            tick: tick.clone(),
1672            moved: moved.clone(),
1673        });
1674        tree.layout(SizeProposal::exact(100.0, 100.0));
1675        (
1676            Probe {
1677                tree,
1678                leaves: leaves.get(),
1679                tick,
1680                moved,
1681            },
1682            outside,
1683        )
1684    }
1685
1686    /// It lands on the first focusable descendant, not on the container.
1687    #[test]
1688    fn focus_into_lands_on_the_first_focusable_descendant() {
1689        let (p, _) = probe(2);
1690        assert!(p.moved.get());
1691        assert_eq!(p.tree.focused(), Some(p.leaves[0]));
1692    }
1693
1694    /// **It is a no-op while focus is already inside** — the property that lets
1695    /// it be called from `build`, which re-runs on every rebuild. A bare
1696    /// `focus` on the first focusable descendant would drag focus back to the
1697    /// first field every time the caller rebuilt for an unrelated reason, which
1698    /// mid-edit is the caret jumping to the start of the line.
1699    #[test]
1700    fn focus_into_leaves_focus_alone_when_it_is_already_inside() {
1701        let (mut p, _) = probe(2);
1702        p.tree.focus(p.leaves[1]);
1703        p.rebuild_driver();
1704        assert!(p.moved.get(), "focus is inside, so the answer is still yes");
1705        assert_eq!(
1706            p.tree.focused(),
1707            Some(p.leaves[1]),
1708            "focus was dragged back to the first focusable child"
1709        );
1710    }
1711
1712    /// A subtree with nothing focusable leaves focus exactly where it was: an
1713    /// empty region never traps it, and the caller is told so.
1714    #[test]
1715    fn focus_into_an_unfocusable_subtree_moves_nothing() {
1716        let (mut p, outside) = probe(0);
1717        p.tree.focus(outside);
1718        p.rebuild_driver();
1719        assert!(!p.moved.get());
1720        assert_eq!(p.tree.focused(), Some(outside));
1721    }
1722}