Skip to main content

euv_core/scene/tree/
impl.rs

1use super::*;
2
3/// Default scene tree with a pre-created root `View` node.
4impl Default for SceneTree {
5    /// Allocates a new `SceneTree` containing a root container node.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Initialized scene tree.
10    fn default() -> Self {
11        let root_style: Style = Style::default()
12            .column()
13            .width(Length::Percent(100.0))
14            .height(Length::Percent(100.0));
15        let root_node: SceneNode = SceneNode::new(1, NodeKind::View, root_style);
16        Self {
17            nodes: vec![root_node],
18            free_list: Vec::new(),
19            root: NodeId::new(0, 1),
20            focus: FocusManager::default(),
21            revision: 1,
22            transitions: Vec::new(),
23            caret_visible: true,
24        }
25    }
26}
27
28/// Core retained scene graph mutation and traversal operations.
29impl SceneTree {
30    /// Allocates a new node of `kind` with initial `style`.
31    ///
32    /// # Arguments
33    ///
34    /// - `&Self` - Mutable scene tree.
35    /// - `NodeKind` - Semantic node kind.
36    /// - `Style` - Initial style.
37    ///
38    /// # Returns
39    ///
40    /// - `NodeId` - Generation-checked node handle.
41    pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
42        let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
43            let slot: &mut SceneNode = &mut self.get_mut_nodes()[index as usize];
44            let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
45            *slot = SceneNode::new(next_gen, kind, style);
46            NodeId::new(index, next_gen)
47        } else {
48            let index: u32 = self.get_nodes().len() as u32;
49            self.get_mut_nodes().push(SceneNode::new(1, kind, style));
50            NodeId::new(index, 1)
51        };
52        let next_rev: u64 = self.get_revision().wrapping_add(1);
53        self.set_revision(next_rev);
54        id
55    }
56
57    /// Creates a container `View` node.
58    ///
59    /// # Arguments
60    ///
61    /// - `&Self` - Mutable scene tree.
62    /// - `Style` - Initial box style.
63    ///
64    /// # Returns
65    ///
66    /// - `NodeId` - Created node handle.
67    pub fn create_view(&mut self, style: Style) -> NodeId {
68        self.create_node(NodeKind::View, style)
69    }
70
71    /// Creates a `Text` node holding `content`.
72    ///
73    /// # Arguments
74    ///
75    /// - `&Self` - Mutable scene tree.
76    /// - `String` - Initial UTF-8 text.
77    /// - `Style` - Initial text and box style.
78    ///
79    /// # Returns
80    ///
81    /// - `NodeId` - Created text node handle.
82    pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
83        self.create_node(NodeKind::Text(content), style)
84    }
85
86    /// Creates an editable `Input` node.
87    ///
88    /// # Arguments
89    ///
90    /// - `&Self` - Mutable scene tree.
91    /// - `InputNodeState` - Initial input state.
92    /// - `Style` - Initial input style.
93    ///
94    /// # Returns
95    ///
96    /// - `NodeId` - Created input node handle.
97    pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
98        self.create_node(NodeKind::Input(state), style)
99    }
100
101    /// Creates an `Image` node displaying `buffer`.
102    ///
103    /// # Arguments
104    ///
105    /// - `&Self` - Mutable scene tree.
106    /// - `ImageBuffer` - Decoded RGBA8 image buffer.
107    /// - `Style` - Initial image style.
108    ///
109    /// # Returns
110    ///
111    /// - `NodeId` - Created image node handle.
112    pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
113        self.create_node(NodeKind::Image(buffer), style)
114    }
115
116    /// Creates a `ScrollView` container with `Overflow::Scroll`.
117    ///
118    /// # Arguments
119    ///
120    /// - `&Self` - Mutable scene tree.
121    /// - `Style` - Initial scroll container style.
122    ///
123    /// # Returns
124    ///
125    /// - `NodeId` - Created scroll view handle.
126    pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
127        self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
128    }
129
130    /// Creates a custom `Canvas` node bound to `painter`.
131    ///
132    /// # Arguments
133    ///
134    /// - `&Self` - Mutable scene tree.
135    /// - `Style` - Initial canvas style.
136    /// - `CanvasDrawCallback` - Draw callback invoked on each paint pass.
137    ///
138    /// # Returns
139    ///
140    /// - `NodeId` - Created canvas node handle.
141    pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
142        let id: NodeId = self.create_node(NodeKind::Canvas, style);
143        if let Some(node) = self.get_node_mut(id) {
144            node.set_canvas_painter(Some(painter));
145        }
146        id
147    }
148
149    /// Creates an overlay `Portal` node rendered in the top stacking context.
150    ///
151    /// # Arguments
152    ///
153    /// - `&Self` - Mutable scene tree.
154    /// - `Style` - Initial portal style.
155    ///
156    /// # Returns
157    ///
158    /// - `NodeId` - Created portal node handle.
159    pub fn create_portal(&mut self, style: Style) -> NodeId {
160        self.create_node(NodeKind::Portal, style)
161    }
162
163    /// Creates a logical `Fragment` grouping node.
164    ///
165    /// # Arguments
166    ///
167    /// - `&Self` - Mutable scene tree.
168    ///
169    /// # Returns
170    ///
171    /// - `NodeId` - Created fragment node handle.
172    pub fn create_fragment(&mut self) -> NodeId {
173        self.create_node(NodeKind::Fragment, Style::default())
174    }
175
176    /// Returns an immutable reference to a live node matching `id`.
177    ///
178    /// # Arguments
179    ///
180    /// - `&Self` - Scene tree reference.
181    /// - `NodeId` - Node handle.
182    ///
183    /// # Returns
184    ///
185    /// - `Option<&SceneNode>` - Live node reference if valid.
186    #[must_use]
187    pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
188        let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
189        if node.get_alive() && node.get_generation() == id.get_generation() {
190            Some(node)
191        } else {
192            None
193        }
194    }
195
196    /// Returns a mutable reference to a live node matching `id`.
197    ///
198    /// # Arguments
199    ///
200    /// - `&Self` - Mutable scene tree.
201    /// - `NodeId` - Node handle.
202    ///
203    /// # Returns
204    ///
205    /// - `Option<&mut SceneNode>` - Mutable live node reference if valid.
206    pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
207        let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
208        if node.get_alive() && node.get_generation() == id.get_generation() {
209            Some(node)
210        } else {
211            None
212        }
213    }
214
215    /// Returns total count of live scene nodes.
216    ///
217    /// # Arguments
218    ///
219    /// - `&Self` - Scene tree reference.
220    ///
221    /// # Returns
222    ///
223    /// - `usize` - Number of live nodes in the arena.
224    #[must_use]
225    pub fn live_node_count(&self) -> usize {
226        self.get_nodes()
227            .iter()
228            .filter(|node: &&SceneNode| node.get_alive())
229            .count()
230    }
231
232    /// Appends `child` to `parent` and marks layout and paint dirty upward.
233    ///
234    /// # Arguments
235    ///
236    /// - `&Self` - Mutable scene tree.
237    /// - `NodeId` - Parent container node.
238    /// - `NodeId` - Child node to attach.
239    pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
240        if parent == child {
241            return;
242        }
243        let prev_parent: Option<NodeId> = self.get_node(child).and_then(SceneNode::parent_id);
244        if let Some(old_parent) = prev_parent
245            && let Some(old_node) = self.get_node_mut(old_parent)
246        {
247            old_node
248                .get_mut_children()
249                .retain(|item: &NodeId| *item != child);
250            if old_parent != parent {
251                self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
252            }
253        }
254        if let Some(child_node) = self.get_node_mut(child) {
255            child_node.set_parent(Some(parent));
256        } else {
257            return;
258        }
259        if let Some(parent_node) = self.get_node_mut(parent) {
260            parent_node.get_mut_children().push(child);
261        }
262        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
263    }
264
265    /// Appends multiple `children` to `parent` in a single dirty-marking pass with pre-reserved capacity.
266    ///
267    /// # Arguments
268    ///
269    /// - `&Self` - Mutable scene tree.
270    /// - `NodeId` - Parent container node.
271    /// - `&[NodeId]` - Ordered child nodes to append.
272    pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
273        if children.is_empty() || self.get_node(parent).is_none() {
274            return;
275        }
276        let mut attached: Vec<NodeId> = Vec::with_capacity(children.len());
277        for child in children.iter().copied() {
278            if child == parent {
279                continue;
280            }
281            let prev_parent: Option<NodeId> = self
282                .get_node(child)
283                .and_then(|node: &SceneNode| node.parent_id());
284            if let Some(old_parent) = prev_parent {
285                if let Some(old_node) = self.get_node_mut(old_parent) {
286                    old_node
287                        .get_mut_children()
288                        .retain(|id: &NodeId| *id != child);
289                }
290                if old_parent != parent {
291                    self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
292                }
293            }
294            if let Some(child_node) = self.get_node_mut(child) {
295                child_node.set_parent(Some(parent));
296                attached.push(child);
297            }
298        }
299        if attached.is_empty() {
300            return;
301        }
302        if let Some(parent_node) = self.get_node_mut(parent) {
303            parent_node.get_mut_children().extend(attached);
304        }
305        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
306    }
307
308    /// Replaces all children of `parent` with `new_children`, disposing previous subtrees cleanly.
309    ///
310    /// # Arguments
311    ///
312    /// - `&Self` - Mutable scene tree.
313    /// - `NodeId` - Parent container node.
314    /// - `Vec<NodeId>` - Replacement ordered children.
315    pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
316        let old_children: Vec<NodeId> = match self.get_node_mut(parent) {
317            Some(node) => take(node.get_mut_children()),
318            None => return,
319        };
320        for old_child in old_children.into_iter() {
321            if !new_children.contains(&old_child) {
322                self.dispose_subtree(old_child);
323            }
324        }
325        for child in new_children.iter().copied() {
326            if let Some(child_node) = self.get_node_mut(child) {
327                child_node.set_parent(Some(parent));
328            }
329        }
330        if let Some(parent_node) = self.get_node_mut(parent) {
331            parent_node.set_children(new_children);
332        }
333        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
334    }
335
336    /// Surgically updates a node's `Style`, only marking layout dirty when `LayoutStyle` changed.
337    ///
338    /// # Arguments
339    ///
340    /// - `&Self` - Mutable scene tree.
341    /// - `NodeId` - Target node handle.
342    /// - `Style` - Replacement compiled style.
343    pub fn set_style(&mut self, id: NodeId, style: Style) {
344        let dirty_mask: u16 = match self.get_node_mut(id) {
345            Some(node) => {
346                let prev: Style = node.get_style();
347                if prev == style {
348                    return;
349                }
350                let mut mask: u16 = DIRTY_PAINT;
351                if prev.get_layout() != style.get_layout() || prev.get_text() != style.get_text() {
352                    mask |= DIRTY_LAYOUT | DIRTY_TEXT;
353                }
354                node.set_style(style);
355                mask
356            }
357            None => return,
358        };
359        self.mark_dirty(id, dirty_mask);
360    }
361
362    /// Surgically updates the UTF-8 string of a `NodeKind::Text` node.
363    ///
364    /// # Arguments
365    ///
366    /// - `&Self` - Mutable scene tree.
367    /// - `NodeId` - Target text node handle.
368    /// - `String` - Replacement text string.
369    pub fn set_text(&mut self, id: NodeId, text: String) {
370        let changed: bool = match self.get_node_mut(id) {
371            Some(node) => match node.get_mut_kind() {
372                NodeKind::Text(current) => {
373                    if *current == text {
374                        false
375                    } else {
376                        *current = text;
377                        true
378                    }
379                }
380                _ => false,
381            },
382            None => false,
383        };
384        if changed {
385            self.mark_dirty(id, DIRTY_TEXT_CHANGE_MASK);
386        }
387    }
388
389    /// Updates scroll offset on a scroll container without triggering full subtree re-layout.
390    ///
391    /// # Arguments
392    ///
393    /// - `&Self` - Mutable scene tree.
394    /// - `NodeId` - Target scroll container handle.
395    /// - `Point` - New scroll offset clamped to content bounds.
396    pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
397        let changed: bool = match self.get_node_mut(id) {
398            Some(node) => {
399                let layout_box: LayoutBox = node.get_layout_box();
400                let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
401                    && layout_box.get_content_size().get_height() <= 0.0
402                    && layout_box.get_content_bounds().get_width() <= 0.0
403                    && layout_box.get_content_bounds().get_height() <= 0.0;
404                let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
405                    Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
406                } else {
407                    let max_x: f32 = (layout_box.get_content_size().get_width()
408                        - layout_box.get_content_bounds().get_width())
409                    .max(0.0);
410                    let max_y: f32 = (layout_box.get_content_size().get_height()
411                        - layout_box.get_content_bounds().get_height())
412                    .max(0.0);
413                    Point::new(
414                        offset.get_x().clamp(0.0, max_x),
415                        offset.get_y().clamp(0.0, max_y),
416                    )
417                };
418                if layout_box.get_scroll_offset() == clamped {
419                    false
420                } else {
421                    node.get_mut_layout_box().set_scroll_offset(clamped);
422                    true
423                }
424            }
425            None => false,
426        };
427        if changed {
428            self.mark_dirty(id, DIRTY_SCROLL | DIRTY_PAINT);
429        }
430    }
431
432    /// Records virtualized scroll progress `(scroll_y, content_height)` on `id` for overlay scrollbar rendering.
433    ///
434    /// # Arguments
435    ///
436    /// - `&Self` - Mutable scene tree.
437    /// - `NodeId` - Target virtualized scroll container.
438    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
439    /// - `f32` - Full virtualized content height in logical pixels.
440    pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
441        let changed: bool = match self.get_node_mut(id) {
442            Some(node) => {
443                let next: Option<(f32, f32)> = Some((scroll_y.max(0.0), content_height.max(1.0)));
444                if node.virtual_scroll_metrics() == next {
445                    false
446                } else {
447                    node.set_virtual_scroll(next);
448                    true
449                }
450            }
451            None => false,
452        };
453        if changed {
454            self.mark_dirty(id, DIRTY_SCROLL | DIRTY_PAINT);
455        }
456    }
457
458    /// Computes screen-space logical bounds for `id` after subtracting ancestor scroll offsets.
459    ///
460    /// # Arguments
461    ///
462    /// - `&Self` - Scene tree reference.
463    /// - `NodeId` - Target node handle.
464    ///
465    /// # Returns
466    ///
467    /// - `Option<Rect>` - Screen-space rectangle if the node is alive.
468    #[must_use]
469    pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
470        let node: &SceneNode = self.get_node(id)?;
471        let raw: Rect = node.get_layout_box().get_bounds();
472        let off: Point = self.ancestor_scroll_offset(id);
473        Some(Rect::new(
474            raw.get_x() - off.get_x(),
475            raw.get_y() - off.get_y(),
476            raw.get_width(),
477            raw.get_height(),
478        ))
479    }
480
481    /// Starts or smoothly retargets a paint/transform transition on `transition.get_node()`.
482    ///
483    /// # Arguments
484    ///
485    /// - `&Self` - Mutable scene tree.
486    /// - `NodeTransition` - Transition specification to run.
487    pub fn start_transition(&mut self, mut transition: NodeTransition) {
488        let target: NodeId = transition.get_node();
489        let had_active: bool = self
490            .get_transitions()
491            .iter()
492            .any(|tr: &NodeTransition| tr.get_node() == target);
493        self.get_mut_transitions()
494            .retain(|tr: &NodeTransition| tr.get_node() != target);
495        if had_active && let Some(node) = self.get_node(target) {
496            let paint: PaintStyle = node.get_style().get_paint();
497            let tr: Transform2D = paint.get_transform();
498            let cur_op: f32 = paint.get_opacity();
499            let cur_tx: f32 = tr.get_translate_x();
500            let cur_ty: f32 = tr.get_translate_y();
501            let cur_sc: f32 = tr.get_scale_x();
502            let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
503                .hypot(transition.get_to_ty() - transition.get_from_ty())
504                .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
505            let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
506                .hypot(transition.get_to_ty() - cur_ty)
507                .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
508            if full_dist > 0.01 {
509                let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
510                transition.set_duration((transition.get_duration() * ratio).max(0.05));
511            }
512            transition.set_from_opacity(cur_op);
513            transition.set_from_tx(cur_tx);
514            transition.set_from_ty(cur_ty);
515            transition.set_from_scale(cur_sc);
516        }
517        let (opacity, transform): (f32, Transform2D) = transition.sample();
518        let mut unhidden: bool = false;
519        if let Some(node) = self.get_node_mut(target) {
520            let mut style: Style = node.get_style();
521            if !transition.get_hide_on_complete()
522                && style.get_layout().get_display() == Display::None
523            {
524                style.get_mut_layout().set_display(Display::Flex);
525                unhidden = true;
526            }
527            style.get_mut_paint().set_opacity(opacity);
528            style.get_mut_paint().set_transform(transform);
529            node.set_style(style);
530        }
531        if unhidden {
532            self.mark_dirty(target, DIRTY_LAYOUT | DIRTY_PAINT);
533        } else {
534            self.mark_dirty(target, DIRTY_PAINT);
535        }
536        self.get_mut_transitions().push(transition);
537    }
538
539    /// Advances all active transitions by `dt_secs` and returns `true` if any node updated.
540    ///
541    /// # Arguments
542    ///
543    /// - `&Self` - Mutable scene tree.
544    /// - `f32` - Elapsed frame time in seconds.
545    ///
546    /// # Returns
547    ///
548    /// - `bool` - Whether at least one transition ticked on this frame.
549    pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
550        if self.get_transitions().is_empty() {
551            return false;
552        }
553        let step: f32 = dt_secs.clamp(0.001, 0.05);
554        let mut active: Vec<NodeTransition> = take(self.get_mut_transitions());
555        let mut remaining: Vec<NodeTransition> = Vec::with_capacity(active.len());
556        let mut any_updated: bool = false;
557        for mut tr in active.drain(..) {
558            let target: NodeId = tr.get_node();
559            if self.get_node(target).is_none() {
560                continue;
561            }
562            let total_span: f32 = tr.get_delay() + tr.get_duration();
563            let prev_elapsed: f32 = tr.get_elapsed();
564            let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
565            tr.set_elapsed(next_elapsed);
566            let done: bool = tr.is_complete();
567            let in_hold: bool = prev_elapsed > 0.0 && next_elapsed <= tr.get_delay() && !done;
568            if !in_hold {
569                let (opacity, transform): (f32, Transform2D) = tr.sample();
570                let hide: bool = done && tr.get_hide_on_complete();
571                if let Some(node) = self.get_node_mut(target) {
572                    let mut style: Style = node.get_style();
573                    style.get_mut_paint().set_opacity(opacity);
574                    style.get_mut_paint().set_transform(transform);
575                    if hide {
576                        style.get_mut_layout().set_display(Display::None);
577                    }
578                    node.set_style(style);
579                }
580                if hide {
581                    self.mark_dirty(target, DIRTY_LAYOUT | DIRTY_PAINT);
582                } else {
583                    self.mark_dirty(target, DIRTY_PAINT);
584                }
585                any_updated = true;
586            }
587            if !done {
588                remaining.push(tr);
589            }
590        }
591        self.set_transitions(remaining);
592        any_updated
593    }
594
595    /// Returns `true` while one or more node transitions are still running.
596    ///
597    /// # Arguments
598    ///
599    /// - `&Self` - Scene tree reference.
600    ///
601    /// # Returns
602    ///
603    /// - `bool` - Whether animations are active.
604    #[must_use]
605    pub fn has_active_transitions(&self) -> bool {
606        !self.get_transitions().is_empty()
607    }
608
609    /// Attaches a `Lifecycle` hook observer onto `id` for mount, activate, freeze, resume, unmount, and destroy dispatch.
610    ///
611    /// # Arguments
612    ///
613    /// - `&Self` - Mutable scene tree.
614    /// - `NodeId` - Target scene node handle.
615    /// - `Rc<dyn Lifecycle>` - Shared lifecycle hook observer.
616    pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
617        if let Some(node) = self.get_node_mut(id) {
618            node.add_lifecycle(hook);
619        }
620    }
621
622    /// Collects all `(NodeId, Rc<dyn Lifecycle>)` observers in the subtree rooted at `root`.
623    ///
624    /// # Arguments
625    ///
626    /// - `&Self` - Scene tree reference.
627    /// - `NodeId` - Subtree root handle.
628    ///
629    /// # Returns
630    ///
631    /// - `Vec<(NodeId, Rc<dyn Lifecycle>)>` - Ordered observers in pre-order traversal.
632    #[must_use]
633    pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
634        let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
635        let mut stack: Vec<NodeId> = vec![root];
636        while let Some(current) = stack.pop() {
637            if let Some(node) = self.get_node(current) {
638                for hook in node.lifecycle_observers().into_iter() {
639                    out.push((current, hook));
640                }
641                for child in node.get_children().iter().rev().copied() {
642                    stack.push(child);
643                }
644            }
645        }
646        out
647    }
648
649    /// Cancels any active paint/transform transitions targeting nodes within the subtree rooted at `root`.
650    ///
651    /// # Arguments
652    ///
653    /// - `&Self` - Mutable scene tree.
654    /// - `NodeId` - Subtree root handle.
655    pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
656        if self.get_transitions().is_empty() {
657            return;
658        }
659        let mut ids: HashSet<NodeId> = HashSet::new();
660        let mut stack: Vec<NodeId> = vec![root];
661        while let Some(current) = stack.pop() {
662            if ids.insert(current)
663                && let Some(node) = self.get_node(current)
664            {
665                for child in node.get_children().iter().copied() {
666                    stack.push(child);
667                }
668            }
669        }
670        self.get_mut_transitions()
671            .retain(|tr: &NodeTransition| !ids.contains(&tr.get_node()));
672    }
673
674    /// Attaches a reactive `Scope` to `id` so it automatically disposes when the node unmounts.
675    ///
676    /// # Arguments
677    ///
678    /// - `&Self` - Mutable scene tree.
679    /// - `NodeId` - Target node handle.
680    /// - `Scope` - Reactive ownership scope.
681    pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
682        if let Some(node) = self.get_node_mut(id) {
683            if let Some(existing) = node.owned_scope() {
684                existing.enter(|| {
685                    on_cleanup(move || {
686                        scope.dispose();
687                    });
688                });
689            } else {
690                node.set_scope(Some(scope));
691            }
692        }
693    }
694
695    /// Marks `id` dirty with `mask` and propagates subtree dirty bits to ancestors in O(depth).
696    ///
697    /// # Arguments
698    ///
699    /// - `&Self` - Mutable scene tree.
700    /// - `NodeId` - Mutated node handle.
701    /// - `u16` - Dirty flag bits to set.
702    pub fn mark_dirty(&mut self, id: NodeId, mask: u16) {
703        let mut parent_opt: Option<NodeId> = match self.get_node_mut(id) {
704            Some(node) => {
705                node.get_mut_dirty().insert(mask);
706                node.parent_id()
707            }
708            None => return,
709        };
710        let mut ancestor_mask: u16 = DIRTY_NONE;
711        if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
712            ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
713        }
714        if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
715            ancestor_mask |= DIRTY_SUBTREE_PAINT;
716        }
717        while let Some(ancestor_id) = parent_opt {
718            if let Some(ancestor) = self.get_node_mut(ancestor_id) {
719                let already: bool =
720                    (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
721                ancestor.get_mut_dirty().insert(ancestor_mask);
722                if already {
723                    break;
724                }
725                parent_opt = ancestor.parent_id();
726            } else {
727                break;
728            }
729        }
730        let next_rev: u64 = self.get_revision().wrapping_add(1);
731        self.set_revision(next_rev);
732    }
733
734    /// Computes accumulated ancestor scroll offset for `id` (zero for top-layer `Portal`/`Fixed` nodes).
735    ///
736    /// # Arguments
737    ///
738    /// - `&Self` - Scene tree reference.
739    /// - `NodeId` - Target node handle.
740    ///
741    /// # Returns
742    ///
743    /// - `Point` - Total scroll offset applied to `id`.
744    fn ancestor_scroll_offset(&self, id: NodeId) -> Point {
745        let Some(start) = self.get_node(id) else {
746            return Point::default();
747        };
748        if matches!(start.get_kind(), NodeKind::Portal)
749            || start.get_style().get_layout().get_position() == Position::Fixed
750        {
751            return Point::default();
752        }
753        let mut sx: f32 = 0.0;
754        let mut sy: f32 = 0.0;
755        let mut cursor: Option<NodeId> = start.parent_id();
756        while let Some(pid) = cursor {
757            if let Some(pnode) = self.get_node(pid) {
758                let off: Point = pnode.get_layout_box().get_scroll_offset();
759                sx += off.get_x();
760                sy += off.get_y();
761                if matches!(pnode.get_kind(), NodeKind::Portal)
762                    || pnode.get_style().get_layout().get_position() == Position::Fixed
763                {
764                    break;
765                }
766                cursor = pnode.parent_id();
767            } else {
768                break;
769            }
770        }
771        Point::new(sx, sy)
772    }
773
774    /// Returns `true` when `id` and every ancestor up to the root are alive, non-`Display::None`, and have positive opacity.
775    ///
776    /// # Arguments
777    ///
778    /// - `&Self` - Scene tree reference.
779    /// - `NodeId` - Target node handle.
780    ///
781    /// # Returns
782    ///
783    /// - `bool` - Whether the node is visibly rendered in the scene.
784    #[must_use]
785    pub fn is_node_visible(&self, id: NodeId) -> bool {
786        let mut cursor: Option<NodeId> = Some(id);
787        while let Some(cur) = cursor {
788            let Some(node) = self.get_node(cur) else {
789                return false;
790            };
791            if node.get_style().get_layout().get_display() == Display::None
792                || node.get_style().get_paint().get_opacity() <= 0.0
793            {
794                return false;
795            }
796            cursor = node.parent_id();
797        }
798        true
799    }
800
801    /// Collects the tight physical damage region from dirty paint/scroll nodes and clears paint dirty flags.
802    ///
803    /// # Arguments
804    ///
805    /// - `&Self` - Mutable scene tree.
806    /// - `f32` - Active display scale factor.
807    ///
808    /// # Returns
809    ///
810    /// - `DamageRegion` - Minimal damaged region, full damage on structural/layout change, or clean when idle.
811    pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
812        let mut full: bool = false;
813        let mut dirty_ids: Vec<(NodeId, Rect, f32)> = Vec::new();
814        for (idx, node) in self.get_nodes().iter().enumerate() {
815            if !node.get_alive() {
816                continue;
817            }
818            let bits: u16 = node.get_dirty().get_bits();
819            if (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
820                full = true;
821                break;
822            }
823            if (bits & (DIRTY_PAINT | DIRTY_SCROLL)) != 0 {
824                let b: Rect = node.get_layout_box().get_bounds();
825                if b.get_width() > 0.0 && b.get_height() > 0.0 {
826                    let mut margin: f32 = 10.0;
827                    if let Some(shadow) = node.get_style().get_paint().box_shadow() {
828                        margin = margin.max(
829                            shadow.get_blur_radius()
830                                + shadow.get_spread_radius()
831                                + shadow.get_offset_x().abs().max(shadow.get_offset_y().abs())
832                                + 4.0,
833                        );
834                    }
835                    let nid: NodeId = NodeId::new(idx as u32, node.get_generation());
836                    dirty_ids.push((nid, b, margin));
837                } else if (bits & DIRTY_PAINT) != 0 {
838                    full = true;
839                    break;
840                }
841            }
842        }
843        let mut damage: DamageRegion = if full {
844            DamageRegion::full()
845        } else {
846            let mut region: DamageRegion = DamageRegion::default();
847            for (nid, raw_bounds, margin) in dirty_ids.into_iter() {
848                let off: Point = self.ancestor_scroll_offset(nid);
849                let phys: Rect = Rect::new(
850                    ((raw_bounds.get_x() - off.get_x() - margin) * scale).floor(),
851                    ((raw_bounds.get_y() - off.get_y() - margin) * scale).floor(),
852                    ((raw_bounds.get_width() + margin * 2.0) * scale).ceil(),
853                    ((raw_bounds.get_height() + margin * 2.0) * scale).ceil(),
854                );
855                region.add_rect(phys);
856            }
857            region
858        };
859        let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
860        for node in self.get_mut_nodes().iter_mut() {
861            if node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0 {
862                node.get_mut_dirty().remove(clear_mask);
863            }
864        }
865        if full {
866            damage.set_full_damage(true);
867        }
868        damage
869    }
870
871    /// Recursively detaches and recycles `id`, returning all owned `Scope`s and `Lifecycle` observers for borrow-safe finalization.
872    ///
873    /// # Arguments
874    ///
875    /// - `&Self` - Mutable scene tree.
876    /// - `NodeId` - Subtree root handle to dispose.
877    ///
878    /// # Returns
879    ///
880    /// - `DisposedSubtreePayload` - Collected scopes and lifecycle observers to finalize outside any borrow.
881    pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
882        if id == self.get_root() {
883            return (Vec::new(), Vec::new());
884        }
885        self.cancel_subtree_transitions(id);
886        let mut stack: Vec<NodeId> = vec![id];
887        let mut scopes: Vec<Scope> = Vec::new();
888        let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
889        while let Some(current) = stack.pop() {
890            let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(current) {
891                Some(node) => {
892                    node.set_alive(false);
893                    if let Some(scope) = node.owned_scope() {
894                        scopes.push(scope);
895                    }
896                    for hook in node.take_lifecycles().into_iter() {
897                        observers.push((current, hook));
898                    }
899                    node.set_scope(None);
900                    node.set_parent(None);
901                    node.set_canvas_painter(None);
902                    node.set_handlers(EventHandlers::default());
903                    let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
904                    node.set_generation(next_gen);
905                    Some(take(node.get_mut_children()))
906                }
907                None => None,
908            };
909            let Some(children) = children_opt else {
910                continue;
911            };
912            self.get_mut_free_list().push(current.get_index());
913            for child in children.into_iter() {
914                stack.push(child);
915            }
916        }
917        (scopes, observers)
918    }
919
920    /// Recursively removes and disposes `id`, recycling all arena slots, running lifecycle hooks, and disposing scopes.
921    ///
922    /// # Arguments
923    ///
924    /// - `&Self` - Mutable scene tree.
925    /// - `NodeId` - Subtree root handle to dispose.
926    pub fn dispose_subtree(&mut self, id: NodeId) {
927        let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
928        finalize_disposed_subtree(scopes, observers);
929    }
930
931    /// Updates keyboard focus to `target`, emitting `Blur` and `Focus` events.
932    ///
933    /// # Arguments
934    ///
935    /// - `&Self` - Mutable scene tree.
936    /// - `Option<NodeId>` - Newly focused node, or `None` to clear focus.
937    ///
938    /// # Returns
939    ///
940    /// - `Vec<(UiEventHandler, UiEvent)>` - Callbacks to invoke outside the tree borrow.
941    pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
942        let prev: Option<NodeId> = self.get_focus().focused_node();
943        if prev == target {
944            return Vec::new();
945        }
946        let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
947        if let Some(old_id) = prev {
948            if let Some(old_node) = self.get_node_mut(old_id) {
949                old_node.get_mut_interaction().set_focused(false);
950                if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
951                    callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
952                }
953            }
954            self.mark_dirty(old_id, DIRTY_PAINT);
955        }
956        self.get_mut_focus().set_focused(target);
957        if let Some(new_id) = target {
958            if let Some(new_node) = self.get_node_mut(new_id) {
959                new_node.get_mut_interaction().set_focused(true);
960                if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
961                    callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
962                }
963            }
964            self.mark_dirty(new_id, DIRTY_PAINT);
965        }
966        callbacks
967    }
968}
969
970/// Shared scene handle operations enabling surgical reactive node updates.
971impl SceneHandle {
972    /// Creates a new `SceneHandle` wrapping a fresh `SceneTree`.
973    ///
974    /// # Returns
975    ///
976    /// - `Self` - Shared scene handle.
977    #[must_use]
978    pub fn new_tree() -> Self {
979        Self {
980            inner: Rc::new(RefCell::new(SceneTree::default())),
981        }
982    }
983
984    /// Updates virtualized scroll metrics `(scroll_y, content_height)` on `id` for accurate scrollbar thumbs.
985    ///
986    /// # Arguments
987    ///
988    /// - `&Self` - Scene handle reference.
989    /// - `NodeId` - Target virtualized scroll container.
990    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
991    /// - `f32` - Total virtualized content height in logical pixels.
992    pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
993        self.with_write(
994            |tree: &mut SceneTree| {
995                tree.set_virtual_scroll(id, scroll_y, content_height);
996            },
997            (),
998        );
999    }
1000
1001    /// Computes screen-space logical bounds for `id` subtracting ancestor scroll offsets.
1002    ///
1003    /// # Arguments
1004    ///
1005    /// - `&Self` - Scene handle reference.
1006    /// - `NodeId` - Target node handle.
1007    ///
1008    /// # Returns
1009    ///
1010    /// - `Option<Rect>` - Screen-space bounds if the node is alive.
1011    #[must_use]
1012    pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
1013        self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
1014    }
1015
1016    /// Starts or replaces a smooth paint/transform transition on the target node.
1017    ///
1018    /// # Arguments
1019    ///
1020    /// - `&Self` - Scene handle reference.
1021    /// - `NodeTransition` - Transition specification to run.
1022    pub fn start_transition(&self, transition: NodeTransition) {
1023        self.with_write(
1024            |tree: &mut SceneTree| {
1025                tree.start_transition(transition);
1026            },
1027            (),
1028        );
1029    }
1030
1031    /// Marks `id` dirty with `mask` for incremental repainting.
1032    ///
1033    /// # Arguments
1034    ///
1035    /// - `&Self` - Scene handle reference.
1036    /// - `NodeId` - Target node handle.
1037    /// - `u16` - Dirty flag bits.
1038    pub fn mark_dirty(&self, id: NodeId, mask: u16) {
1039        self.with_write(
1040            |tree: &mut SceneTree| {
1041                tree.mark_dirty(id, mask);
1042            },
1043            (),
1044        );
1045    }
1046
1047    /// Replaces all children of `parent` and finalizes disposed scopes and `Lifecycle` hooks outside the tree borrow.
1048    ///
1049    /// # Arguments
1050    ///
1051    /// - `&Self` - Scene handle reference.
1052    /// - `NodeId` - Parent container node.
1053    /// - `Vec<NodeId>` - Replacement ordered children.
1054    pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
1055        let (scopes, observers): DisposedSubtreePayload = self.with_write(
1056            |tree: &mut SceneTree| {
1057                let old_children: Vec<NodeId> = match tree.get_node_mut(parent) {
1058                    Some(node) => take(node.get_mut_children()),
1059                    None => return (Vec::new(), Vec::new()),
1060                };
1061                let mut all_scopes: Vec<Scope> = Vec::new();
1062                let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1063                for old_child in old_children.into_iter() {
1064                    if !new_children.contains(&old_child) {
1065                        let (sc, ob): DisposedSubtreePayload =
1066                            tree.dispose_subtree_collect(old_child);
1067                        all_scopes.extend(sc);
1068                        all_obs.extend(ob);
1069                    }
1070                }
1071                for child in new_children.iter().copied() {
1072                    if let Some(child_node) = tree.get_node_mut(child) {
1073                        child_node.set_parent(Some(parent));
1074                    }
1075                }
1076                if let Some(parent_node) = tree.get_node_mut(parent) {
1077                    parent_node.set_children(new_children);
1078                }
1079                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1080                (all_scopes, all_obs)
1081            },
1082            (Vec::new(), Vec::new()),
1083        );
1084        finalize_disposed_subtree(scopes, observers);
1085    }
1086
1087    /// Removes `child` from `parent`, disposes its subtree, and invokes `on_unmount`/`on_destroy` outside any scene borrow.
1088    ///
1089    /// # Arguments
1090    ///
1091    /// - `&Self` - Scene handle reference.
1092    /// - `NodeId` - Parent container handle.
1093    /// - `NodeId` - Child subtree root handle to remove and destroy.
1094    pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
1095        let (scopes, observers): DisposedSubtreePayload = self.with_write(
1096            |tree: &mut SceneTree| {
1097                if let Some(pnode) = tree.get_node_mut(parent) {
1098                    pnode.get_mut_children().retain(|id: &NodeId| *id != child);
1099                }
1100                let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
1101                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1102                out
1103            },
1104            (Vec::new(), Vec::new()),
1105        );
1106        finalize_disposed_subtree(scopes, observers);
1107    }
1108
1109    /// Freezes a subtree visually (`Display::None`), cancels its transitions, and dispatches `Lifecycle::on_freeze` outside any scene borrow.
1110    ///
1111    /// # Arguments
1112    ///
1113    /// - `&Self` - Scene handle reference.
1114    /// - `NodeId` - Subtree root handle to freeze.
1115    pub fn freeze_subtree(&self, root: NodeId) {
1116        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
1117            |tree: &mut SceneTree| {
1118                let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
1119                tree.cancel_subtree_transitions(root);
1120                if let Some(node) = tree.get_node_mut(root) {
1121                    let mut st: Style = node.get_style();
1122                    st.get_mut_layout().set_display(Display::None);
1123                    node.set_style(st);
1124                }
1125                tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
1126                obs
1127            },
1128            Vec::new(),
1129        );
1130        dispatch_lifecycle_freeze(&observers);
1131    }
1132
1133    /// Resumes a previously frozen subtree (`Display::Flex`) and dispatches `Lifecycle::on_resume` outside any scene borrow.
1134    ///
1135    /// # Arguments
1136    ///
1137    /// - `&Self` - Scene handle reference.
1138    /// - `NodeId` - Subtree root handle to resume.
1139    pub fn resume_subtree(&self, root: NodeId) {
1140        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
1141            |tree: &mut SceneTree| {
1142                if let Some(node) = tree.get_node_mut(root) {
1143                    let mut st: Style = node.get_style();
1144                    if st.get_layout().get_display() == Display::None {
1145                        st.get_mut_layout().set_display(Display::Flex);
1146                        node.set_style(st);
1147                    }
1148                }
1149                tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
1150                tree.collect_subtree_lifecycles(root)
1151            },
1152            Vec::new(),
1153        );
1154        dispatch_lifecycle_resume(&observers);
1155    }
1156
1157    /// Dispatches `Lifecycle::on_activate` across all observers in the subtree rooted at `root`.
1158    ///
1159    /// # Arguments
1160    ///
1161    /// - `&Self` - Scene handle reference.
1162    /// - `NodeId` - Subtree root handle becoming active.
1163    pub fn activate_subtree(&self, root: NodeId) {
1164        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
1165            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
1166            Vec::new(),
1167        );
1168        dispatch_lifecycle_activate(&observers);
1169    }
1170
1171    /// Dispatches `Lifecycle::on_update` across all observers in the subtree rooted at `root`.
1172    ///
1173    /// # Arguments
1174    ///
1175    /// - `&Self` - Scene handle reference.
1176    /// - `NodeId` - Subtree root handle receiving updates.
1177    pub fn update_subtree(&self, root: NodeId) {
1178        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
1179            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
1180            Vec::new(),
1181        );
1182        dispatch_lifecycle_update(&observers);
1183    }
1184
1185    /// Returns `true` if any node transition is currently active.
1186    ///
1187    /// # Arguments
1188    ///
1189    /// - `&Self` - Scene handle reference.
1190    ///
1191    /// # Returns
1192    ///
1193    /// - `bool` - Whether animations are running.
1194    #[must_use]
1195    pub fn has_active_transitions(&self) -> bool {
1196        self.with_read(SceneTree::has_active_transitions, false)
1197    }
1198
1199    /// Executes `operation` with immutable access to the underlying `SceneTree`.
1200    ///
1201    /// # Arguments
1202    ///
1203    /// - `&Self` - Scene handle.
1204    /// - `F` - Reader closure.
1205    /// - `R` - Fallback if re-entrantly borrowed.
1206    ///
1207    /// # Returns
1208    ///
1209    /// - `R` - Closure result or fallback.
1210    pub fn with_read<F, R>(&self, operation: F, fallback: R) -> R
1211    where
1212        F: FnOnce(&SceneTree) -> R,
1213    {
1214        let Self { inner } = self;
1215        match inner.try_borrow() {
1216            Ok(guard) => operation(&guard),
1217            Err(_) => fallback,
1218        }
1219    }
1220
1221    /// Executes `operation` with mutable access to the underlying `SceneTree`.
1222    ///
1223    /// # Arguments
1224    ///
1225    /// - `&Self` - Scene handle.
1226    /// - `F` - Mutation closure.
1227    /// - `R` - Fallback if re-entrantly borrowed.
1228    ///
1229    /// # Returns
1230    ///
1231    /// - `R` - Closure result or fallback.
1232    pub fn with_write<F, R>(&self, operation: F, fallback: R) -> R
1233    where
1234        F: FnOnce(&mut SceneTree) -> R,
1235    {
1236        let Self { inner } = self;
1237        match inner.try_borrow_mut() {
1238            Ok(mut guard) => operation(&mut guard),
1239            Err(_) => fallback,
1240        }
1241    }
1242
1243    /// Binds a reactive text expression to `node_id` via a surgical `Effect`.
1244    ///
1245    /// # Arguments
1246    ///
1247    /// - `&Self` - Scene handle.
1248    /// - `NodeId` - Target text node.
1249    /// - `F` - Reactive text producer closure.
1250    ///
1251    /// # Returns
1252    ///
1253    /// - `Effect` - Registered reactive effect.
1254    pub fn bind_text<F>(&self, node_id: NodeId, mut producer: F) -> Effect
1255    where
1256        F: FnMut() -> String + 'static,
1257    {
1258        let handle: Self = self.clone();
1259        Effect::new(move || {
1260            let value: String = producer();
1261            handle.with_write(
1262                |tree: &mut SceneTree| {
1263                    tree.set_text(node_id, value);
1264                },
1265                (),
1266            );
1267        })
1268    }
1269
1270    /// Binds a reactive `Style` expression to `node_id` via a surgical `Effect`.
1271    ///
1272    /// # Arguments
1273    ///
1274    /// - `&Self` - Scene handle.
1275    /// - `NodeId` - Target node.
1276    /// - `F` - Reactive style producer closure.
1277    ///
1278    /// # Returns
1279    ///
1280    /// - `Effect` - Registered reactive effect.
1281    pub fn bind_style<F>(&self, node_id: NodeId, mut producer: F) -> Effect
1282    where
1283        F: FnMut() -> Style + 'static,
1284    {
1285        let handle: Self = self.clone();
1286        Effect::new(move || {
1287            let style: Style = producer();
1288            handle.with_write(
1289                |tree: &mut SceneTree| {
1290                    tree.set_style(node_id, style);
1291                },
1292                (),
1293            );
1294        })
1295    }
1296}
1297
1298/// High-level declarative building helpers on `Context`.
1299impl Context {
1300    /// Creates a new `Context` with reactive viewport, theme, and safe-area signals.
1301    ///
1302    /// # Arguments
1303    ///
1304    /// - `SceneHandle` - Shared scene handle.
1305    /// - `PlatformKind` - Active platform kind.
1306    ///
1307    /// # Returns
1308    ///
1309    /// - `Self` - Constructed build context.
1310    #[must_use]
1311    pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
1312        Self {
1313            scene,
1314            breakpoint: Signal::new(Breakpoint::Expanded),
1315            viewport_size: Signal::new(Size::new(1200.0, 800.0)),
1316            theme_mode: Signal::new(ThemeMode::Light),
1317            platform,
1318            safe_area: Signal::new(SafeAreaInsets::default()),
1319            gesture: Signal::new(None),
1320            system_back: Signal::new(0),
1321            dynamic_hub: DynamicUpdateHub::new(),
1322            fps_limit: Signal::new(None),
1323            live_fps: Signal::new(60.0),
1324            active_touches: Signal::new(Vec::new()),
1325            exit_requested: Signal::new(false),
1326            clock_ms: Rc::new(Cell::new(0)),
1327        }
1328    }
1329
1330    /// Returns the monotonic runtime elapsed clock in milliseconds.
1331    ///
1332    /// # Arguments
1333    ///
1334    /// - `&Self` - Context reference.
1335    ///
1336    /// # Returns
1337    ///
1338    /// - `u64` - Elapsed runtime time in milliseconds.
1339    #[must_use]
1340    pub fn elapsed_ms(&self) -> u64 {
1341        let Self { clock_ms, .. } = self;
1342        clock_ms.get()
1343    }
1344
1345    /// Advances the context's monotonic runtime clock by `delta_ms` milliseconds.
1346    ///
1347    /// # Arguments
1348    ///
1349    /// - `&Self` - Context reference.
1350    /// - `u64` - Milliseconds elapsed since the previous frame.
1351    pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
1352        let Self { clock_ms, .. } = self;
1353        clock_ms.set(clock_ms.get().saturating_add(delta_ms));
1354    }
1355
1356    /// Requests graceful OS-level application termination across all platforms.
1357    ///
1358    /// # Arguments
1359    ///
1360    /// - `&Self` - Context reference.
1361    pub fn request_exit(&self) {
1362        let _: bool = self.get_exit_requested().set_if_changed(true);
1363        let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
1364    }
1365
1366    /// Creates a `View` node with the given style.
1367    ///
1368    /// # Arguments
1369    ///
1370    /// - `&Self` - Build context.
1371    /// - `Style` - Initial style.
1372    ///
1373    /// # Returns
1374    ///
1375    /// - `NodeId` - Created node handle.
1376    pub fn view(&mut self, style: Style) -> NodeId {
1377        self.get_scene().with_write(
1378            |tree: &mut SceneTree| tree.create_view(style),
1379            NodeId::default(),
1380        )
1381    }
1382
1383    /// Creates a `Text` node with static initial text.
1384    ///
1385    /// # Arguments
1386    ///
1387    /// - `&Self` - Build context.
1388    /// - `String` - Text content.
1389    /// - `Style` - Text style.
1390    ///
1391    /// # Returns
1392    ///
1393    /// - `NodeId` - Created node handle.
1394    pub fn text(&mut self, content: String, style: Style) -> NodeId {
1395        self.get_scene().with_write(
1396            |tree: &mut SceneTree| tree.create_text(content, style),
1397            NodeId::default(),
1398        )
1399    }
1400
1401    /// Creates a reactive `Text` node whose content updates surgically whenever tracked signals change.
1402    ///
1403    /// # Arguments
1404    ///
1405    /// - `&Self` - Build context.
1406    /// - `Style` - Text style.
1407    /// - `F` - Reactive text producer.
1408    ///
1409    /// # Returns
1410    ///
1411    /// - `NodeId` - Created reactive text node handle.
1412    pub fn reactive_text<F>(&mut self, style: Style, producer: F) -> NodeId
1413    where
1414        F: FnMut() -> String + 'static,
1415    {
1416        let node_id: NodeId = self.text(String::new(), style);
1417        let handle: SceneHandle = self.get_scene().clone();
1418        let (scope, _): (Scope, Effect) =
1419            Scope::run(|_: Scope| handle.bind_text(node_id, producer));
1420        self.get_scene().with_write(
1421            |tree: &mut SceneTree| {
1422                tree.attach_scope(node_id, scope);
1423            },
1424            (),
1425        );
1426        node_id
1427    }
1428
1429    /// Creates a `ScrollView` node with the given style.
1430    ///
1431    /// # Arguments
1432    ///
1433    /// - `&Self` - Build context.
1434    /// - `Style` - Scroll container style.
1435    ///
1436    /// # Returns
1437    ///
1438    /// - `NodeId` - Created scroll view handle.
1439    pub fn scroll_view(&mut self, style: Style) -> NodeId {
1440        self.get_scene().with_write(
1441            |tree: &mut SceneTree| tree.create_scroll_view(style),
1442            NodeId::default(),
1443        )
1444    }
1445
1446    /// Creates an `Input` node with initial state and style.
1447    ///
1448    /// # Arguments
1449    ///
1450    /// - `&Self` - Build context.
1451    /// - `InputNodeState` - Initial input state.
1452    /// - `Style` - Input style.
1453    ///
1454    /// # Returns
1455    ///
1456    /// - `NodeId` - Created input handle.
1457    pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
1458        self.get_scene().with_write(
1459            |tree: &mut SceneTree| tree.create_input(state, style),
1460            NodeId::default(),
1461        )
1462    }
1463
1464    /// Creates an `Image` node with decoded RGBA8 pixel data.
1465    ///
1466    /// # Arguments
1467    ///
1468    /// - `&Self` - Build context.
1469    /// - `ImageBuffer` - Image buffer.
1470    /// - `Style` - Image style.
1471    ///
1472    /// # Returns
1473    ///
1474    /// - `NodeId` - Created image handle.
1475    pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
1476        self.get_scene().with_write(
1477            |tree: &mut SceneTree| tree.create_image(buffer, style),
1478            NodeId::default(),
1479        )
1480    }
1481
1482    /// Creates a `Canvas` node bound to a custom draw callback.
1483    ///
1484    /// # Arguments
1485    ///
1486    /// - `&Self` - Build context.
1487    /// - `Style` - Canvas style.
1488    /// - `F` - Draw callback receiving node bounds and mutable `DisplayList`.
1489    ///
1490    /// # Returns
1491    ///
1492    /// - `NodeId` - Created canvas handle.
1493    pub fn canvas<F>(&mut self, style: Style, painter: F) -> NodeId
1494    where
1495        F: FnMut(Rect, &mut DisplayList) + 'static,
1496    {
1497        let cb: CanvasDrawCallback = Rc::new(RefCell::new(painter));
1498        self.get_scene().with_write(
1499            |tree: &mut SceneTree| tree.create_canvas(style, cb),
1500            NodeId::default(),
1501        )
1502    }
1503
1504    /// Creates an overlay `Portal` node.
1505    ///
1506    /// # Arguments
1507    ///
1508    /// - `&Self` - Build context.
1509    /// - `Style` - Portal style.
1510    ///
1511    /// # Returns
1512    ///
1513    /// - `NodeId` - Created portal handle.
1514    pub fn portal(&mut self, style: Style) -> NodeId {
1515        self.get_scene().with_write(
1516            |tree: &mut SceneTree| tree.create_portal(style),
1517            NodeId::default(),
1518        )
1519    }
1520
1521    /// Creates a transparent logical `Fragment` grouping container for sibling nodes.
1522    ///
1523    /// # Arguments
1524    ///
1525    /// - `&Self` - Build context.
1526    ///
1527    /// # Returns
1528    ///
1529    /// - `NodeId` - Created fragment handle.
1530    pub fn fragment(&mut self) -> NodeId {
1531        self.get_scene().with_write(
1532            |tree: &mut SceneTree| tree.create_fragment(),
1533            NodeId::default(),
1534        )
1535    }
1536
1537    /// Appends `child` to `parent`.
1538    ///
1539    /// # Arguments
1540    ///
1541    /// - `&Self` - Build context.
1542    /// - `NodeId` - Parent container.
1543    /// - `NodeId` - Child node.
1544    pub fn append(&mut self, parent: NodeId, child: NodeId) {
1545        self.get_scene().with_write(
1546            |tree: &mut SceneTree| {
1547                tree.append_child(parent, child);
1548            },
1549            (),
1550        );
1551    }
1552
1553    /// Appends a slice of `children` to `parent` under a single scene write lock and dirty pass.
1554    ///
1555    /// # Arguments
1556    ///
1557    /// - `&Self` - Build context.
1558    /// - `NodeId` - Parent container.
1559    /// - `&[NodeId]` - Ordered child node slice.
1560    pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
1561        if children.is_empty() {
1562            return;
1563        }
1564        self.get_scene().with_write(
1565            |tree: &mut SceneTree| {
1566                tree.append_children(parent, children);
1567            },
1568            (),
1569        );
1570    }
1571
1572    /// Binds a reactive `Style` closure to `node_id` and attaches its disposal `Scope` automatically.
1573    ///
1574    /// # Arguments
1575    ///
1576    /// - `&Self` - Build context.
1577    /// - `NodeId` - Target scene node.
1578    /// - `F` - Reactive `Style` producer closure.
1579    pub fn bind_style<F>(&mut self, node_id: NodeId, producer: F)
1580    where
1581        F: FnMut() -> Style + 'static,
1582    {
1583        let handle: SceneHandle = self.get_scene().clone();
1584        let (scope, _): (Scope, Effect) =
1585            Scope::run(|_: Scope| handle.bind_style(node_id, producer));
1586        self.get_scene().with_write(
1587            |tree: &mut SceneTree| {
1588                tree.attach_scope(node_id, scope);
1589            },
1590            (),
1591        );
1592    }
1593
1594    /// Registers a pointer-enter handler on `node_id`.
1595    ///
1596    /// # Arguments
1597    ///
1598    /// - `&Self` - Build context.
1599    /// - `NodeId` - Target node handle.
1600    /// - `F` - Pointer-enter callback closure.
1601    pub fn on_pointer_enter<F>(&mut self, node_id: NodeId, callback: F)
1602    where
1603        F: FnMut(&UiEvent) + 'static,
1604    {
1605        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1606        self.get_scene().with_write(
1607            |tree: &mut SceneTree| {
1608                if let Some(node) = tree.get_node_mut(node_id) {
1609                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
1610                }
1611            },
1612            (),
1613        );
1614    }
1615
1616    /// Registers a pointer-leave handler on `node_id`.
1617    ///
1618    /// # Arguments
1619    ///
1620    /// - `&Self` - Build context.
1621    /// - `NodeId` - Target node handle.
1622    /// - `F` - Pointer-leave callback closure.
1623    pub fn on_pointer_leave<F>(&mut self, node_id: NodeId, callback: F)
1624    where
1625        F: FnMut(&UiEvent) + 'static,
1626    {
1627        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1628        self.get_scene().with_write(
1629            |tree: &mut SceneTree| {
1630                if let Some(node) = tree.get_node_mut(node_id) {
1631                    node.get_mut_handlers().set_on_pointer_leave(Some(handler));
1632                }
1633            },
1634            (),
1635        );
1636    }
1637
1638    /// Registers a focus-gained handler on `node_id` and marks it focusable.
1639    ///
1640    /// # Arguments
1641    ///
1642    /// - `&Self` - Build context.
1643    /// - `NodeId` - Target node handle.
1644    /// - `F` - Focus callback closure receiving `UiEventKind::Focus`.
1645    pub fn on_focus<F>(&mut self, node_id: NodeId, callback: F)
1646    where
1647        F: FnMut(&UiEvent) + 'static,
1648    {
1649        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1650        self.get_scene().with_write(
1651            |tree: &mut SceneTree| {
1652                if let Some(node) = tree.get_node_mut(node_id) {
1653                    node.get_mut_handlers().set_on_focus(Some(handler));
1654                    node.get_mut_interaction().set_focusable(true);
1655                }
1656            },
1657            (),
1658        );
1659    }
1660
1661    /// Registers a focus-lost handler on `node_id`.
1662    ///
1663    /// # Arguments
1664    ///
1665    /// - `&Self` - Build context.
1666    /// - `NodeId` - Target node handle.
1667    /// - `F` - Blur callback closure receiving `UiEventKind::Blur`.
1668    pub fn on_blur<F>(&mut self, node_id: NodeId, callback: F)
1669    where
1670        F: FnMut(&UiEvent) + 'static,
1671    {
1672        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1673        self.get_scene().with_write(
1674            |tree: &mut SceneTree| {
1675                if let Some(node) = tree.get_node_mut(node_id) {
1676                    node.get_mut_handlers().set_on_blur(Some(handler));
1677                }
1678            },
1679            (),
1680        );
1681    }
1682
1683    /// Configures whether `node_id` participates in keyboard focus navigation.
1684    ///
1685    /// # Arguments
1686    ///
1687    /// - `&Self` - Build context.
1688    /// - `NodeId` - Target node handle.
1689    /// - `bool` - Whether keyboard focus is enabled.
1690    pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
1691        self.get_scene().with_write(
1692            |tree: &mut SceneTree| {
1693                if let Some(node) = tree.get_node_mut(node_id) {
1694                    node.get_mut_interaction().set_focusable(focusable);
1695                }
1696            },
1697            (),
1698        );
1699    }
1700
1701    /// Registers a click handler on `node_id` and sets pointer cursor automatically.
1702    ///
1703    /// # Arguments
1704    ///
1705    /// - `&Self` - Build context.
1706    /// - `NodeId` - Target node.
1707    /// - `F` - Click callback closure.
1708    pub fn on_click<F>(&mut self, node_id: NodeId, callback: F)
1709    where
1710        F: FnMut(&UiEvent) + 'static,
1711    {
1712        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1713        self.get_scene().with_write(
1714            |tree: &mut SceneTree| {
1715                if let Some(node) = tree.get_node_mut(node_id) {
1716                    node.get_mut_handlers().set_on_click(Some(handler));
1717                    node.get_mut_interaction().set_focusable(true);
1718                    let mut style: Style = node.get_style();
1719                    style.get_mut_paint().set_cursor(CursorIcon::Pointer);
1720                    node.set_style(style);
1721                }
1722            },
1723            (),
1724        );
1725    }
1726
1727    /// Registers a change handler on an `Input` node.
1728    ///
1729    /// # Arguments
1730    ///
1731    /// - `&Self` - Build context.
1732    /// - `NodeId` - Target input node.
1733    /// - `F` - Change callback closure.
1734    pub fn on_change<F>(&mut self, node_id: NodeId, callback: F)
1735    where
1736        F: FnMut(&UiEvent) + 'static,
1737    {
1738        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1739        self.get_scene().with_write(
1740            |tree: &mut SceneTree| {
1741                if let Some(node) = tree.get_node_mut(node_id) {
1742                    node.get_mut_handlers().set_on_change(Some(handler));
1743                }
1744            },
1745            (),
1746        );
1747    }
1748
1749    /// Attaches semantic accessibility properties to `node_id`.
1750    ///
1751    /// # Arguments
1752    ///
1753    /// - `&Self` - Build context.
1754    /// - `NodeId` - Target scene node.
1755    /// - `A11yProps` - Semantic role, label, hint, and state metadata.
1756    pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
1757        self.get_scene().with_write(
1758            |tree: &mut SceneTree| {
1759                if let Some(node) = tree.get_node_mut(node_id) {
1760                    node.set_a11y(Some(props));
1761                }
1762            },
1763            (),
1764        );
1765    }
1766
1767    /// Registers a scroll handler on a scrollable container node.
1768    ///
1769    /// # Arguments
1770    ///
1771    /// - `&Self` - Build context.
1772    /// - `NodeId` - Target scroll container node.
1773    /// - `F` - Scroll callback closure receiving `UiEventKind::Scroll(delta)`.
1774    pub fn on_scroll<F>(&mut self, node_id: NodeId, callback: F)
1775    where
1776        F: FnMut(&UiEvent) + 'static,
1777    {
1778        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1779        self.get_scene().with_write(
1780            |tree: &mut SceneTree| {
1781                if let Some(node) = tree.get_node_mut(node_id) {
1782                    node.get_mut_handlers().set_on_scroll(Some(handler));
1783                }
1784            },
1785            (),
1786        );
1787    }
1788
1789    /// Registers a pointer-down handler on `node_id` for draggable interactive controls.
1790    ///
1791    /// # Arguments
1792    ///
1793    /// - `&Self` - Build context.
1794    /// - `NodeId` - Target node handle.
1795    /// - `F` - Pointer-down callback closure.
1796    pub fn on_pointer_down<F>(&mut self, node_id: NodeId, callback: F)
1797    where
1798        F: FnMut(&UiEvent) + 'static,
1799    {
1800        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1801        self.get_scene().with_write(
1802            |tree: &mut SceneTree| {
1803                if let Some(node) = tree.get_node_mut(node_id) {
1804                    node.get_mut_handlers().set_on_pointer_down(Some(handler));
1805                    let mut style: Style = node.get_style();
1806                    style.get_mut_paint().set_cursor(CursorIcon::Pointer);
1807                    node.set_style(style);
1808                }
1809            },
1810            (),
1811        );
1812    }
1813
1814    /// Registers a pointer-move handler on `node_id` receiving captured drag coordinates while pressed.
1815    ///
1816    /// # Arguments
1817    ///
1818    /// - `&Self` - Build context.
1819    /// - `NodeId` - Target node handle.
1820    /// - `F` - Pointer-move callback closure.
1821    pub fn on_pointer_move<F>(&mut self, node_id: NodeId, callback: F)
1822    where
1823        F: FnMut(&UiEvent) + 'static,
1824    {
1825        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1826        self.get_scene().with_write(
1827            |tree: &mut SceneTree| {
1828                if let Some(node) = tree.get_node_mut(node_id) {
1829                    node.get_mut_handlers().set_on_pointer_move(Some(handler));
1830                }
1831            },
1832            (),
1833        );
1834    }
1835
1836    /// Registers a pointer-up handler on `node_id` invoked when drag capture releases.
1837    ///
1838    /// # Arguments
1839    ///
1840    /// - `&Self` - Build context.
1841    /// - `NodeId` - Target node handle.
1842    /// - `F` - Pointer-up callback closure.
1843    pub fn on_pointer_up<F>(&mut self, node_id: NodeId, callback: F)
1844    where
1845        F: FnMut(&UiEvent) + 'static,
1846    {
1847        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1848        self.get_scene().with_write(
1849            |tree: &mut SceneTree| {
1850                if let Some(node) = tree.get_node_mut(node_id) {
1851                    node.get_mut_handlers().set_on_pointer_up(Some(handler));
1852                }
1853            },
1854            (),
1855        );
1856    }
1857
1858    /// Registers a hover handler on `node_id` invoked on both `PointerEnter` and `PointerLeave`.
1859    ///
1860    /// # Arguments
1861    ///
1862    /// - `&Self` - Build context.
1863    /// - `NodeId` - Target node handle.
1864    /// - `F` - Hover callback closure receiving `UiEventKind::PointerEnter` or `PointerLeave`.
1865    pub fn on_hover<F>(&mut self, node_id: NodeId, callback: F)
1866    where
1867        F: FnMut(&UiEvent) + 'static,
1868    {
1869        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1870        let leave_handler: UiEventHandler = handler.clone();
1871        self.get_scene().with_write(
1872            |tree: &mut SceneTree| {
1873                if let Some(node) = tree.get_node_mut(node_id) {
1874                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
1875                    node.get_mut_handlers()
1876                        .set_on_pointer_leave(Some(leave_handler));
1877                }
1878            },
1879            (),
1880        );
1881    }
1882
1883    /// Registers a keyboard key-down handler on `node_id` and marks it focusable.
1884    ///
1885    /// # Arguments
1886    ///
1887    /// - `&Self` - Build context.
1888    /// - `NodeId` - Target node handle.
1889    /// - `F` - Key-down callback closure receiving `UiEventKind::KeyDown`.
1890    pub fn on_key<F>(&mut self, node_id: NodeId, callback: F)
1891    where
1892        F: FnMut(&UiEvent) + 'static,
1893    {
1894        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1895        self.get_scene().with_write(
1896            |tree: &mut SceneTree| {
1897                if let Some(node) = tree.get_node_mut(node_id) {
1898                    node.get_mut_handlers().set_on_key_down(Some(handler));
1899                    node.get_mut_interaction().set_focusable(true);
1900                }
1901            },
1902            (),
1903        );
1904    }
1905
1906    /// Records virtualized scroll progress on `node_id` so the overlay scrollbar tracks accurately.
1907    ///
1908    /// # Arguments
1909    ///
1910    /// - `&Self` - Build context.
1911    /// - `NodeId` - Target virtualized scroll container.
1912    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
1913    /// - `f32` - Full virtualized content height in logical pixels.
1914    pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
1915        self.get_scene()
1916            .set_virtual_scroll(node_id, scroll_y, content_height);
1917    }
1918
1919    /// Sets the concrete inner pixel scroll offset on `node_id` (used by virtualized lists for sub-pixel alignment).
1920    ///
1921    /// # Arguments
1922    ///
1923    /// - `&Self` - Build context.
1924    /// - `NodeId` - Target scroll container.
1925    /// - `Point` - Scroll offset `(x, y)` in logical pixels.
1926    pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
1927        self.get_scene().with_write(
1928            |tree: &mut SceneTree| {
1929                tree.set_scroll_offset(node_id, offset);
1930            },
1931            (),
1932        );
1933    }
1934
1935    /// Starts a smooth paint/transform transition on `transition.get_node()`.
1936    ///
1937    /// # Arguments
1938    ///
1939    /// - `&Self` - Build context.
1940    /// - `NodeTransition` - Transition specification.
1941    pub fn start_transition(&mut self, transition: NodeTransition) {
1942        self.get_scene().start_transition(transition);
1943    }
1944
1945    /// Mounts a reactive dynamic subtree whose children rebuild cleanly inside an isolated `Scope`.
1946    ///
1947    /// # Arguments
1948    ///
1949    /// - `&Self` - Build context.
1950    /// - `NodeId` - Host container node.
1951    /// - `F` - Reactive zero-`ctx` builder returning child `NodeId` values.
1952    pub fn bind_children<F>(&mut self, host: NodeId, mut builder: F)
1953    where
1954        F: FnMut() -> Vec<NodeId> + 'static,
1955    {
1956        let ctx_clone: Self = self.clone();
1957        let handle: SceneHandle = self.get_scene().clone();
1958        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1959            Effect::new(move || {
1960                let (child_scope, children): (Scope, Vec<NodeId>) =
1961                    Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
1962                let first_opt: Option<NodeId> = children.first().copied();
1963                handle.replace_children_safe(host, children);
1964                if let Some(first) = first_opt {
1965                    handle.with_write(
1966                        |tree: &mut SceneTree| {
1967                            tree.attach_scope(first, child_scope);
1968                        },
1969                        (),
1970                    );
1971                }
1972            })
1973        });
1974        self.get_scene().with_write(
1975            |tree: &mut SceneTree| {
1976                tree.attach_scope(host, scope);
1977            },
1978            (),
1979        );
1980    }
1981}
1982
1983/// Restores the previously bound ambient `Context` when leaving scope.
1984impl Drop for ContextGuard {
1985    /// Restores the saved thread-local `Context`.
1986    ///
1987    /// # Arguments
1988    ///
1989    /// - `&Self` - Mutable scope guard being dropped.
1990    fn drop(&mut self) {
1991        let Self { previous } = self;
1992        let restored: Option<Context> = previous.take();
1993        ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
1994            *slot.borrow_mut() = restored;
1995        });
1996    }
1997}
1998
1999/// `NodeRefTarget` implementation storing a `NodeId` directly into a mutable local binding.
2000impl NodeRefTarget for NodeId {
2001    /// Assigns `id` to `self`.
2002    ///
2003    /// # Arguments
2004    ///
2005    /// - `&Self` - Target `NodeId` slot.
2006    /// - `NodeId` - Mounted node handle.
2007    fn bind_node_ref(&mut self, id: NodeId) {
2008        *self = id;
2009    }
2010}
2011
2012/// `NodeRefTarget` implementation storing a `NodeId` into an `Option<NodeId>`.
2013impl NodeRefTarget for Option<NodeId> {
2014    /// Assigns `Some(id)` to `self`.
2015    ///
2016    /// # Arguments
2017    ///
2018    /// - `&Self` - Target optional `NodeId` slot.
2019    /// - `NodeId` - Mounted node handle.
2020    fn bind_node_ref(&mut self, id: NodeId) {
2021        *self = Some(id);
2022    }
2023}
2024
2025/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<NodeId>`.
2026impl NodeRefTarget for Cell<NodeId> {
2027    /// Sets `self` to `id`.
2028    ///
2029    /// # Arguments
2030    ///
2031    /// - `&Self` - Target `Cell<NodeId>`.
2032    /// - `NodeId` - Mounted node handle.
2033    fn bind_node_ref(&mut self, id: NodeId) {
2034        self.set(id);
2035    }
2036}
2037
2038/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<NodeId>>`.
2039impl NodeRefTarget for Rc<Cell<NodeId>> {
2040    /// Sets the shared cell value to `id`.
2041    ///
2042    /// # Arguments
2043    ///
2044    /// - `&Self` - Target shared `Cell<NodeId>`.
2045    /// - `NodeId` - Mounted node handle.
2046    fn bind_node_ref(&mut self, id: NodeId) {
2047        self.set(id);
2048    }
2049}
2050
2051/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<Option<NodeId>>`.
2052impl NodeRefTarget for Cell<Option<NodeId>> {
2053    /// Sets `self` to `Some(id)`.
2054    ///
2055    /// # Arguments
2056    ///
2057    /// - `&Self` - Target `Cell<Option<NodeId>>`.
2058    /// - `NodeId` - Mounted node handle.
2059    fn bind_node_ref(&mut self, id: NodeId) {
2060        self.set(Some(id));
2061    }
2062}
2063
2064/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<Option<NodeId>>>`.
2065impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
2066    /// Sets the shared cell value to `Some(id)`.
2067    ///
2068    /// # Arguments
2069    ///
2070    /// - `&Self` - Target shared `Cell<Option<NodeId>>`.
2071    /// - `NodeId` - Mounted node handle.
2072    fn bind_node_ref(&mut self, id: NodeId) {
2073        self.set(Some(id));
2074    }
2075}