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            let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
533            self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
534        } else {
535            self.mark_dirty(target, DIRTY_PAINT);
536        }
537        self.get_mut_transitions().push(transition);
538    }
539
540    /// Advances all active transitions by `dt_secs` and returns `true` if any node updated.
541    ///
542    /// # Arguments
543    ///
544    /// - `&Self` - Mutable scene tree.
545    /// - `f32` - Elapsed frame time in seconds.
546    ///
547    /// # Returns
548    ///
549    /// - `bool` - Whether at least one transition ticked on this frame.
550    pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
551        if self.get_transitions().is_empty() {
552            return false;
553        }
554        let step: f32 = dt_secs.clamp(0.001, 0.05);
555        let mut active: Vec<NodeTransition> = take(self.get_mut_transitions());
556        let mut remaining: Vec<NodeTransition> = Vec::with_capacity(active.len());
557        let mut any_updated: bool = false;
558        for mut tr in active.drain(..) {
559            let target: NodeId = tr.get_node();
560            if self.get_node(target).is_none() {
561                continue;
562            }
563            let total_span: f32 = tr.get_delay() + tr.get_duration();
564            let prev_elapsed: f32 = tr.get_elapsed();
565            let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
566            tr.set_elapsed(next_elapsed);
567            let done: bool = tr.is_complete();
568            let in_hold: bool = prev_elapsed > 0.0 && next_elapsed <= tr.get_delay() && !done;
569            if !in_hold {
570                let (opacity, transform): (f32, Transform2D) = tr.sample();
571                let hide: bool = done && tr.get_hide_on_complete();
572                if let Some(node) = self.get_node_mut(target) {
573                    let mut style: Style = node.get_style();
574                    style.get_mut_paint().set_opacity(opacity);
575                    style.get_mut_paint().set_transform(transform);
576                    if hide {
577                        style.get_mut_layout().set_display(Display::None);
578                    }
579                    node.set_style(style);
580                }
581                if hide {
582                    self.clear_subtree_hover(target);
583                    let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
584                    self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
585                } else {
586                    self.mark_dirty(target, DIRTY_PAINT);
587                }
588                any_updated = true;
589            }
590            if !done {
591                remaining.push(tr);
592            }
593        }
594        self.set_transitions(remaining);
595        any_updated
596    }
597
598    /// Clears transient hover/active flags throughout the subtree rooted at `root` when an overlay hides.
599    ///
600    /// # Arguments
601    ///
602    /// - `&Self` - Mutable scene tree.
603    /// - `NodeId` - Root node being hidden.
604    fn clear_subtree_hover(&mut self, root: NodeId) {
605        let mut stack: Vec<NodeId> = vec![root];
606        while let Some(id) = stack.pop() {
607            let children: Vec<NodeId> = match self.get_node_mut(id) {
608                Some(node) => {
609                    node.get_mut_interaction().set_hovered(false);
610                    node.get_mut_interaction().set_pressed(false);
611                    node.get_children().clone()
612                }
613                None => continue,
614            };
615            stack.extend(children);
616        }
617    }
618
619    /// Returns `true` while one or more node transitions are still running.
620    ///
621    /// # Arguments
622    ///
623    /// - `&Self` - Scene tree reference.
624    ///
625    /// # Returns
626    ///
627    /// - `bool` - Whether animations are active.
628    #[must_use]
629    pub fn has_active_transitions(&self) -> bool {
630        !self.get_transitions().is_empty()
631    }
632
633    /// Attaches a `Lifecycle` hook observer onto `id` for mount, activate, freeze, resume, unmount, and destroy dispatch.
634    ///
635    /// # Arguments
636    ///
637    /// - `&Self` - Mutable scene tree.
638    /// - `NodeId` - Target scene node handle.
639    /// - `Rc<dyn Lifecycle>` - Shared lifecycle hook observer.
640    pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
641        if let Some(node) = self.get_node_mut(id) {
642            node.add_lifecycle(hook);
643        }
644    }
645
646    /// Collects all `(NodeId, Rc<dyn Lifecycle>)` observers in the subtree rooted at `root`.
647    ///
648    /// # Arguments
649    ///
650    /// - `&Self` - Scene tree reference.
651    /// - `NodeId` - Subtree root handle.
652    ///
653    /// # Returns
654    ///
655    /// - `Vec<(NodeId, Rc<dyn Lifecycle>)>` - Ordered observers in pre-order traversal.
656    #[must_use]
657    pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
658        let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
659        let mut stack: Vec<NodeId> = vec![root];
660        while let Some(current) = stack.pop() {
661            if let Some(node) = self.get_node(current) {
662                for hook in node.lifecycle_observers().into_iter() {
663                    out.push((current, hook));
664                }
665                for child in node.get_children().iter().rev().copied() {
666                    stack.push(child);
667                }
668            }
669        }
670        out
671    }
672
673    /// Cancels any active paint/transform transitions targeting nodes within the subtree rooted at `root`.
674    ///
675    /// # Arguments
676    ///
677    /// - `&Self` - Mutable scene tree.
678    /// - `NodeId` - Subtree root handle.
679    pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
680        if self.get_transitions().is_empty() {
681            return;
682        }
683        let mut ids: HashSet<NodeId> = HashSet::new();
684        let mut stack: Vec<NodeId> = vec![root];
685        while let Some(current) = stack.pop() {
686            if ids.insert(current)
687                && let Some(node) = self.get_node(current)
688            {
689                for child in node.get_children().iter().copied() {
690                    stack.push(child);
691                }
692            }
693        }
694        self.get_mut_transitions()
695            .retain(|tr: &NodeTransition| !ids.contains(&tr.get_node()));
696    }
697
698    /// Attaches a reactive `Scope` to `id` so it automatically disposes when the node unmounts.
699    ///
700    /// # Arguments
701    ///
702    /// - `&Self` - Mutable scene tree.
703    /// - `NodeId` - Target node handle.
704    /// - `Scope` - Reactive ownership scope.
705    pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
706        if let Some(node) = self.get_node_mut(id) {
707            if let Some(existing) = node.owned_scope() {
708                existing.enter(|| {
709                    on_cleanup(move || {
710                        scope.dispose();
711                    });
712                });
713            } else {
714                node.set_scope(Some(scope));
715            }
716        }
717    }
718
719    /// Marks `id` dirty with `mask` and propagates subtree dirty bits to ancestors in O(depth).
720    ///
721    /// # Arguments
722    ///
723    /// - `&Self` - Mutable scene tree.
724    /// - `NodeId` - Mutated node handle.
725    /// - `u16` - Dirty flag bits to set.
726    pub fn mark_dirty(&mut self, id: NodeId, mask: u16) {
727        let mut parent_opt: Option<NodeId> = match self.get_node_mut(id) {
728            Some(node) => {
729                node.get_mut_dirty().insert(mask);
730                node.parent_id()
731            }
732            None => return,
733        };
734        let mut ancestor_mask: u16 = DIRTY_NONE;
735        if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
736            ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
737        }
738        if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
739            ancestor_mask |= DIRTY_SUBTREE_PAINT;
740        }
741        while let Some(ancestor_id) = parent_opt {
742            if let Some(ancestor) = self.get_node_mut(ancestor_id) {
743                let already: bool =
744                    (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
745                ancestor.get_mut_dirty().insert(ancestor_mask);
746                if already {
747                    break;
748                }
749                parent_opt = ancestor.parent_id();
750            } else {
751                break;
752            }
753        }
754        let next_rev: u64 = self.get_revision().wrapping_add(1);
755        self.set_revision(next_rev);
756    }
757
758    /// Computes accumulated ancestor scroll offset for `id` (zero for top-layer `Portal`/`Fixed` nodes).
759    ///
760    /// # Arguments
761    ///
762    /// - `&Self` - Scene tree reference.
763    /// - `NodeId` - Target node handle.
764    ///
765    /// # Returns
766    ///
767    /// - `Point` - Total scroll offset applied to `id`.
768    fn ancestor_scroll_offset(&self, id: NodeId) -> Point {
769        let Some(start) = self.get_node(id) else {
770            return Point::default();
771        };
772        if matches!(start.get_kind(), NodeKind::Portal)
773            || start.get_style().get_layout().get_position() == Position::Fixed
774        {
775            return Point::default();
776        }
777        let mut sx: f32 = 0.0;
778        let mut sy: f32 = 0.0;
779        let mut cursor: Option<NodeId> = start.parent_id();
780        while let Some(pid) = cursor {
781            if let Some(pnode) = self.get_node(pid) {
782                let off: Point = pnode.get_layout_box().get_scroll_offset();
783                sx += off.get_x();
784                sy += off.get_y();
785                if matches!(pnode.get_kind(), NodeKind::Portal)
786                    || pnode.get_style().get_layout().get_position() == Position::Fixed
787                {
788                    break;
789                }
790                cursor = pnode.parent_id();
791            } else {
792                break;
793            }
794        }
795        Point::new(sx, sy)
796    }
797
798    /// Returns `true` when `id` and every ancestor up to the root are alive, non-`Display::None`, and have positive opacity.
799    ///
800    /// # Arguments
801    ///
802    /// - `&Self` - Scene tree reference.
803    /// - `NodeId` - Target node handle.
804    ///
805    /// # Returns
806    ///
807    /// - `bool` - Whether the node is visibly rendered in the scene.
808    #[must_use]
809    pub fn is_node_visible(&self, id: NodeId) -> bool {
810        let mut cursor: Option<NodeId> = Some(id);
811        while let Some(cur) = cursor {
812            let Some(node) = self.get_node(cur) else {
813                return false;
814            };
815            if node.get_style().get_layout().get_display() == Display::None
816                || node.get_style().get_paint().get_opacity() <= 0.0
817            {
818                return false;
819            }
820            cursor = node.parent_id();
821        }
822        true
823    }
824
825    /// Collects the tight physical damage region from dirty paint/scroll nodes and clears paint dirty flags.
826    ///
827    /// # Arguments
828    ///
829    /// - `&Self` - Mutable scene tree.
830    /// - `f32` - Active display scale factor.
831    ///
832    /// # Returns
833    ///
834    /// - `DamageRegion` - Minimal damaged region, full damage on structural/layout change, or clean when idle.
835    pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
836        let mut full: bool = false;
837        let mut dirty_ids: Vec<(NodeId, Rect, f32)> = Vec::new();
838        for (idx, node) in self.get_nodes().iter().enumerate() {
839            if !node.get_alive() {
840                continue;
841            }
842            let bits: u16 = node.get_dirty().get_bits();
843            if (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
844                full = true;
845                break;
846            }
847            if (bits & (DIRTY_PAINT | DIRTY_SCROLL)) != 0 {
848                let b: Rect = node.get_layout_box().get_bounds();
849                if b.get_width() > 0.0 && b.get_height() > 0.0 {
850                    let mut margin: f32 = 10.0;
851                    if let Some(shadow) = node.get_style().get_paint().box_shadow() {
852                        margin = margin.max(
853                            shadow.get_blur_radius()
854                                + shadow.get_spread_radius()
855                                + shadow.get_offset_x().abs().max(shadow.get_offset_y().abs())
856                                + 4.0,
857                        );
858                    }
859                    let nid: NodeId = NodeId::new(idx as u32, node.get_generation());
860                    dirty_ids.push((nid, b, margin));
861                } else if (bits & DIRTY_PAINT) != 0 {
862                    full = true;
863                    break;
864                }
865            }
866        }
867        let mut damage: DamageRegion = if full {
868            DamageRegion::full()
869        } else {
870            let mut region: DamageRegion = DamageRegion::default();
871            for (nid, raw_bounds, margin) in dirty_ids.into_iter() {
872                let off: Point = self.ancestor_scroll_offset(nid);
873                let phys: Rect = Rect::new(
874                    ((raw_bounds.get_x() - off.get_x() - margin) * scale).floor(),
875                    ((raw_bounds.get_y() - off.get_y() - margin) * scale).floor(),
876                    ((raw_bounds.get_width() + margin * 2.0) * scale).ceil(),
877                    ((raw_bounds.get_height() + margin * 2.0) * scale).ceil(),
878                );
879                region.add_rect(phys);
880            }
881            region
882        };
883        let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
884        for node in self.get_mut_nodes().iter_mut() {
885            if node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0 {
886                node.get_mut_dirty().remove(clear_mask);
887            }
888        }
889        if full {
890            damage.set_full_damage(true);
891        }
892        damage
893    }
894
895    /// Recursively detaches and recycles `id`, returning all owned `Scope`s and `Lifecycle` observers for borrow-safe finalization.
896    ///
897    /// # Arguments
898    ///
899    /// - `&Self` - Mutable scene tree.
900    /// - `NodeId` - Subtree root handle to dispose.
901    ///
902    /// # Returns
903    ///
904    /// - `DisposedSubtreePayload` - Collected scopes and lifecycle observers to finalize outside any borrow.
905    pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
906        if id == self.get_root() {
907            return (Vec::new(), Vec::new());
908        }
909        self.cancel_subtree_transitions(id);
910        let mut stack: Vec<NodeId> = vec![id];
911        let mut scopes: Vec<Scope> = Vec::new();
912        let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
913        while let Some(current) = stack.pop() {
914            let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(current) {
915                Some(node) => {
916                    node.set_alive(false);
917                    if let Some(scope) = node.owned_scope() {
918                        scopes.push(scope);
919                    }
920                    for hook in node.take_lifecycles().into_iter() {
921                        observers.push((current, hook));
922                    }
923                    node.set_scope(None);
924                    node.set_parent(None);
925                    node.set_canvas_painter(None);
926                    node.set_handlers(EventHandlers::default());
927                    let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
928                    node.set_generation(next_gen);
929                    Some(take(node.get_mut_children()))
930                }
931                None => None,
932            };
933            let Some(children) = children_opt else {
934                continue;
935            };
936            self.get_mut_free_list().push(current.get_index());
937            for child in children.into_iter() {
938                stack.push(child);
939            }
940        }
941        (scopes, observers)
942    }
943
944    /// Recursively removes and disposes `id`, recycling all arena slots, running lifecycle hooks, and disposing scopes.
945    ///
946    /// # Arguments
947    ///
948    /// - `&Self` - Mutable scene tree.
949    /// - `NodeId` - Subtree root handle to dispose.
950    pub fn dispose_subtree(&mut self, id: NodeId) {
951        let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
952        finalize_disposed_subtree(scopes, observers);
953    }
954
955    /// Updates keyboard focus to `target`, emitting `Blur` and `Focus` events.
956    ///
957    /// # Arguments
958    ///
959    /// - `&Self` - Mutable scene tree.
960    /// - `Option<NodeId>` - Newly focused node, or `None` to clear focus.
961    ///
962    /// # Returns
963    ///
964    /// - `Vec<(UiEventHandler, UiEvent)>` - Callbacks to invoke outside the tree borrow.
965    pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
966        let prev: Option<NodeId> = self.get_focus().focused_node();
967        if prev == target {
968            return Vec::new();
969        }
970        let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
971        if let Some(old_id) = prev {
972            if let Some(old_node) = self.get_node_mut(old_id) {
973                old_node.get_mut_interaction().set_focused(false);
974                if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
975                    callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
976                }
977            }
978            self.mark_dirty(old_id, DIRTY_PAINT);
979        }
980        self.get_mut_focus().set_focused(target);
981        if let Some(new_id) = target {
982            if let Some(new_node) = self.get_node_mut(new_id) {
983                new_node.get_mut_interaction().set_focused(true);
984                if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
985                    callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
986                }
987            }
988            self.mark_dirty(new_id, DIRTY_PAINT);
989        }
990        callbacks
991    }
992}
993
994/// Shared scene handle operations enabling surgical reactive node updates.
995impl SceneHandle {
996    /// Creates a new `SceneHandle` wrapping a fresh `SceneTree`.
997    ///
998    /// # Returns
999    ///
1000    /// - `Self` - Shared scene handle.
1001    #[must_use]
1002    pub fn new_tree() -> Self {
1003        Self {
1004            inner: Rc::new(RefCell::new(SceneTree::default())),
1005        }
1006    }
1007
1008    /// Updates virtualized scroll metrics `(scroll_y, content_height)` on `id` for accurate scrollbar thumbs.
1009    ///
1010    /// # Arguments
1011    ///
1012    /// - `&Self` - Scene handle reference.
1013    /// - `NodeId` - Target virtualized scroll container.
1014    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
1015    /// - `f32` - Total virtualized content height in logical pixels.
1016    pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
1017        self.with_write(
1018            |tree: &mut SceneTree| {
1019                tree.set_virtual_scroll(id, scroll_y, content_height);
1020            },
1021            (),
1022        );
1023    }
1024
1025    /// Computes screen-space logical bounds for `id` subtracting ancestor scroll offsets.
1026    ///
1027    /// # Arguments
1028    ///
1029    /// - `&Self` - Scene handle reference.
1030    /// - `NodeId` - Target node handle.
1031    ///
1032    /// # Returns
1033    ///
1034    /// - `Option<Rect>` - Screen-space bounds if the node is alive.
1035    #[must_use]
1036    pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
1037        self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
1038    }
1039
1040    /// Starts or replaces a smooth paint/transform transition on the target node.
1041    ///
1042    /// # Arguments
1043    ///
1044    /// - `&Self` - Scene handle reference.
1045    /// - `NodeTransition` - Transition specification to run.
1046    pub fn start_transition(&self, transition: NodeTransition) {
1047        self.with_write(
1048            |tree: &mut SceneTree| {
1049                tree.start_transition(transition);
1050            },
1051            (),
1052        );
1053    }
1054
1055    /// Marks `id` dirty with `mask` for incremental repainting.
1056    ///
1057    /// # Arguments
1058    ///
1059    /// - `&Self` - Scene handle reference.
1060    /// - `NodeId` - Target node handle.
1061    /// - `u16` - Dirty flag bits.
1062    pub fn mark_dirty(&self, id: NodeId, mask: u16) {
1063        self.with_write(
1064            |tree: &mut SceneTree| {
1065                tree.mark_dirty(id, mask);
1066            },
1067            (),
1068        );
1069    }
1070
1071    /// Replaces all children of `parent` and finalizes disposed scopes and `Lifecycle` hooks outside the tree borrow.
1072    ///
1073    /// # Arguments
1074    ///
1075    /// - `&Self` - Scene handle reference.
1076    /// - `NodeId` - Parent container node.
1077    /// - `Vec<NodeId>` - Replacement ordered children.
1078    pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
1079        let (scopes, observers): DisposedSubtreePayload = self.with_write(
1080            |tree: &mut SceneTree| {
1081                let old_children: Vec<NodeId> = match tree.get_node_mut(parent) {
1082                    Some(node) => take(node.get_mut_children()),
1083                    None => return (Vec::new(), Vec::new()),
1084                };
1085                let mut all_scopes: Vec<Scope> = Vec::new();
1086                let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1087                for old_child in old_children.into_iter() {
1088                    if !new_children.contains(&old_child) {
1089                        let (sc, ob): DisposedSubtreePayload =
1090                            tree.dispose_subtree_collect(old_child);
1091                        all_scopes.extend(sc);
1092                        all_obs.extend(ob);
1093                    }
1094                }
1095                for child in new_children.iter().copied() {
1096                    if let Some(child_node) = tree.get_node_mut(child) {
1097                        child_node.set_parent(Some(parent));
1098                    }
1099                }
1100                if let Some(parent_node) = tree.get_node_mut(parent) {
1101                    parent_node.set_children(new_children);
1102                }
1103                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1104                (all_scopes, all_obs)
1105            },
1106            (Vec::new(), Vec::new()),
1107        );
1108        finalize_disposed_subtree(scopes, observers);
1109    }
1110
1111    /// Removes `child` from `parent`, disposes its subtree, and invokes `on_unmount`/`on_destroy` outside any scene borrow.
1112    ///
1113    /// # Arguments
1114    ///
1115    /// - `&Self` - Scene handle reference.
1116    /// - `NodeId` - Parent container handle.
1117    /// - `NodeId` - Child subtree root handle to remove and destroy.
1118    pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
1119        let (scopes, observers): DisposedSubtreePayload = self.with_write(
1120            |tree: &mut SceneTree| {
1121                if let Some(pnode) = tree.get_node_mut(parent) {
1122                    pnode.get_mut_children().retain(|id: &NodeId| *id != child);
1123                }
1124                let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
1125                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1126                out
1127            },
1128            (Vec::new(), Vec::new()),
1129        );
1130        finalize_disposed_subtree(scopes, observers);
1131    }
1132
1133    /// Freezes a subtree visually (`Display::None`), cancels its transitions, and dispatches `Lifecycle::on_freeze` outside any scene borrow.
1134    ///
1135    /// # Arguments
1136    ///
1137    /// - `&Self` - Scene handle reference.
1138    /// - `NodeId` - Subtree root handle to freeze.
1139    pub fn freeze_subtree(&self, root: NodeId) {
1140        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
1141            |tree: &mut SceneTree| {
1142                let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
1143                tree.cancel_subtree_transitions(root);
1144                if let Some(node) = tree.get_node_mut(root) {
1145                    let mut st: Style = node.get_style();
1146                    st.get_mut_layout().set_display(Display::None);
1147                    node.set_style(st);
1148                }
1149                tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
1150                obs
1151            },
1152            Vec::new(),
1153        );
1154        dispatch_lifecycle_freeze(&observers);
1155    }
1156
1157    /// Resumes a previously frozen subtree (`Display::Flex`) and dispatches `Lifecycle::on_resume` outside any scene borrow.
1158    ///
1159    /// # Arguments
1160    ///
1161    /// - `&Self` - Scene handle reference.
1162    /// - `NodeId` - Subtree root handle to resume.
1163    pub fn resume_subtree(&self, root: NodeId) {
1164        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
1165            |tree: &mut SceneTree| {
1166                if let Some(node) = tree.get_node_mut(root) {
1167                    let mut st: Style = node.get_style();
1168                    if st.get_layout().get_display() == Display::None {
1169                        st.get_mut_layout().set_display(Display::Flex);
1170                        node.set_style(st);
1171                    }
1172                }
1173                tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
1174                tree.collect_subtree_lifecycles(root)
1175            },
1176            Vec::new(),
1177        );
1178        dispatch_lifecycle_resume(&observers);
1179    }
1180
1181    /// Dispatches `Lifecycle::on_activate` across all observers in the subtree rooted at `root`.
1182    ///
1183    /// # Arguments
1184    ///
1185    /// - `&Self` - Scene handle reference.
1186    /// - `NodeId` - Subtree root handle becoming active.
1187    pub fn activate_subtree(&self, root: NodeId) {
1188        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
1189            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
1190            Vec::new(),
1191        );
1192        dispatch_lifecycle_activate(&observers);
1193    }
1194
1195    /// Dispatches `Lifecycle::on_update` across all observers in the subtree rooted at `root`.
1196    ///
1197    /// # Arguments
1198    ///
1199    /// - `&Self` - Scene handle reference.
1200    /// - `NodeId` - Subtree root handle receiving updates.
1201    pub fn update_subtree(&self, root: NodeId) {
1202        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
1203            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
1204            Vec::new(),
1205        );
1206        dispatch_lifecycle_update(&observers);
1207    }
1208
1209    /// Returns `true` if any node transition is currently active.
1210    ///
1211    /// # Arguments
1212    ///
1213    /// - `&Self` - Scene handle reference.
1214    ///
1215    /// # Returns
1216    ///
1217    /// - `bool` - Whether animations are running.
1218    #[must_use]
1219    pub fn has_active_transitions(&self) -> bool {
1220        self.with_read(SceneTree::has_active_transitions, false)
1221    }
1222
1223    /// Executes `operation` with immutable access to the underlying `SceneTree`.
1224    ///
1225    /// # Arguments
1226    ///
1227    /// - `&Self` - Scene handle.
1228    /// - `F` - Reader closure.
1229    /// - `R` - Fallback if re-entrantly borrowed.
1230    ///
1231    /// # Returns
1232    ///
1233    /// - `R` - Closure result or fallback.
1234    pub fn with_read<F, R>(&self, operation: F, fallback: R) -> R
1235    where
1236        F: FnOnce(&SceneTree) -> R,
1237    {
1238        let Self { inner } = self;
1239        match inner.try_borrow() {
1240            Ok(guard) => operation(&guard),
1241            Err(_) => fallback,
1242        }
1243    }
1244
1245    /// Executes `operation` with mutable access to the underlying `SceneTree`.
1246    ///
1247    /// # Arguments
1248    ///
1249    /// - `&Self` - Scene handle.
1250    /// - `F` - Mutation closure.
1251    /// - `R` - Fallback if re-entrantly borrowed.
1252    ///
1253    /// # Returns
1254    ///
1255    /// - `R` - Closure result or fallback.
1256    pub fn with_write<F, R>(&self, operation: F, fallback: R) -> R
1257    where
1258        F: FnOnce(&mut SceneTree) -> R,
1259    {
1260        let Self { inner } = self;
1261        match inner.try_borrow_mut() {
1262            Ok(mut guard) => operation(&mut guard),
1263            Err(_) => fallback,
1264        }
1265    }
1266
1267    /// Binds a reactive text expression to `node_id` via a surgical `Effect`.
1268    ///
1269    /// # Arguments
1270    ///
1271    /// - `&Self` - Scene handle.
1272    /// - `NodeId` - Target text node.
1273    /// - `F` - Reactive text producer closure.
1274    ///
1275    /// # Returns
1276    ///
1277    /// - `Effect` - Registered reactive effect.
1278    pub fn bind_text<F>(&self, node_id: NodeId, mut producer: F) -> Effect
1279    where
1280        F: FnMut() -> String + 'static,
1281    {
1282        let handle: Self = self.clone();
1283        Effect::new(move || {
1284            let value: String = producer();
1285            handle.with_write(
1286                |tree: &mut SceneTree| {
1287                    tree.set_text(node_id, value);
1288                },
1289                (),
1290            );
1291        })
1292    }
1293
1294    /// Binds a reactive `Style` expression to `node_id` via a surgical `Effect`.
1295    ///
1296    /// # Arguments
1297    ///
1298    /// - `&Self` - Scene handle.
1299    /// - `NodeId` - Target node.
1300    /// - `F` - Reactive style producer closure.
1301    ///
1302    /// # Returns
1303    ///
1304    /// - `Effect` - Registered reactive effect.
1305    pub fn bind_style<F>(&self, node_id: NodeId, mut producer: F) -> Effect
1306    where
1307        F: FnMut() -> Style + 'static,
1308    {
1309        let handle: Self = self.clone();
1310        Effect::new(move || {
1311            let style: Style = producer();
1312            handle.with_write(
1313                |tree: &mut SceneTree| {
1314                    tree.set_style(node_id, style);
1315                },
1316                (),
1317            );
1318        })
1319    }
1320}
1321
1322/// High-level declarative building helpers on `Context`.
1323impl Context {
1324    /// Creates a new `Context` with reactive viewport, theme, and safe-area signals.
1325    ///
1326    /// # Arguments
1327    ///
1328    /// - `SceneHandle` - Shared scene handle.
1329    /// - `PlatformKind` - Active platform kind.
1330    ///
1331    /// # Returns
1332    ///
1333    /// - `Self` - Constructed build context.
1334    #[must_use]
1335    pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
1336        Self {
1337            scene,
1338            breakpoint: Signal::new(Breakpoint::Expanded),
1339            viewport_size: Signal::new(Size::new(1200.0, 800.0)),
1340            theme_mode: Signal::new(ThemeMode::Light),
1341            platform,
1342            safe_area: Signal::new(SafeAreaInsets::default()),
1343            gesture: Signal::new(None),
1344            system_back: Signal::new(0),
1345            dynamic_hub: DynamicUpdateHub::new(),
1346            fps_limit: Signal::new(None),
1347            live_fps: Signal::new(60.0),
1348            active_touches: Signal::new(Vec::new()),
1349            exit_requested: Signal::new(false),
1350            clock_ms: Rc::new(Cell::new(0)),
1351        }
1352    }
1353
1354    /// Returns the monotonic runtime elapsed clock in milliseconds.
1355    ///
1356    /// # Arguments
1357    ///
1358    /// - `&Self` - Context reference.
1359    ///
1360    /// # Returns
1361    ///
1362    /// - `u64` - Elapsed runtime time in milliseconds.
1363    #[must_use]
1364    pub fn elapsed_ms(&self) -> u64 {
1365        let Self { clock_ms, .. } = self;
1366        clock_ms.get()
1367    }
1368
1369    /// Advances the context's monotonic runtime clock by `delta_ms` milliseconds.
1370    ///
1371    /// # Arguments
1372    ///
1373    /// - `&Self` - Context reference.
1374    /// - `u64` - Milliseconds elapsed since the previous frame.
1375    pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
1376        let Self { clock_ms, .. } = self;
1377        clock_ms.set(clock_ms.get().saturating_add(delta_ms));
1378    }
1379
1380    /// Requests graceful OS-level application termination across all platforms.
1381    ///
1382    /// # Arguments
1383    ///
1384    /// - `&Self` - Context reference.
1385    pub fn request_exit(&self) {
1386        let _: bool = self.get_exit_requested().set_if_changed(true);
1387        let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
1388    }
1389
1390    /// Creates a `View` node with the given style.
1391    ///
1392    /// # Arguments
1393    ///
1394    /// - `&Self` - Build context.
1395    /// - `Style` - Initial style.
1396    ///
1397    /// # Returns
1398    ///
1399    /// - `NodeId` - Created node handle.
1400    pub fn view(&mut self, style: Style) -> NodeId {
1401        self.get_scene().with_write(
1402            |tree: &mut SceneTree| tree.create_view(style),
1403            NodeId::default(),
1404        )
1405    }
1406
1407    /// Creates a `Text` node with static initial text.
1408    ///
1409    /// # Arguments
1410    ///
1411    /// - `&Self` - Build context.
1412    /// - `String` - Text content.
1413    /// - `Style` - Text style.
1414    ///
1415    /// # Returns
1416    ///
1417    /// - `NodeId` - Created node handle.
1418    pub fn text(&mut self, content: String, style: Style) -> NodeId {
1419        self.get_scene().with_write(
1420            |tree: &mut SceneTree| tree.create_text(content, style),
1421            NodeId::default(),
1422        )
1423    }
1424
1425    /// Creates a reactive `Text` node whose content updates surgically whenever tracked signals change.
1426    ///
1427    /// # Arguments
1428    ///
1429    /// - `&Self` - Build context.
1430    /// - `Style` - Text style.
1431    /// - `F` - Reactive text producer.
1432    ///
1433    /// # Returns
1434    ///
1435    /// - `NodeId` - Created reactive text node handle.
1436    pub fn reactive_text<F>(&mut self, style: Style, producer: F) -> NodeId
1437    where
1438        F: FnMut() -> String + 'static,
1439    {
1440        let node_id: NodeId = self.text(String::new(), style);
1441        let handle: SceneHandle = self.get_scene().clone();
1442        let (scope, _): (Scope, Effect) =
1443            Scope::run(|_: Scope| handle.bind_text(node_id, producer));
1444        self.get_scene().with_write(
1445            |tree: &mut SceneTree| {
1446                tree.attach_scope(node_id, scope);
1447            },
1448            (),
1449        );
1450        node_id
1451    }
1452
1453    /// Creates a `ScrollView` node with the given style.
1454    ///
1455    /// # Arguments
1456    ///
1457    /// - `&Self` - Build context.
1458    /// - `Style` - Scroll container style.
1459    ///
1460    /// # Returns
1461    ///
1462    /// - `NodeId` - Created scroll view handle.
1463    pub fn scroll_view(&mut self, style: Style) -> NodeId {
1464        self.get_scene().with_write(
1465            |tree: &mut SceneTree| tree.create_scroll_view(style),
1466            NodeId::default(),
1467        )
1468    }
1469
1470    /// Creates an `Input` node with initial state and style.
1471    ///
1472    /// # Arguments
1473    ///
1474    /// - `&Self` - Build context.
1475    /// - `InputNodeState` - Initial input state.
1476    /// - `Style` - Input style.
1477    ///
1478    /// # Returns
1479    ///
1480    /// - `NodeId` - Created input handle.
1481    pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
1482        self.get_scene().with_write(
1483            |tree: &mut SceneTree| tree.create_input(state, style),
1484            NodeId::default(),
1485        )
1486    }
1487
1488    /// Creates an `Image` node with decoded RGBA8 pixel data.
1489    ///
1490    /// # Arguments
1491    ///
1492    /// - `&Self` - Build context.
1493    /// - `ImageBuffer` - Image buffer.
1494    /// - `Style` - Image style.
1495    ///
1496    /// # Returns
1497    ///
1498    /// - `NodeId` - Created image handle.
1499    pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
1500        self.get_scene().with_write(
1501            |tree: &mut SceneTree| tree.create_image(buffer, style),
1502            NodeId::default(),
1503        )
1504    }
1505
1506    /// Creates a `Canvas` node bound to a custom draw callback.
1507    ///
1508    /// # Arguments
1509    ///
1510    /// - `&Self` - Build context.
1511    /// - `Style` - Canvas style.
1512    /// - `F` - Draw callback receiving node bounds and mutable `DisplayList`.
1513    ///
1514    /// # Returns
1515    ///
1516    /// - `NodeId` - Created canvas handle.
1517    pub fn canvas<F>(&mut self, style: Style, painter: F) -> NodeId
1518    where
1519        F: FnMut(Rect, &mut DisplayList) + 'static,
1520    {
1521        let cb: CanvasDrawCallback = Rc::new(RefCell::new(painter));
1522        self.get_scene().with_write(
1523            |tree: &mut SceneTree| tree.create_canvas(style, cb),
1524            NodeId::default(),
1525        )
1526    }
1527
1528    /// Creates an overlay `Portal` node.
1529    ///
1530    /// # Arguments
1531    ///
1532    /// - `&Self` - Build context.
1533    /// - `Style` - Portal style.
1534    ///
1535    /// # Returns
1536    ///
1537    /// - `NodeId` - Created portal handle.
1538    pub fn portal(&mut self, style: Style) -> NodeId {
1539        self.get_scene().with_write(
1540            |tree: &mut SceneTree| tree.create_portal(style),
1541            NodeId::default(),
1542        )
1543    }
1544
1545    /// Creates a transparent logical `Fragment` grouping container for sibling nodes.
1546    ///
1547    /// # Arguments
1548    ///
1549    /// - `&Self` - Build context.
1550    ///
1551    /// # Returns
1552    ///
1553    /// - `NodeId` - Created fragment handle.
1554    pub fn fragment(&mut self) -> NodeId {
1555        self.get_scene().with_write(
1556            |tree: &mut SceneTree| tree.create_fragment(),
1557            NodeId::default(),
1558        )
1559    }
1560
1561    /// Appends `child` to `parent`.
1562    ///
1563    /// # Arguments
1564    ///
1565    /// - `&Self` - Build context.
1566    /// - `NodeId` - Parent container.
1567    /// - `NodeId` - Child node.
1568    pub fn append(&mut self, parent: NodeId, child: NodeId) {
1569        self.get_scene().with_write(
1570            |tree: &mut SceneTree| {
1571                tree.append_child(parent, child);
1572            },
1573            (),
1574        );
1575    }
1576
1577    /// Appends a slice of `children` to `parent` under a single scene write lock and dirty pass.
1578    ///
1579    /// # Arguments
1580    ///
1581    /// - `&Self` - Build context.
1582    /// - `NodeId` - Parent container.
1583    /// - `&[NodeId]` - Ordered child node slice.
1584    pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
1585        if children.is_empty() {
1586            return;
1587        }
1588        self.get_scene().with_write(
1589            |tree: &mut SceneTree| {
1590                tree.append_children(parent, children);
1591            },
1592            (),
1593        );
1594    }
1595
1596    /// Binds a reactive `Style` closure to `node_id` and attaches its disposal `Scope` automatically.
1597    ///
1598    /// # Arguments
1599    ///
1600    /// - `&Self` - Build context.
1601    /// - `NodeId` - Target scene node.
1602    /// - `F` - Reactive `Style` producer closure.
1603    pub fn bind_style<F>(&mut self, node_id: NodeId, producer: F)
1604    where
1605        F: FnMut() -> Style + 'static,
1606    {
1607        let handle: SceneHandle = self.get_scene().clone();
1608        let (scope, _): (Scope, Effect) =
1609            Scope::run(|_: Scope| handle.bind_style(node_id, producer));
1610        self.get_scene().with_write(
1611            |tree: &mut SceneTree| {
1612                tree.attach_scope(node_id, scope);
1613            },
1614            (),
1615        );
1616    }
1617
1618    /// Registers a pointer-enter handler on `node_id`.
1619    ///
1620    /// # Arguments
1621    ///
1622    /// - `&Self` - Build context.
1623    /// - `NodeId` - Target node handle.
1624    /// - `F` - Pointer-enter callback closure.
1625    pub fn on_pointer_enter<F>(&mut self, node_id: NodeId, callback: F)
1626    where
1627        F: FnMut(&UiEvent) + 'static,
1628    {
1629        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1630        self.get_scene().with_write(
1631            |tree: &mut SceneTree| {
1632                if let Some(node) = tree.get_node_mut(node_id) {
1633                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
1634                }
1635            },
1636            (),
1637        );
1638    }
1639
1640    /// Registers a pointer-leave handler on `node_id`.
1641    ///
1642    /// # Arguments
1643    ///
1644    /// - `&Self` - Build context.
1645    /// - `NodeId` - Target node handle.
1646    /// - `F` - Pointer-leave callback closure.
1647    pub fn on_pointer_leave<F>(&mut self, node_id: NodeId, callback: F)
1648    where
1649        F: FnMut(&UiEvent) + 'static,
1650    {
1651        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1652        self.get_scene().with_write(
1653            |tree: &mut SceneTree| {
1654                if let Some(node) = tree.get_node_mut(node_id) {
1655                    node.get_mut_handlers().set_on_pointer_leave(Some(handler));
1656                }
1657            },
1658            (),
1659        );
1660    }
1661
1662    /// Registers a focus-gained handler on `node_id` and marks it focusable.
1663    ///
1664    /// # Arguments
1665    ///
1666    /// - `&Self` - Build context.
1667    /// - `NodeId` - Target node handle.
1668    /// - `F` - Focus callback closure receiving `UiEventKind::Focus`.
1669    pub fn on_focus<F>(&mut self, node_id: NodeId, callback: F)
1670    where
1671        F: FnMut(&UiEvent) + 'static,
1672    {
1673        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1674        self.get_scene().with_write(
1675            |tree: &mut SceneTree| {
1676                if let Some(node) = tree.get_node_mut(node_id) {
1677                    node.get_mut_handlers().set_on_focus(Some(handler));
1678                    node.get_mut_interaction().set_focusable(true);
1679                }
1680            },
1681            (),
1682        );
1683    }
1684
1685    /// Registers a focus-lost handler on `node_id`.
1686    ///
1687    /// # Arguments
1688    ///
1689    /// - `&Self` - Build context.
1690    /// - `NodeId` - Target node handle.
1691    /// - `F` - Blur callback closure receiving `UiEventKind::Blur`.
1692    pub fn on_blur<F>(&mut self, node_id: NodeId, callback: F)
1693    where
1694        F: FnMut(&UiEvent) + 'static,
1695    {
1696        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1697        self.get_scene().with_write(
1698            |tree: &mut SceneTree| {
1699                if let Some(node) = tree.get_node_mut(node_id) {
1700                    node.get_mut_handlers().set_on_blur(Some(handler));
1701                }
1702            },
1703            (),
1704        );
1705    }
1706
1707    /// Configures whether `node_id` participates in keyboard focus navigation.
1708    ///
1709    /// # Arguments
1710    ///
1711    /// - `&Self` - Build context.
1712    /// - `NodeId` - Target node handle.
1713    /// - `bool` - Whether keyboard focus is enabled.
1714    pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
1715        self.get_scene().with_write(
1716            |tree: &mut SceneTree| {
1717                if let Some(node) = tree.get_node_mut(node_id) {
1718                    node.get_mut_interaction().set_focusable(focusable);
1719                }
1720            },
1721            (),
1722        );
1723    }
1724
1725    /// Registers a click handler on `node_id` and sets pointer cursor automatically.
1726    ///
1727    /// # Arguments
1728    ///
1729    /// - `&Self` - Build context.
1730    /// - `NodeId` - Target node.
1731    /// - `F` - Click callback closure.
1732    pub fn on_click<F>(&mut self, node_id: NodeId, callback: F)
1733    where
1734        F: FnMut(&UiEvent) + 'static,
1735    {
1736        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1737        self.get_scene().with_write(
1738            |tree: &mut SceneTree| {
1739                if let Some(node) = tree.get_node_mut(node_id) {
1740                    node.get_mut_handlers().set_on_click(Some(handler));
1741                    node.get_mut_interaction().set_focusable(true);
1742                    if node.get_style().get_paint().get_cursor() == CursorIcon::Default {
1743                        let mut style: Style = node.get_style();
1744                        style.get_mut_paint().set_cursor(CursorIcon::Pointer);
1745                        node.set_style(style);
1746                    }
1747                }
1748            },
1749            (),
1750        );
1751    }
1752
1753    /// Registers a change handler on an `Input` node.
1754    ///
1755    /// # Arguments
1756    ///
1757    /// - `&Self` - Build context.
1758    /// - `NodeId` - Target input node.
1759    /// - `F` - Change callback closure.
1760    pub fn on_change<F>(&mut self, node_id: NodeId, callback: F)
1761    where
1762        F: FnMut(&UiEvent) + 'static,
1763    {
1764        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1765        self.get_scene().with_write(
1766            |tree: &mut SceneTree| {
1767                if let Some(node) = tree.get_node_mut(node_id) {
1768                    node.get_mut_handlers().set_on_change(Some(handler));
1769                }
1770            },
1771            (),
1772        );
1773    }
1774
1775    /// Attaches semantic accessibility properties to `node_id`.
1776    ///
1777    /// # Arguments
1778    ///
1779    /// - `&Self` - Build context.
1780    /// - `NodeId` - Target scene node.
1781    /// - `A11yProps` - Semantic role, label, hint, and state metadata.
1782    pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
1783        self.get_scene().with_write(
1784            |tree: &mut SceneTree| {
1785                if let Some(node) = tree.get_node_mut(node_id) {
1786                    node.set_a11y(Some(props));
1787                }
1788            },
1789            (),
1790        );
1791    }
1792
1793    /// Registers a scroll handler on a scrollable container node.
1794    ///
1795    /// # Arguments
1796    ///
1797    /// - `&Self` - Build context.
1798    /// - `NodeId` - Target scroll container node.
1799    /// - `F` - Scroll callback closure receiving `UiEventKind::Scroll(delta)`.
1800    pub fn on_scroll<F>(&mut self, node_id: NodeId, callback: F)
1801    where
1802        F: FnMut(&UiEvent) + 'static,
1803    {
1804        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1805        self.get_scene().with_write(
1806            |tree: &mut SceneTree| {
1807                if let Some(node) = tree.get_node_mut(node_id) {
1808                    node.get_mut_handlers().set_on_scroll(Some(handler));
1809                }
1810            },
1811            (),
1812        );
1813    }
1814
1815    /// Registers a pointer-down handler on `node_id` for draggable interactive controls.
1816    ///
1817    /// # Arguments
1818    ///
1819    /// - `&Self` - Build context.
1820    /// - `NodeId` - Target node handle.
1821    /// - `F` - Pointer-down callback closure.
1822    pub fn on_pointer_down<F>(&mut self, node_id: NodeId, callback: F)
1823    where
1824        F: FnMut(&UiEvent) + 'static,
1825    {
1826        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1827        self.get_scene().with_write(
1828            |tree: &mut SceneTree| {
1829                if let Some(node) = tree.get_node_mut(node_id) {
1830                    node.get_mut_handlers().set_on_pointer_down(Some(handler));
1831                    if node.get_style().get_paint().get_cursor() == CursorIcon::Default {
1832                        let mut style: Style = node.get_style();
1833                        style.get_mut_paint().set_cursor(CursorIcon::Pointer);
1834                        node.set_style(style);
1835                    }
1836                }
1837            },
1838            (),
1839        );
1840    }
1841
1842    /// Registers a pointer-move handler on `node_id` receiving captured drag coordinates while pressed.
1843    ///
1844    /// # Arguments
1845    ///
1846    /// - `&Self` - Build context.
1847    /// - `NodeId` - Target node handle.
1848    /// - `F` - Pointer-move callback closure.
1849    pub fn on_pointer_move<F>(&mut self, node_id: NodeId, callback: F)
1850    where
1851        F: FnMut(&UiEvent) + 'static,
1852    {
1853        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1854        self.get_scene().with_write(
1855            |tree: &mut SceneTree| {
1856                if let Some(node) = tree.get_node_mut(node_id) {
1857                    node.get_mut_handlers().set_on_pointer_move(Some(handler));
1858                }
1859            },
1860            (),
1861        );
1862    }
1863
1864    /// Registers a pointer-up handler on `node_id` invoked when drag capture releases.
1865    ///
1866    /// # Arguments
1867    ///
1868    /// - `&Self` - Build context.
1869    /// - `NodeId` - Target node handle.
1870    /// - `F` - Pointer-up callback closure.
1871    pub fn on_pointer_up<F>(&mut self, node_id: NodeId, callback: F)
1872    where
1873        F: FnMut(&UiEvent) + 'static,
1874    {
1875        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1876        self.get_scene().with_write(
1877            |tree: &mut SceneTree| {
1878                if let Some(node) = tree.get_node_mut(node_id) {
1879                    node.get_mut_handlers().set_on_pointer_up(Some(handler));
1880                }
1881            },
1882            (),
1883        );
1884    }
1885
1886    /// Registers a hover handler on `node_id` invoked on both `PointerEnter` and `PointerLeave`.
1887    ///
1888    /// # Arguments
1889    ///
1890    /// - `&Self` - Build context.
1891    /// - `NodeId` - Target node handle.
1892    /// - `F` - Hover callback closure receiving `UiEventKind::PointerEnter` or `PointerLeave`.
1893    pub fn on_hover<F>(&mut self, node_id: NodeId, callback: F)
1894    where
1895        F: FnMut(&UiEvent) + 'static,
1896    {
1897        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1898        let leave_handler: UiEventHandler = handler.clone();
1899        self.get_scene().with_write(
1900            |tree: &mut SceneTree| {
1901                if let Some(node) = tree.get_node_mut(node_id) {
1902                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
1903                    node.get_mut_handlers()
1904                        .set_on_pointer_leave(Some(leave_handler));
1905                }
1906            },
1907            (),
1908        );
1909    }
1910
1911    /// Registers a keyboard key-down handler on `node_id` and marks it focusable.
1912    ///
1913    /// # Arguments
1914    ///
1915    /// - `&Self` - Build context.
1916    /// - `NodeId` - Target node handle.
1917    /// - `F` - Key-down callback closure receiving `UiEventKind::KeyDown`.
1918    pub fn on_key<F>(&mut self, node_id: NodeId, callback: F)
1919    where
1920        F: FnMut(&UiEvent) + 'static,
1921    {
1922        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
1923        self.get_scene().with_write(
1924            |tree: &mut SceneTree| {
1925                if let Some(node) = tree.get_node_mut(node_id) {
1926                    node.get_mut_handlers().set_on_key_down(Some(handler));
1927                    node.get_mut_interaction().set_focusable(true);
1928                }
1929            },
1930            (),
1931        );
1932    }
1933
1934    /// Records virtualized scroll progress on `node_id` so the overlay scrollbar tracks accurately.
1935    ///
1936    /// # Arguments
1937    ///
1938    /// - `&Self` - Build context.
1939    /// - `NodeId` - Target virtualized scroll container.
1940    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
1941    /// - `f32` - Full virtualized content height in logical pixels.
1942    pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
1943        self.get_scene()
1944            .set_virtual_scroll(node_id, scroll_y, content_height);
1945    }
1946
1947    /// Sets the concrete inner pixel scroll offset on `node_id` (used by virtualized lists for sub-pixel alignment).
1948    ///
1949    /// # Arguments
1950    ///
1951    /// - `&Self` - Build context.
1952    /// - `NodeId` - Target scroll container.
1953    /// - `Point` - Scroll offset `(x, y)` in logical pixels.
1954    pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
1955        self.get_scene().with_write(
1956            |tree: &mut SceneTree| {
1957                tree.set_scroll_offset(node_id, offset);
1958            },
1959            (),
1960        );
1961    }
1962
1963    /// Starts a smooth paint/transform transition on `transition.get_node()`.
1964    ///
1965    /// # Arguments
1966    ///
1967    /// - `&Self` - Build context.
1968    /// - `NodeTransition` - Transition specification.
1969    pub fn start_transition(&mut self, transition: NodeTransition) {
1970        self.get_scene().start_transition(transition);
1971    }
1972
1973    /// Mounts a reactive dynamic subtree whose children rebuild cleanly inside an isolated `Scope`.
1974    ///
1975    /// # Arguments
1976    ///
1977    /// - `&Self` - Build context.
1978    /// - `NodeId` - Host container node.
1979    /// - `F` - Reactive zero-`ctx` builder returning child `NodeId` values.
1980    pub fn bind_children<F>(&mut self, host: NodeId, mut builder: F)
1981    where
1982        F: FnMut() -> Vec<NodeId> + 'static,
1983    {
1984        let ctx_clone: Self = self.clone();
1985        let handle: SceneHandle = self.get_scene().clone();
1986        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1987            Effect::new(move || {
1988                let (child_scope, children): (Scope, Vec<NodeId>) =
1989                    Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
1990                let first_opt: Option<NodeId> = children.first().copied();
1991                handle.replace_children_safe(host, children);
1992                if let Some(first) = first_opt {
1993                    handle.with_write(
1994                        |tree: &mut SceneTree| {
1995                            tree.attach_scope(first, child_scope);
1996                        },
1997                        (),
1998                    );
1999                }
2000            })
2001        });
2002        self.get_scene().with_write(
2003            |tree: &mut SceneTree| {
2004                tree.attach_scope(host, scope);
2005            },
2006            (),
2007        );
2008    }
2009}
2010
2011/// Restores the previously bound ambient `Context` when leaving scope.
2012impl Drop for ContextGuard {
2013    /// Restores the saved thread-local `Context`.
2014    ///
2015    /// # Arguments
2016    ///
2017    /// - `&Self` - Mutable scope guard being dropped.
2018    fn drop(&mut self) {
2019        let Self { previous } = self;
2020        let restored: Option<Context> = previous.take();
2021        ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
2022            *slot.borrow_mut() = restored;
2023        });
2024    }
2025}
2026
2027/// `NodeRefTarget` implementation storing a `NodeId` directly into a mutable local binding.
2028impl NodeRefTarget for NodeId {
2029    /// Assigns `id` to `self`.
2030    ///
2031    /// # Arguments
2032    ///
2033    /// - `&Self` - Target `NodeId` slot.
2034    /// - `NodeId` - Mounted node handle.
2035    fn bind_node_ref(&mut self, id: NodeId) {
2036        *self = id;
2037    }
2038}
2039
2040/// `NodeRefTarget` implementation storing a `NodeId` into an `Option<NodeId>`.
2041impl NodeRefTarget for Option<NodeId> {
2042    /// Assigns `Some(id)` to `self`.
2043    ///
2044    /// # Arguments
2045    ///
2046    /// - `&Self` - Target optional `NodeId` slot.
2047    /// - `NodeId` - Mounted node handle.
2048    fn bind_node_ref(&mut self, id: NodeId) {
2049        *self = Some(id);
2050    }
2051}
2052
2053/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<NodeId>`.
2054impl NodeRefTarget for Cell<NodeId> {
2055    /// Sets `self` to `id`.
2056    ///
2057    /// # Arguments
2058    ///
2059    /// - `&Self` - Target `Cell<NodeId>`.
2060    /// - `NodeId` - Mounted node handle.
2061    fn bind_node_ref(&mut self, id: NodeId) {
2062        self.set(id);
2063    }
2064}
2065
2066/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<NodeId>>`.
2067impl NodeRefTarget for Rc<Cell<NodeId>> {
2068    /// Sets the shared cell value to `id`.
2069    ///
2070    /// # Arguments
2071    ///
2072    /// - `&Self` - Target shared `Cell<NodeId>`.
2073    /// - `NodeId` - Mounted node handle.
2074    fn bind_node_ref(&mut self, id: NodeId) {
2075        self.set(id);
2076    }
2077}
2078
2079/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<Option<NodeId>>`.
2080impl NodeRefTarget for Cell<Option<NodeId>> {
2081    /// Sets `self` to `Some(id)`.
2082    ///
2083    /// # Arguments
2084    ///
2085    /// - `&Self` - Target `Cell<Option<NodeId>>`.
2086    /// - `NodeId` - Mounted node handle.
2087    fn bind_node_ref(&mut self, id: NodeId) {
2088        self.set(Some(id));
2089    }
2090}
2091
2092/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<Option<NodeId>>>`.
2093impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
2094    /// Sets the shared cell value to `Some(id)`.
2095    ///
2096    /// # Arguments
2097    ///
2098    /// - `&Self` - Target shared `Cell<Option<NodeId>>`.
2099    /// - `NodeId` - Mounted node handle.
2100    fn bind_node_ref(&mut self, id: NodeId) {
2101        self.set(Some(id));
2102    }
2103}
2104
2105/// `TextNodeContent` implementation mounting an owned `String` as a static text node.
2106impl TextNodeContent for String {
2107    /// Mounts a static text scene node from this `String`.
2108    ///
2109    /// # Arguments
2110    ///
2111    /// - `Self` - Owned text string.
2112    /// - `&mut Context` - Active scene build context.
2113    /// - `Style` - Resolved text style.
2114    ///
2115    /// # Returns
2116    ///
2117    /// - `NodeId` - Mounted text node handle.
2118    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
2119        ctx.text(self, style)
2120    }
2121}
2122
2123/// `TextNodeContent` implementation mounting a string slice as a static text node.
2124impl TextNodeContent for &str {
2125    /// Mounts a static text scene node from this `&str`.
2126    ///
2127    /// # Arguments
2128    ///
2129    /// - `Self` - Borrowed text slice.
2130    /// - `&mut Context` - Active scene build context.
2131    /// - `Style` - Resolved text style.
2132    ///
2133    /// # Returns
2134    ///
2135    /// - `NodeId` - Mounted text node handle.
2136    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
2137        ctx.text(self.to_string(), style)
2138    }
2139}
2140
2141/// `TextNodeContent` implementation mounting a borrowed `&String` as a static text node.
2142impl TextNodeContent for &String {
2143    /// Mounts a static text scene node from this `&String`.
2144    ///
2145    /// # Arguments
2146    ///
2147    /// - `Self` - Borrowed string reference.
2148    /// - `&mut Context` - Active scene build context.
2149    /// - `Style` - Resolved text style.
2150    ///
2151    /// # Returns
2152    ///
2153    /// - `NodeId` - Mounted text node handle.
2154    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
2155        ctx.text(self.clone(), style)
2156    }
2157}
2158
2159/// `TextNodeContent` implementation mounting a `Cow<str>` as a static text node.
2160impl TextNodeContent for Cow<'_, str> {
2161    /// Mounts a static text scene node from this `Cow<str>`.
2162    ///
2163    /// # Arguments
2164    ///
2165    /// - `Self` - Copy-on-write string value.
2166    /// - `&mut Context` - Active scene build context.
2167    /// - `Style` - Resolved text style.
2168    ///
2169    /// # Returns
2170    ///
2171    /// - `NodeId` - Mounted text node handle.
2172    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
2173        ctx.text(self.into_owned(), style)
2174    }
2175}
2176
2177/// `TextNodeContent` implementation mounting any `FnMut() -> S` closure or function item as a reactive text node.
2178impl<F, S> TextNodeContent for F
2179where
2180    F: FnMut() -> S + 'static,
2181    S: Into<String>,
2182{
2183    /// Mounts a reactive text scene node bound to this closure or function item.
2184    ///
2185    /// # Arguments
2186    ///
2187    /// - `Self` - Reactive text producer closure.
2188    /// - `&mut Context` - Active scene build context.
2189    /// - `Style` - Resolved text style.
2190    ///
2191    /// # Returns
2192    ///
2193    /// - `NodeId` - Mounted reactive text node handle.
2194    fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
2195        ctx.reactive_text(style, move || self().into())
2196    }
2197}