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