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            live_count: 1,
20            root: NodeId::new(0, 1),
21            focus: FocusManager::default(),
22            revision: 1,
23            transitions: Vec::new(),
24            caret_visible: true,
25            portal_nodes: Vec::new(),
26            dirty_paint_nodes: Vec::new(),
27            full_damage_pending: true,
28            layout_damage_pending: true,
29            full_damage_overflow: false,
30            created_since_damage: 0,
31            extra_logical_damage: Vec::new(),
32            text_selection: None,
33        }
34    }
35}
36
37/// Core retained scene graph mutation and traversal operations.
38impl SceneTree {
39    /// Returns the incrementally maintained slice of live `NodeKind::Portal` and `Position::Fixed` nodes.
40    ///
41    /// # Arguments
42    ///
43    /// - `&Self` - Scene tree reference.
44    ///
45    /// # Returns
46    ///
47    /// - `&[NodeId]` - Live top-layer portal and fixed-position node handles.
48    #[must_use]
49    #[inline(always)]
50    pub fn portal_nodes(&self) -> &[NodeId] {
51        let Self { portal_nodes, .. } = self;
52        portal_nodes.as_slice()
53    }
54
55    /// Returns `true` when at least one live `NodeKind::Portal` or `Position::Fixed` node is registered.
56    ///
57    /// # Arguments
58    ///
59    /// - `&Self` - Scene tree reference.
60    ///
61    /// # Returns
62    ///
63    /// - `bool` - Whether any top-layer portal or fixed node exists in the scene.
64    #[must_use]
65    #[inline(always)]
66    pub fn has_portal_nodes(&self) -> bool {
67        let Self { portal_nodes, .. } = self;
68        !portal_nodes.is_empty()
69    }
70
71    /// Synchronizes `id` membership in `portal_nodes` whenever a top-layer node is created, mutated, or disposed.
72    ///
73    /// # Arguments
74    ///
75    /// - `&Self` - Mutable scene tree.
76    /// - `NodeId` - Target node handle.
77    /// - `bool` - Whether the node currently qualifies as a `Portal` or `Position::Fixed` top-layer node.
78    fn sync_portal_registration(&mut self, id: NodeId, is_portal: bool) {
79        let portals: &mut Vec<NodeId> = self.get_mut_portal_nodes();
80        if is_portal {
81            if !portals.contains(&id) {
82                portals.push(id);
83            }
84        } else if !portals.is_empty() {
85            portals.retain(|existing: &NodeId| *existing != id);
86        }
87    }
88
89    /// Allocates a new node of `kind` with initial `style`.
90    ///
91    /// # Arguments
92    ///
93    /// - `&Self` - Mutable scene tree.
94    /// - `NodeKind` - Semantic node kind.
95    /// - `Style` - Initial style.
96    ///
97    /// # Returns
98    ///
99    /// - `NodeId` - Generation-checked node handle.
100    pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
101        let is_portal: bool = matches!(kind, NodeKind::Portal)
102            || style.get_layout().get_position() == Position::Fixed;
103        let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
104            let slot: &mut SceneNode = &mut self.get_mut_nodes()[index as usize];
105            let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
106            *slot = SceneNode::new(next_gen, kind, style);
107            NodeId::new(index, next_gen)
108        } else {
109            let index: u32 = self.get_nodes().len() as u32;
110            self.get_mut_nodes().push(SceneNode::new(1, kind, style));
111            NodeId::new(index, 1)
112        };
113        if is_portal {
114            self.get_mut_portal_nodes().push(id);
115            self.set_full_damage_pending(true);
116        }
117        let next_live: usize = self.get_live_count().saturating_add(1);
118        self.set_live_count(next_live);
119        let next_created: usize = self.get_created_since_damage().saturating_add(1);
120        self.set_created_since_damage(next_created);
121        self.set_layout_damage_pending(true);
122        if next_created > DIRTY_PAINT_FULL_THRESHOLD {
123            self.set_full_damage_pending(true);
124            self.set_full_damage_overflow(true);
125        }
126        let next_rev: u64 = self.get_revision().wrapping_add(1);
127        self.set_revision(next_rev);
128        id
129    }
130
131    /// Creates a container `View` node.
132    ///
133    /// # Arguments
134    ///
135    /// - `&Self` - Mutable scene tree.
136    /// - `Style` - Initial box style.
137    ///
138    /// # Returns
139    ///
140    /// - `NodeId` - Created node handle.
141    pub fn create_view(&mut self, style: Style) -> NodeId {
142        self.create_node(NodeKind::View, style)
143    }
144
145    /// Creates a `Text` node holding `content`.
146    ///
147    /// # Arguments
148    ///
149    /// - `&Self` - Mutable scene tree.
150    /// - `String` - Initial UTF-8 text.
151    /// - `Style` - Initial text and box style.
152    ///
153    /// # Returns
154    ///
155    /// - `NodeId` - Created text node handle.
156    pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
157        self.create_node(NodeKind::Text(content), style)
158    }
159
160    /// Creates an editable `Input` node.
161    ///
162    /// # Arguments
163    ///
164    /// - `&Self` - Mutable scene tree.
165    /// - `InputNodeState` - Initial input state.
166    /// - `Style` - Initial input style.
167    ///
168    /// # Returns
169    ///
170    /// - `NodeId` - Created input node handle.
171    pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
172        self.create_node(NodeKind::Input(state), style)
173    }
174
175    /// Creates an `Image` node displaying `buffer`.
176    ///
177    /// # Arguments
178    ///
179    /// - `&Self` - Mutable scene tree.
180    /// - `ImageBuffer` - Decoded RGBA8 image buffer.
181    /// - `Style` - Initial image style.
182    ///
183    /// # Returns
184    ///
185    /// - `NodeId` - Created image node handle.
186    pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
187        self.create_node(NodeKind::Image(buffer), style)
188    }
189
190    /// Creates a `ScrollView` container with `Overflow::Scroll`.
191    ///
192    /// # Arguments
193    ///
194    /// - `&Self` - Mutable scene tree.
195    /// - `Style` - Initial scroll container style.
196    ///
197    /// # Returns
198    ///
199    /// - `NodeId` - Created scroll view handle.
200    pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
201        self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
202    }
203
204    /// Creates a custom `Canvas` node bound to `painter`.
205    ///
206    /// # Arguments
207    ///
208    /// - `&Self` - Mutable scene tree.
209    /// - `Style` - Initial canvas style.
210    /// - `CanvasDrawCallback` - Draw callback invoked on each paint pass.
211    ///
212    /// # Returns
213    ///
214    /// - `NodeId` - Created canvas node handle.
215    pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
216        let id: NodeId = self.create_node(NodeKind::Canvas, style);
217        if let Some(node) = self.get_node_mut(id) {
218            node.set_canvas_painter(Some(painter));
219        }
220        id
221    }
222
223    /// Creates an overlay `Portal` node rendered in the top stacking context.
224    ///
225    /// # Arguments
226    ///
227    /// - `&Self` - Mutable scene tree.
228    /// - `Style` - Initial portal style.
229    ///
230    /// # Returns
231    ///
232    /// - `NodeId` - Created portal node handle.
233    pub fn create_portal(&mut self, style: Style) -> NodeId {
234        self.create_node(NodeKind::Portal, style)
235    }
236
237    /// Creates a logical `Fragment` grouping node.
238    ///
239    /// # Arguments
240    ///
241    /// - `&Self` - Mutable scene tree.
242    ///
243    /// # Returns
244    ///
245    /// - `NodeId` - Created fragment node handle.
246    pub fn create_fragment(&mut self) -> NodeId {
247        self.create_node(NodeKind::Fragment, Style::default())
248    }
249
250    /// Returns an immutable reference to a live node matching `id`.
251    ///
252    /// # Arguments
253    ///
254    /// - `&Self` - Scene tree reference.
255    /// - `NodeId` - Node handle.
256    ///
257    /// # Returns
258    ///
259    /// - `Option<&SceneNode>` - Live node reference if valid.
260    #[must_use]
261    pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
262        let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
263        if node.get_alive() && node.get_generation() == id.get_generation() {
264            Some(node)
265        } else {
266            None
267        }
268    }
269
270    /// Returns a mutable reference to a live node matching `id`.
271    ///
272    /// # Arguments
273    ///
274    /// - `&Self` - Mutable scene tree.
275    /// - `NodeId` - Node handle.
276    ///
277    /// # Returns
278    ///
279    /// - `Option<&mut SceneNode>` - Mutable live node reference if valid.
280    pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
281        let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
282        if node.get_alive() && node.get_generation() == id.get_generation() {
283            Some(node)
284        } else {
285            None
286        }
287    }
288
289    /// Returns total count of live scene nodes in O(1).
290    ///
291    /// # Arguments
292    ///
293    /// - `&Self` - Scene tree reference.
294    ///
295    /// # Returns
296    ///
297    /// - `usize` - Number of live nodes in the arena.
298    #[must_use]
299    #[inline(always)]
300    pub fn live_node_count(&self) -> usize {
301        self.get_live_count()
302    }
303
304    /// Appends `child` to `parent` and marks layout and paint dirty upward.
305    ///
306    /// # Arguments
307    ///
308    /// - `&Self` - Mutable scene tree.
309    /// - `NodeId` - Parent container node.
310    /// - `NodeId` - Child node to attach.
311    pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
312        if parent == child {
313            return;
314        }
315        let prev_parent: Option<NodeId> = self.get_node(child).and_then(SceneNode::parent_id);
316        if let Some(old_parent) = prev_parent {
317            if old_parent != parent {
318                self.record_subtree_logical_damage(child);
319            }
320            if let Some(old_node) = self.get_node_mut(old_parent) {
321                old_node
322                    .get_mut_children()
323                    .retain(|item: &NodeId| *item != child);
324                if old_parent != parent {
325                    self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
326                }
327            }
328        }
329        if let Some(child_node) = self.get_node_mut(child) {
330            child_node.set_parent(Some(parent));
331        } else {
332            return;
333        }
334        if let Some(parent_node) = self.get_node_mut(parent) {
335            parent_node.get_mut_children().push(child);
336        }
337        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
338    }
339
340    /// Appends multiple `children` to `parent` in a single dirty-marking pass with zero-alloc fresh-orphan fast path.
341    ///
342    /// # Arguments
343    ///
344    /// - `&Self` - Mutable scene tree.
345    /// - `NodeId` - Parent container node.
346    /// - `&[NodeId]` - Ordered child nodes to append.
347    pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
348        if children.is_empty() || self.get_node(parent).is_none() {
349            return;
350        }
351        let all_fresh_orphans: bool = children.iter().copied().all(|child: NodeId| {
352            child != parent
353                && self
354                    .get_node(child)
355                    .is_some_and(|node: &SceneNode| node.parent_id().is_none())
356        });
357        if all_fresh_orphans {
358            for child in children.iter().copied() {
359                if let Some(child_node) = self.get_node_mut(child) {
360                    child_node.set_parent(Some(parent));
361                }
362            }
363            if let Some(parent_node) = self.get_node_mut(parent) {
364                parent_node.get_mut_children().extend_from_slice(children);
365            }
366            self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
367            return;
368        }
369        let mut attached: Vec<NodeId> = Vec::with_capacity(children.len());
370        for child in children.iter().copied() {
371            if child == parent {
372                continue;
373            }
374            let prev_parent: Option<NodeId> = self
375                .get_node(child)
376                .and_then(|node: &SceneNode| node.parent_id());
377            if let Some(old_parent) = prev_parent {
378                if old_parent != parent {
379                    self.record_subtree_logical_damage(child);
380                }
381                if let Some(old_node) = self.get_node_mut(old_parent) {
382                    old_node
383                        .get_mut_children()
384                        .retain(|id: &NodeId| *id != child);
385                }
386                if old_parent != parent {
387                    self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
388                }
389            }
390            if let Some(child_node) = self.get_node_mut(child) {
391                child_node.set_parent(Some(parent));
392                attached.push(child);
393            }
394        }
395        if attached.is_empty() {
396            return;
397        }
398        if let Some(parent_node) = self.get_node_mut(parent) {
399            parent_node.get_mut_children().extend(attached);
400        }
401        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
402    }
403
404    /// Replaces all children of `parent` with `new_children`, disposing previous subtrees cleanly.
405    ///
406    /// # Arguments
407    ///
408    /// - `&Self` - Mutable scene tree.
409    /// - `NodeId` - Parent container node.
410    /// - `Vec<NodeId>` - Replacement ordered children.
411    pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
412        let old_children: Vec<NodeId> = match self.get_node_mut(parent) {
413            Some(node) => take(node.get_mut_children()),
414            None => return,
415        };
416        if new_children.is_empty() {
417            for old_child in old_children.into_iter() {
418                self.dispose_subtree(old_child);
419            }
420        } else if old_children.len() > 16 && new_children.len() > 16 {
421            let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
422            for old_child in old_children.into_iter() {
423                if !keep_set.contains(&old_child) {
424                    self.dispose_subtree(old_child);
425                }
426            }
427        } else {
428            for old_child in old_children.into_iter() {
429                if !new_children.contains(&old_child) {
430                    self.dispose_subtree(old_child);
431                }
432            }
433        }
434        for child in new_children.iter().copied() {
435            if let Some(child_node) = self.get_node_mut(child) {
436                child_node.set_parent(Some(parent));
437            }
438        }
439        if let Some(parent_node) = self.get_node_mut(parent) {
440            parent_node.set_children(new_children);
441        }
442        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
443    }
444
445    /// Computes the minimal dirty bitmask and optional portal update comparing `prev` and `next` styles by reference.
446    ///
447    /// # Arguments
448    ///
449    /// - `&Style` - Previous compiled style reference.
450    /// - `&Style` - Candidate replacement style reference.
451    /// - `bool` - Whether the target node is already `NodeKind::Portal`.
452    ///
453    /// # Returns
454    ///
455    /// - `(u16, Option<bool>)` - Tuple `(dirty_mask, portal_update)`; `dirty_mask == DIRTY_NONE` on no-op writes.
456    #[inline]
457    fn diff_style_change(prev: &Style, next: &Style, is_portal_kind: bool) -> (u16, Option<bool>) {
458        let layout_changed: bool = prev.layout_ref() != next.layout_ref();
459        let text_metrics_changed: bool = !prev.text_ref().same_layout_metrics(next.text_ref());
460        if layout_changed || text_metrics_changed {
461            let prev_fixed: bool = prev.layout_ref().get_position() == Position::Fixed;
462            let next_fixed: bool = next.layout_ref().get_position() == Position::Fixed;
463            let portal_update: Option<bool> = if !is_portal_kind && prev_fixed != next_fixed {
464                Some(next_fixed)
465            } else {
466                None
467            };
468            let layout_bits: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
469            let visual_bits: u16 = DIRTY_TEXT | DIRTY_PAINT;
470            let mask: u16 = layout_bits | visual_bits;
471            return (mask, portal_update);
472        }
473        let paint_changed: bool = prev.paint_ref() != next.paint_ref();
474        let text_visual_changed: bool = prev.text_ref() != next.text_ref();
475        if paint_changed || text_visual_changed {
476            (DIRTY_PAINT, None)
477        } else {
478            (DIRTY_NONE, None)
479        }
480    }
481
482    /// Returns `true` when transitioning from `prev` to `next` paint style can shrink shadows, borders, transforms, or hide children.
483    ///
484    /// # Arguments
485    ///
486    /// - `&PaintStyle` - Previous paint style reference.
487    /// - `&PaintStyle` - Replacement paint style reference.
488    ///
489    /// # Returns
490    ///
491    /// - `bool` - Whether the node's pre-mutation conservative bounds must be snapshotted before overwriting style.
492    #[inline]
493    fn needs_pre_paint_damage(prev: &PaintStyle, next: &PaintStyle) -> bool {
494        let shadow_changed: bool = prev.box_shadow() != next.box_shadow();
495        let transform_changed: bool = prev.get_transform() != next.get_transform();
496        let border_shrank: bool = prev.get_border().get_width() > next.get_border().get_width();
497        let focus_removed: bool =
498            prev.focus_ring_border().is_some() && next.focus_ring_border().is_none();
499        let opacity_toggled_zero: bool = (prev.get_opacity() > 0.0) != (next.get_opacity() > 0.0);
500        let a: bool = shadow_changed || transform_changed;
501        let b: bool = border_shrank || focus_removed;
502        let ab: bool = a || b;
503        ab || opacity_toggled_zero
504    }
505
506    /// Surgically updates a node's `Style`, marking only `DIRTY_PAINT` for pure paint changes and skipping no-op writes.
507    ///
508    /// # Arguments
509    ///
510    /// - `&Self` - Mutable scene tree.
511    /// - `NodeId` - Target node handle.
512    /// - `Style` - Replacement compiled style.
513    pub fn set_style(&mut self, id: NodeId, style: Style) {
514        let pre_snapshot: Option<(u16, Option<bool>, bool, bool)> =
515            self.get_node(id).map(|node: &SceneNode| {
516                let is_portal_kind: bool = matches!(node.get_kind(), NodeKind::Portal);
517                let prev: &Style = node.style_ref();
518                let (mask, update): (u16, Option<bool>) =
519                    Self::diff_style_change(prev, &style, is_portal_kind);
520                let pre_paint: bool = mask != DIRTY_NONE
521                    && Self::needs_pre_paint_damage(prev.paint_ref(), style.paint_ref());
522                let subtree_hidden: bool = pre_paint
523                    && (prev.paint_ref().get_opacity() > 0.0)
524                        != (style.paint_ref().get_opacity() > 0.0)
525                    && !node.get_children().is_empty();
526                (mask, update, pre_paint, subtree_hidden)
527            });
528        let Some((dirty_mask, portal_update, pre_paint, subtree_hidden)) = pre_snapshot else {
529            return;
530        };
531        if dirty_mask == DIRTY_NONE {
532            return;
533        }
534        if subtree_hidden {
535            self.record_subtree_logical_damage(id);
536        } else if pre_paint {
537            self.record_node_logical_damage(id);
538        }
539        if let Some(node) = self.get_node_mut(id) {
540            node.set_style(style);
541        }
542        if let Some(is_portal) = portal_update {
543            self.sync_portal_registration(id, is_portal);
544        }
545        self.mark_dirty(id, dirty_mask);
546    }
547
548    /// Mutates a node's `Style` in place and marks the minimal dirty mask (`DIRTY_PAINT` vs layout) only if changed.
549    ///
550    /// # Arguments
551    ///
552    /// - `&Self` - Mutable scene tree.
553    /// - `NodeId` - Target node handle.
554    /// - `F` - In-place style mutator closure receiving `&mut Style`.
555    ///
556    /// # Returns
557    ///
558    /// - `bool` - `true` when the node existed and its style changed.
559    pub fn mutate_style<F>(&mut self, id: NodeId, mutator: F) -> bool
560    where
561        F: FnOnce(&mut Style),
562    {
563        let prev_opt: Option<(Style, bool, bool)> = self.get_node(id).map(|node: &SceneNode| {
564            (
565                *node.style_ref(),
566                matches!(node.get_kind(), NodeKind::Portal),
567                !node.get_children().is_empty(),
568            )
569        });
570        let Some((prev, is_portal_kind, has_children)) = prev_opt else {
571            return false;
572        };
573        let mut next: Style = prev;
574        mutator(&mut next);
575        let (dirty_mask, portal_update): (u16, Option<bool>) =
576            Self::diff_style_change(&prev, &next, is_portal_kind);
577        if dirty_mask == DIRTY_NONE {
578            return false;
579        }
580        let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), next.paint_ref());
581        if pre_paint {
582            let opacity_toggled_zero: bool =
583                (prev.paint_ref().get_opacity() > 0.0) != (next.paint_ref().get_opacity() > 0.0);
584            if opacity_toggled_zero && has_children {
585                self.record_subtree_logical_damage(id);
586            } else {
587                self.record_node_logical_damage(id);
588            }
589        }
590        if let Some(node) = self.get_node_mut(id) {
591            node.set_style(next);
592        }
593        if let Some(is_portal) = portal_update {
594            self.sync_portal_registration(id, is_portal);
595        }
596        self.mark_dirty(id, dirty_mask);
597        true
598    }
599
600    /// Surgically updates the UTF-8 string of a `NodeKind::Text` node.
601    ///
602    /// # Arguments
603    ///
604    /// - `&Self` - Mutable scene tree.
605    /// - `NodeId` - Target text node handle.
606    /// - `String` - Replacement text string.
607    pub fn set_text(&mut self, id: NodeId, text: String) {
608        let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
609            Some(node) => {
610                let layout: &LayoutStyle = node.style_ref().layout_ref();
611                let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
612                    && matches!(layout.get_height(), Length::Px(_));
613                match node.get_mut_kind() {
614                    NodeKind::Text(current) => {
615                        if *current == text {
616                            (false, has_fixed)
617                        } else {
618                            *current = text;
619                            (true, has_fixed)
620                        }
621                    }
622                    _ => (false, false),
623                }
624            }
625            None => (false, false),
626        };
627        if changed {
628            let mask: u16 = if fixed_size {
629                DIRTY_PAINT
630            } else {
631                DIRTY_TEXT_CHANGE_MASK
632            };
633            self.mark_dirty(id, mask);
634        }
635    }
636
637    /// Updates scroll offset on a scroll container without triggering full subtree re-layout.
638    ///
639    /// # Arguments
640    ///
641    /// - `&Self` - Mutable scene tree.
642    /// - `NodeId` - Target scroll container handle.
643    /// - `Point` - New scroll offset clamped to content bounds.
644    pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
645        let changed: bool = match self.get_node_mut(id) {
646            Some(node) => {
647                let layout_box: LayoutBox = node.get_layout_box();
648                let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
649                    && layout_box.get_content_size().get_height() <= 0.0
650                    && layout_box.get_content_bounds().get_width() <= 0.0
651                    && layout_box.get_content_bounds().get_height() <= 0.0;
652                let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
653                    Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
654                } else {
655                    let max_x: f32 = (layout_box.get_content_size().get_width()
656                        - layout_box.get_content_bounds().get_width())
657                    .max(0.0);
658                    let max_y: f32 = (layout_box.get_content_size().get_height()
659                        - layout_box.get_content_bounds().get_height())
660                    .max(0.0);
661                    Point::new(
662                        offset.get_x().clamp(0.0, max_x),
663                        offset.get_y().clamp(0.0, max_y),
664                    )
665                };
666                if layout_box.get_scroll_offset() == clamped {
667                    false
668                } else {
669                    node.get_mut_layout_box().set_scroll_offset(clamped);
670                    true
671                }
672            }
673            None => false,
674        };
675        if changed {
676            self.mark_dirty(id, DIRTY_SCROLL | DIRTY_PAINT);
677        }
678    }
679
680    /// Records virtualized scroll progress `(scroll_y, content_height)` on `id` for overlay scrollbar rendering.
681    ///
682    /// # Arguments
683    ///
684    /// - `&Self` - Mutable scene tree.
685    /// - `NodeId` - Target virtualized scroll container.
686    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
687    /// - `f32` - Full virtualized content height in logical pixels.
688    pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
689        let changed: bool = match self.get_node_mut(id) {
690            Some(node) => {
691                let next: Option<(f32, f32)> = Some((scroll_y.max(0.0), content_height.max(1.0)));
692                if node.virtual_scroll_metrics() == next {
693                    false
694                } else {
695                    node.set_virtual_scroll(next);
696                    true
697                }
698            }
699            None => false,
700        };
701        if changed {
702            self.mark_dirty(id, DIRTY_SCROLL | DIRTY_PAINT);
703        }
704    }
705
706    /// Computes screen-space logical bounds for `id` after applying ancestor scroll offsets and transforms.
707    ///
708    /// # Arguments
709    ///
710    /// - `&Self` - Scene tree reference.
711    /// - `NodeId` - Target node handle.
712    ///
713    /// # Returns
714    ///
715    /// - `Option<Rect>` - Screen-space rectangle if the node is alive.
716    #[must_use]
717    pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
718        let node: &SceneNode = self.get_node(id)?;
719        let raw: Rect = node.get_layout_box().get_bounds();
720        let (off, tx, ty, sx, sy): (Point, f32, f32, f32, f32) =
721            self.node_scroll_and_transform(node);
722        Some(Rect::new(
723            raw.get_x() - off.get_x() + tx,
724            raw.get_y() - off.get_y() + ty,
725            raw.get_width() * sx,
726            raw.get_height() * sy,
727        ))
728    }
729
730    /// Computes accumulated ancestor scroll offset and combined 2D transform for `node` in a single ancestor walk.
731    ///
732    /// # Arguments
733    ///
734    /// - `&Self` - Scene tree reference.
735    /// - `&SceneNode` - Borrowed target scene node.
736    ///
737    /// # Returns
738    ///
739    /// - `(Point, f32, f32, f32, f32)` - Tuple `(scroll_offset, tx, ty, scale_x, scale_y)`.
740    #[inline]
741    fn node_scroll_and_transform(&self, node: &SceneNode) -> (Point, f32, f32, f32, f32) {
742        let style: &Style = node.style_ref();
743        let tr: Transform2D = style.get_paint().get_transform();
744        let mut tx: f32 = tr.get_translate_x();
745        let mut ty: f32 = tr.get_translate_y();
746        let sx_scale: f32 = tr.get_scale_x();
747        let sy_scale: f32 = tr.get_scale_y();
748        let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
749            || style.get_layout().get_position() == Position::Fixed;
750        let mut scroll_x: f32 = 0.0;
751        let mut scroll_y: f32 = 0.0;
752        let mut cursor: Option<NodeId> = node.parent_id();
753        while let Some(pid) = cursor {
754            if let Some(pnode) = self.get_node(pid) {
755                let pstyle: &Style = pnode.style_ref();
756                let ptr: Transform2D = pstyle.get_paint().get_transform();
757                tx += ptr.get_translate_x();
758                ty += ptr.get_translate_y();
759                if !start_top_layer {
760                    let off: Point = pnode.get_layout_box().get_scroll_offset();
761                    scroll_x += off.get_x();
762                    scroll_y += off.get_y();
763                }
764                let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
765                    || pstyle.get_layout().get_position() == Position::Fixed;
766                if parent_top_layer {
767                    break;
768                }
769                cursor = pnode.parent_id();
770            } else {
771                break;
772            }
773        }
774        (Point::new(scroll_x, scroll_y), tx, ty, sx_scale, sy_scale)
775    }
776
777    /// Computes a conservative logical screen-space paint rectangle for `id` including ancestor scroll, transform, border, focus ring, and `3 * sigma` shadow halo.
778    ///
779    /// Returns `None` when a non-axis-aligned rotation or ancestor scale requires a safe full-viewport fallback.
780    ///
781    /// # Arguments
782    ///
783    /// - `&Self` - Scene tree reference.
784    /// - `NodeId` - Target scene node handle.
785    ///
786    /// # Returns
787    ///
788    /// - `Option<Rect>` - Conservative logical screen bounds, `Some(Rect::default())` when unmeasured, or `None` for unsafe fallback.
789    #[must_use]
790    pub(crate) fn node_conservative_logical_rect(&self, id: NodeId) -> Option<Rect> {
791        let node: &SceneNode = self.get_node(id)?;
792        let raw_bounds: Rect = node.get_layout_box().get_bounds();
793        if raw_bounds.get_width() <= 0.0 || raw_bounds.get_height() <= 0.0 {
794            return Some(Rect::default());
795        }
796        let style: &Style = node.style_ref();
797        let paint: &PaintStyle = style.paint_ref();
798        let tr: Transform2D = paint.get_transform();
799        if tr.get_rotation_rad().abs() > 0.0001
800            || tr.get_scale_x() <= 0.0
801            || tr.get_scale_y() <= 0.0
802        {
803            return None;
804        }
805        let mut tx: f32 = tr.get_translate_x();
806        let mut ty: f32 = tr.get_translate_y();
807        let sx: f32 = tr.get_scale_x();
808        let sy: f32 = tr.get_scale_y();
809        let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
810            || style.layout_ref().get_position() == Position::Fixed;
811        let mut scroll_x: f32 = 0.0;
812        let mut scroll_y: f32 = 0.0;
813        let mut cursor: Option<NodeId> = node.parent_id();
814        while let Some(pid) = cursor {
815            let Some(pnode) = self.get_node(pid) else {
816                break;
817            };
818            let pstyle: &Style = pnode.style_ref();
819            let ptr: Transform2D = pstyle.paint_ref().get_transform();
820            if ptr.get_rotation_rad().abs() > 0.0001
821                || (ptr.get_scale_x() - 1.0).abs() > 0.001
822                || (ptr.get_scale_y() - 1.0).abs() > 0.001
823            {
824                return None;
825            }
826            tx += ptr.get_translate_x();
827            ty += ptr.get_translate_y();
828            if !start_top_layer {
829                let off: Point = pnode.get_layout_box().get_scroll_offset();
830                scroll_x += off.get_x();
831                scroll_y += off.get_y();
832            }
833            let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
834                || pstyle.layout_ref().get_position() == Position::Fixed;
835            if parent_top_layer {
836                break;
837            }
838            cursor = pnode.parent_id();
839        }
840        let border_w: f32 = paint.get_border().get_width();
841        let focus_pad: f32 = if paint.focus_ring_border().is_some() {
842            12.0
843        } else {
844            0.0
845        };
846        let mut margin: f32 = 10.0_f32.max(border_w + 6.0).max(focus_pad);
847        if let Some(shadow) = paint.box_shadow() {
848            let blur_pad: f32 = (shadow.get_blur_radius().max(0.5) * 1.5).min(96.0) + 4.0;
849            let spread: f32 = shadow.get_spread_radius().max(0.0);
850            let off_max: f32 = shadow.get_offset_x().abs().max(shadow.get_offset_y().abs());
851            margin = margin.max(blur_pad + spread + off_max + 4.0);
852        }
853        let base_x: f32 = raw_bounds.get_x() - scroll_x;
854        let base_y: f32 = raw_bounds.get_y() - scroll_y;
855        let base_rect: Rect = Rect::new(
856            base_x - margin,
857            base_y - margin,
858            raw_bounds.get_width() + margin * 2.0,
859            raw_bounds.get_height() + margin * 2.0,
860        );
861        let shifted_x: bool = tx != 0.0 || sx != 1.0;
862        let shifted_y: bool = ty != 0.0 || sy != 1.0;
863        if shifted_x || shifted_y {
864            let scale_pad_x: f32 = ((sx - 1.0).abs() * raw_bounds.get_width()).max(0.0);
865            let scale_pad_y: f32 = ((sy - 1.0).abs() * raw_bounds.get_height()).max(0.0);
866            let shifted_rect: Rect = Rect::new(
867                base_x + tx - margin - scale_pad_x,
868                base_y + ty - margin - scale_pad_y,
869                raw_bounds.get_width() * sx + (margin + scale_pad_x) * 2.0,
870                raw_bounds.get_height() * sy + (margin + scale_pad_y) * 2.0,
871            );
872            Some(base_rect.union(shifted_rect))
873        } else {
874            Some(base_rect)
875        }
876    }
877
878    /// Converts a conservative logical screen rectangle into an exact outward-rounded physical pixel rectangle.
879    ///
880    /// # Arguments
881    ///
882    /// - `Rect` - Conservative logical screen rectangle.
883    /// - `f32` - Active display scale factor.
884    ///
885    /// # Returns
886    ///
887    /// - `Rect` - Physical pixel rectangle guaranteed to enclose all covered pixels.
888    #[must_use]
889    pub(crate) fn scale_logical_to_phys_rect(logical: Rect, scale: f32) -> Rect {
890        let x0: f32 = (logical.get_x() * scale).floor();
891        let y0: f32 = (logical.get_y() * scale).floor();
892        let x1: f32 = (logical.right() * scale).ceil();
893        let y1: f32 = (logical.bottom() * scale).ceil();
894        Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
895    }
896
897    /// Records the current conservative logical bounds of `id` into `extra_logical_damage` prior to destructive mutation.
898    ///
899    /// # Arguments
900    ///
901    /// - `&Self` - Mutable scene tree.
902    /// - `NodeId` - Target scene node handle.
903    fn record_node_logical_damage(&mut self, id: NodeId) {
904        if self.get_full_damage_pending() {
905            return;
906        }
907        let rect_opt: Option<Rect> = self.node_conservative_logical_rect(id);
908        match rect_opt {
909            Some(rect) => {
910                if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
911                    return;
912                }
913                if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
914                    self.set_full_damage_pending(true);
915                    self.set_full_damage_overflow(true);
916                    self.get_mut_extra_logical_damage().clear();
917                } else {
918                    self.get_mut_extra_logical_damage().push(rect);
919                }
920            }
921            None => {
922                self.set_full_damage_pending(true);
923            }
924        }
925    }
926
927    /// Records pre-mutation conservative logical bounds for every live laid-out node in the subtree rooted at `root`.
928    ///
929    /// # Arguments
930    ///
931    /// - `&Self` - Mutable scene tree.
932    /// - `NodeId` - Subtree root handle.
933    fn record_subtree_logical_damage(&mut self, root: NodeId) {
934        if self.get_full_damage_pending() {
935            return;
936        }
937        let mut stack: Vec<NodeId> = vec![root];
938        let mut visited: usize = 0;
939        while let Some(current) = stack.pop() {
940            let Some(node) = self.get_node(current) else {
941                continue;
942            };
943            visited += 1;
944            if visited > DIRTY_PAINT_FULL_THRESHOLD {
945                self.set_full_damage_pending(true);
946                self.set_full_damage_overflow(true);
947                self.get_mut_extra_logical_damage().clear();
948                return;
949            }
950            let children: Vec<NodeId> = node.get_children().clone();
951            let raw_bounds: Rect = node.get_layout_box().get_bounds();
952            if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
953                self.record_node_logical_damage(current);
954                if self.get_full_damage_pending() {
955                    return;
956                }
957            }
958            for child in children.into_iter() {
959                stack.push(child);
960            }
961        }
962    }
963
964    /// Starts or smoothly retargets a paint/transform transition on `transition.get_node()`.
965    ///
966    /// # Arguments
967    ///
968    /// - `&Self` - Mutable scene tree.
969    /// - `NodeTransition` - Transition specification to run.
970    pub fn start_transition(&mut self, mut transition: NodeTransition) {
971        let target: NodeId = transition.get_node();
972        let had_active: bool = self
973            .get_transitions()
974            .iter()
975            .any(|tr: &NodeTransition| tr.get_node() == target);
976        self.get_mut_transitions()
977            .retain(|tr: &NodeTransition| tr.get_node() != target);
978        if had_active && let Some(node) = self.get_node(target) {
979            let paint: PaintStyle = node.get_style().get_paint();
980            let tr: Transform2D = paint.get_transform();
981            let cur_op: f32 = paint.get_opacity();
982            let cur_tx: f32 = tr.get_translate_x();
983            let cur_ty: f32 = tr.get_translate_y();
984            let cur_sc: f32 = tr.get_scale_x();
985            let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
986                .hypot(transition.get_to_ty() - transition.get_from_ty())
987                .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
988            let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
989                .hypot(transition.get_to_ty() - cur_ty)
990                .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
991            if full_dist > 0.01 {
992                let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
993                transition.set_duration((transition.get_duration() * ratio).max(0.05));
994            }
995            transition.set_from_opacity(cur_op);
996            transition.set_from_tx(cur_tx);
997            transition.set_from_ty(cur_ty);
998            transition.set_from_scale(cur_sc);
999        }
1000        let (opacity, transform): (f32, Transform2D) = transition.sample();
1001        let mut unhidden: bool = false;
1002        if let Some(node) = self.get_node_mut(target) {
1003            let style: &mut Style = node.get_mut_style();
1004            if !transition.get_hide_on_complete()
1005                && style.layout_ref().get_display() == Display::None
1006            {
1007                style.get_mut_layout().set_display(Display::Flex);
1008                unhidden = true;
1009            }
1010            style.get_mut_paint().set_opacity(opacity);
1011            style.get_mut_paint().set_transform(transform);
1012        }
1013        if unhidden {
1014            let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1015            self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
1016        } else {
1017            self.mark_dirty(target, DIRTY_PAINT);
1018        }
1019        self.get_mut_transitions().push(transition);
1020    }
1021
1022    /// Advances all active transitions by `dt_secs` and returns `true` if any node updated.
1023    ///
1024    /// # Arguments
1025    ///
1026    /// - `&Self` - Mutable scene tree.
1027    /// - `f32` - Elapsed frame time in seconds.
1028    ///
1029    /// # Returns
1030    ///
1031    /// - `bool` - Whether at least one transition ticked on this frame.
1032    pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
1033        let len: usize = self.get_transitions().len();
1034        if len == 0 {
1035            return false;
1036        }
1037        let step: f32 = dt_secs.clamp(0.001, 0.05);
1038        let mut any_updated: bool = false;
1039        let mut write_idx: usize = 0;
1040        for read_idx in 0..len {
1041            let target: NodeId = self.get_transitions()[read_idx].get_node();
1042            if self.get_node(target).is_none() {
1043                continue;
1044            }
1045            let (done, sample_opt, hide): (bool, Option<(f32, Transform2D)>, bool) = {
1046                let tr: &mut NodeTransition = &mut self.get_mut_transitions()[read_idx];
1047                let total_span: f32 = tr.get_delay() + tr.get_duration();
1048                let prev_elapsed: f32 = tr.get_elapsed();
1049                let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
1050                tr.set_elapsed(next_elapsed);
1051                let is_done: bool = tr.is_complete();
1052                let in_hold: bool =
1053                    prev_elapsed > 0.0 && next_elapsed <= tr.get_delay() && !is_done;
1054                if in_hold {
1055                    (is_done, None, false)
1056                } else {
1057                    let sampled: (f32, Transform2D) = tr.sample();
1058                    let should_hide: bool = is_done && tr.get_hide_on_complete();
1059                    (is_done, Some(sampled), should_hide)
1060                }
1061            };
1062            if let Some((opacity, transform)) = sample_opt {
1063                if let Some(node) = self.get_node_mut(target) {
1064                    let style: &mut Style = node.get_mut_style();
1065                    style.get_mut_paint().set_opacity(opacity);
1066                    style.get_mut_paint().set_transform(transform);
1067                    if hide {
1068                        style.get_mut_layout().set_display(Display::None);
1069                    }
1070                }
1071                if hide {
1072                    self.clear_subtree_hover(target);
1073                    let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1074                    self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
1075                } else {
1076                    self.mark_dirty(target, DIRTY_PAINT);
1077                }
1078                any_updated = true;
1079            }
1080            if !done {
1081                if write_idx != read_idx {
1082                    self.get_mut_transitions().swap(write_idx, read_idx);
1083                }
1084                write_idx += 1;
1085            }
1086        }
1087        self.get_mut_transitions().truncate(write_idx);
1088        any_updated
1089    }
1090
1091    /// Clears transient hover/active flags throughout the subtree rooted at `root` when an overlay hides.
1092    ///
1093    /// # Arguments
1094    ///
1095    /// - `&Self` - Mutable scene tree.
1096    /// - `NodeId` - Root node being hidden.
1097    fn clear_subtree_hover(&mut self, root: NodeId) {
1098        let mut stack: Vec<NodeId> = vec![root];
1099        while let Some(id) = stack.pop() {
1100            let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(id) {
1101                Some(node) => {
1102                    node.get_mut_interaction().set_hovered(false);
1103                    node.get_mut_interaction().set_pressed(false);
1104                    if node.get_children().is_empty() {
1105                        None
1106                    } else {
1107                        Some(node.get_children().clone())
1108                    }
1109                }
1110                None => continue,
1111            };
1112            if let Some(children) = children_opt {
1113                stack.extend(children);
1114            }
1115        }
1116    }
1117
1118    /// Returns `true` while one or more node transitions are still running.
1119    ///
1120    /// # Arguments
1121    ///
1122    /// - `&Self` - Scene tree reference.
1123    ///
1124    /// # Returns
1125    ///
1126    /// - `bool` - Whether animations are active.
1127    #[must_use]
1128    pub fn has_active_transitions(&self) -> bool {
1129        !self.get_transitions().is_empty()
1130    }
1131
1132    /// Attaches a `Lifecycle` hook observer onto `id` for mount, activate, freeze, resume, unmount, and destroy dispatch.
1133    ///
1134    /// # Arguments
1135    ///
1136    /// - `&Self` - Mutable scene tree.
1137    /// - `NodeId` - Target scene node handle.
1138    /// - `Rc<dyn Lifecycle>` - Shared lifecycle hook observer.
1139    pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
1140        if let Some(node) = self.get_node_mut(id) {
1141            node.add_lifecycle(hook);
1142        }
1143    }
1144
1145    /// Collects all `(NodeId, Rc<dyn Lifecycle>)` observers in the subtree rooted at `root`.
1146    ///
1147    /// # Arguments
1148    ///
1149    /// - `&Self` - Scene tree reference.
1150    /// - `NodeId` - Subtree root handle.
1151    ///
1152    /// # Returns
1153    ///
1154    /// - `Vec<(NodeId, Rc<dyn Lifecycle>)>` - Ordered observers in pre-order traversal.
1155    #[must_use]
1156    pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
1157        let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1158        let mut stack: Vec<NodeId> = vec![root];
1159        while let Some(current) = stack.pop() {
1160            if let Some(node) = self.get_node(current) {
1161                for hook in node.lifecycle_observers().into_iter() {
1162                    out.push((current, hook));
1163                }
1164                for child in node.get_children().iter().rev().copied() {
1165                    stack.push(child);
1166                }
1167            }
1168        }
1169        out
1170    }
1171
1172    /// Collects all `Lifecycle` observers attached to visible (`Display != None`) nodes across the entire tree.
1173    ///
1174    /// # Arguments
1175    ///
1176    /// - `&Self` - Scene tree reference.
1177    ///
1178    /// # Returns
1179    ///
1180    /// - `Vec<(NodeId, Rc<dyn Lifecycle>)>` - Visible `(node, lifecycle)` observer pairs in pre-order.
1181    #[must_use]
1182    pub fn collect_visible_lifecycles(&self) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
1183        let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1184        let mut stack: Vec<NodeId> = vec![self.get_root()];
1185        while let Some(current) = stack.pop() {
1186            if let Some(node) = self.get_node(current) {
1187                if node.style_ref().layout_ref().get_display() == Display::None {
1188                    continue;
1189                }
1190                for hook in node.lifecycle_observers().into_iter() {
1191                    out.push((current, hook));
1192                }
1193                for child in node.get_children().iter().rev().copied() {
1194                    stack.push(child);
1195                }
1196            }
1197        }
1198        out
1199    }
1200
1201    /// Collects all reactive `ScopeId`s attached to nodes within the subtree rooted at `root`.
1202    ///
1203    /// # Arguments
1204    ///
1205    /// - `&Self` - Scene tree reference.
1206    /// - `NodeId` - Subtree root handle.
1207    ///
1208    /// # Returns
1209    ///
1210    /// - `Vec<ScopeId>` - Owned scope identifiers discovered within `root`.
1211    #[must_use]
1212    pub fn collect_subtree_scope_ids(&self, root: NodeId) -> Vec<ScopeId> {
1213        let mut out: Vec<ScopeId> = Vec::new();
1214        let mut stack: Vec<NodeId> = vec![root];
1215        while let Some(current) = stack.pop() {
1216            if let Some(node) = self.get_node(current) {
1217                if let Some(scope) = node.owned_scope() {
1218                    out.push(scope.id());
1219                }
1220                for child in node.get_children().iter().rev().copied() {
1221                    stack.push(child);
1222                }
1223            }
1224        }
1225        out
1226    }
1227
1228    /// Cancels any active paint/transform transitions targeting nodes within the subtree rooted at `root`.
1229    ///
1230    /// # Arguments
1231    ///
1232    /// - `&Self` - Mutable scene tree.
1233    /// - `NodeId` - Subtree root handle.
1234    pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
1235        if self.get_transitions().is_empty() {
1236            return;
1237        }
1238        let mut ids: HashSet<NodeId> = HashSet::new();
1239        let mut stack: Vec<NodeId> = vec![root];
1240        while let Some(current) = stack.pop() {
1241            if ids.insert(current)
1242                && let Some(node) = self.get_node(current)
1243            {
1244                for child in node.get_children().iter().copied() {
1245                    stack.push(child);
1246                }
1247            }
1248        }
1249        self.get_mut_transitions()
1250            .retain(|tr: &NodeTransition| !ids.contains(&tr.get_node()));
1251    }
1252
1253    /// Attaches a reactive `Scope` to `id` so it automatically disposes when the node unmounts.
1254    ///
1255    /// # Arguments
1256    ///
1257    /// - `&Self` - Mutable scene tree.
1258    /// - `NodeId` - Target node handle.
1259    /// - `Scope` - Reactive ownership scope.
1260    pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
1261        if let Some(node) = self.get_node_mut(id) {
1262            if let Some(existing) = node.owned_scope() {
1263                existing.enter(|| {
1264                    on_cleanup(move || {
1265                        scope.dispose();
1266                    });
1267                });
1268            } else {
1269                node.set_scope(Some(scope));
1270            }
1271        }
1272    }
1273
1274    /// Marks `id` dirty with `mask` and propagates subtree dirty bits to ancestors in O(depth).
1275    ///
1276    /// # Arguments
1277    ///
1278    /// - `&Self` - Mutable scene tree.
1279    /// - `NodeId` - Mutated node handle.
1280    /// - `u16` - Dirty flag bits to set.
1281    pub fn mark_dirty(&mut self, id: NodeId, mask: u16) {
1282        let check_portal: bool = (mask & DIRTY_LAYOUT) != 0;
1283        let (prev_bits, mut parent_opt, portal_state): (u16, Option<NodeId>, Option<bool>) =
1284            match self.get_node_mut(id) {
1285                Some(node) => {
1286                    let prev: u16 = node.get_dirty().get_bits();
1287                    node.get_mut_dirty().insert(mask);
1288                    let portal_opt: Option<bool> = if check_portal {
1289                        let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
1290                            || node.style_ref().get_layout().get_position() == Position::Fixed;
1291                        Some(is_portal)
1292                    } else {
1293                        None
1294                    };
1295                    (prev, node.parent_id(), portal_opt)
1296                }
1297                None => return,
1298            };
1299        if let Some(is_portal) = portal_state
1300            && (is_portal || self.has_portal_nodes())
1301        {
1302            self.sync_portal_registration(id, is_portal);
1303        }
1304        if (mask & DIRTY_FULL_DAMAGE_MASK) != 0 {
1305            self.set_layout_damage_pending(true);
1306        }
1307        let paint_or_scroll: u16 = DIRTY_PAINT | DIRTY_SCROLL;
1308        if !self.get_full_damage_pending()
1309            && (mask & paint_or_scroll) != 0
1310            && (prev_bits & paint_or_scroll) == 0
1311        {
1312            if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
1313                self.set_full_damage_pending(true);
1314                self.set_full_damage_overflow(true);
1315                self.get_mut_dirty_paint_nodes().clear();
1316            } else {
1317                self.get_mut_dirty_paint_nodes().push(id);
1318            }
1319        }
1320        let mut ancestor_mask: u16 = DIRTY_NONE;
1321        if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
1322            ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
1323        }
1324        if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
1325            ancestor_mask |= DIRTY_SUBTREE_PAINT;
1326        }
1327        while let Some(ancestor_id) = parent_opt {
1328            if let Some(ancestor) = self.get_node_mut(ancestor_id) {
1329                let already: bool =
1330                    (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
1331                ancestor.get_mut_dirty().insert(ancestor_mask);
1332                if already {
1333                    break;
1334                }
1335                parent_opt = ancestor.parent_id();
1336            } else {
1337                break;
1338            }
1339        }
1340        let next_rev: u64 = self.get_revision().wrapping_add(1);
1341        self.set_revision(next_rev);
1342    }
1343
1344    /// Returns `true` when `id` and every ancestor up to the root are alive, non-`Display::None`, and have positive opacity.
1345    ///
1346    /// # Arguments
1347    ///
1348    /// - `&Self` - Scene tree reference.
1349    /// - `NodeId` - Target node handle.
1350    ///
1351    /// # Returns
1352    ///
1353    /// - `bool` - Whether the node is visibly rendered in the scene.
1354    #[must_use]
1355    pub fn is_node_visible(&self, id: NodeId) -> bool {
1356        let mut cursor: Option<NodeId> = Some(id);
1357        while let Some(cur) = cursor {
1358            let Some(node) = self.get_node(cur) else {
1359                return false;
1360            };
1361            let style: &Style = node.style_ref();
1362            if style.get_layout().get_display() == Display::None
1363                || style.get_paint().get_opacity() <= 0.0
1364            {
1365                return false;
1366            }
1367            cursor = node.parent_id();
1368        }
1369        true
1370    }
1371
1372    /// Collects the tight physical damage region from dirty paint/scroll nodes in O(dirty) and clears paint dirty flags.
1373    ///
1374    /// # Arguments
1375    ///
1376    /// - `&Self` - Mutable scene tree.
1377    /// - `f32` - Active display scale factor.
1378    ///
1379    /// # Returns
1380    ///
1381    /// - `DamageRegion` - Minimal damaged region, full damage on structural/layout change, or clean when idle.
1382    pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
1383        let (damage, _): (DamageRegion, bool) = self.collect_surgical_paint_damage(scale, false);
1384        damage
1385    }
1386
1387    /// Collects tight physical paint/scroll/removed-node damage while optionally deferring layout bounds diffing to `LayoutEngine`.
1388    ///
1389    /// # Arguments
1390    ///
1391    /// - `&Self` - Mutable scene tree.
1392    /// - `f32` - Active display scale factor.
1393    /// - `bool` - When `true`, allows surgical pre/post-layout damage diffing instead of promoting all layout mutations to full redraw.
1394    ///
1395    /// # Returns
1396    ///
1397    /// - `(DamageRegion, bool)` - Collected damage region and whether a layout pass is still pending.
1398    pub(crate) fn collect_surgical_paint_damage(
1399        &mut self,
1400        scale: f32,
1401        allow_partial_layout: bool,
1402    ) -> (DamageRegion, bool) {
1403        let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
1404        let layout_pending: bool = self.get_layout_damage_pending();
1405        let no_paint_nodes: bool = self.get_dirty_paint_nodes().is_empty();
1406        let no_extra: bool = self.get_extra_logical_damage().is_empty();
1407        if !self.get_full_damage_pending() && !layout_pending && no_paint_nodes && no_extra {
1408            self.set_created_since_damage(0);
1409            return (DamageRegion::default(), false);
1410        }
1411        let mut full: bool =
1412            self.get_full_damage_pending() || (!allow_partial_layout && layout_pending);
1413        let mut region: DamageRegion = DamageRegion::default();
1414        if !full {
1415            let extra_len: usize = self.get_extra_logical_damage().len();
1416            for i in 0..extra_len {
1417                let logical_rect: Rect = self.get_extra_logical_damage()[i];
1418                if logical_rect.get_width() > 0.0 && logical_rect.get_height() > 0.0 {
1419                    region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
1420                }
1421            }
1422            let dirty_len: usize = self.get_dirty_paint_nodes().len();
1423            for i in 0..dirty_len {
1424                let nid: NodeId = self.get_dirty_paint_nodes()[i];
1425                let Some(node) = self.get_node(nid) else {
1426                    continue;
1427                };
1428                let bits: u16 = node.get_dirty().get_bits();
1429                let has_layout_bits: bool = (bits & DIRTY_LAYOUT_PASS_MASK) != 0;
1430                if !allow_partial_layout && (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
1431                    full = true;
1432                    break;
1433                }
1434                if (bits & DIRTY_SCROLL) != 0 && has_layout_bits {
1435                    full = true;
1436                    break;
1437                }
1438                if (bits & (DIRTY_PAINT | DIRTY_SCROLL)) == 0 {
1439                    continue;
1440                }
1441                let raw_bounds: Rect = node.get_layout_box().get_bounds();
1442                if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
1443                    match self.node_conservative_logical_rect(nid) {
1444                        Some(logical_rect) => {
1445                            region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
1446                        }
1447                        None => {
1448                            full = true;
1449                            break;
1450                        }
1451                    }
1452                } else if (bits & DIRTY_PAINT) != 0
1453                    && !has_layout_bits
1454                    && node.style_ref().layout_ref().get_display() != Display::None
1455                {
1456                    full = true;
1457                    break;
1458                }
1459            }
1460        }
1461        self.set_layout_damage_pending(false);
1462        self.set_created_since_damage(0);
1463        self.get_mut_extra_logical_damage().clear();
1464        if !full {
1465            let dirty_len: usize = self.get_dirty_paint_nodes().len();
1466            for i in 0..dirty_len {
1467                let nid: NodeId = self.get_dirty_paint_nodes()[i];
1468                let mut parent_opt: Option<NodeId> = match self.get_node_mut(nid) {
1469                    Some(node) => {
1470                        node.get_mut_dirty().remove(clear_mask);
1471                        node.parent_id()
1472                    }
1473                    None => None,
1474                };
1475                while let Some(ancestor_id) = parent_opt {
1476                    if let Some(ancestor) = self.get_node_mut(ancestor_id) {
1477                        if (ancestor.get_dirty().get_bits() & DIRTY_SUBTREE_PAINT) == 0 {
1478                            break;
1479                        }
1480                        ancestor.get_mut_dirty().remove(DIRTY_SUBTREE_PAINT);
1481                        parent_opt = ancestor.parent_id();
1482                    } else {
1483                        break;
1484                    }
1485                }
1486            }
1487            self.get_mut_dirty_paint_nodes().clear();
1488            return (region, layout_pending);
1489        }
1490        self.set_full_damage_pending(false);
1491        self.get_mut_dirty_paint_nodes().clear();
1492        for node in self.get_mut_nodes().iter_mut() {
1493            if node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0 {
1494                node.get_mut_dirty().remove(clear_mask);
1495            }
1496        }
1497        (DamageRegion::full(), layout_pending)
1498    }
1499
1500    /// Consumes and returns whether the most recent dirty-paint accumulation overflowed `DIRTY_PAINT_FULL_THRESHOLD`.
1501    ///
1502    /// # Arguments
1503    ///
1504    /// - `&Self` - Mutable scene tree.
1505    ///
1506    /// # Returns
1507    ///
1508    /// - `bool` - `true` if dirty paint nodes overflowed into full damage.
1509    pub(crate) fn take_full_damage_overflow(&mut self) -> bool {
1510        let was_overflow: bool = self.get_full_damage_overflow();
1511        self.set_full_damage_overflow(false);
1512        was_overflow
1513    }
1514
1515    /// Recursively detaches and recycles `id`, returning all owned `Scope`s and `Lifecycle` observers for borrow-safe finalization.
1516    ///
1517    /// # Arguments
1518    ///
1519    /// - `&Self` - Mutable scene tree.
1520    /// - `NodeId` - Subtree root handle to dispose.
1521    ///
1522    /// # Returns
1523    ///
1524    /// - `DisposedSubtreePayload` - Collected scopes and lifecycle observers to finalize outside any borrow.
1525    pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
1526        if id == self.get_root() {
1527            return (Vec::new(), Vec::new());
1528        }
1529        self.record_subtree_logical_damage(id);
1530        self.cancel_subtree_transitions(id);
1531        let mut stack: Vec<NodeId> = vec![id];
1532        let mut scopes: Vec<Scope> = Vec::new();
1533        let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1534        while let Some(current) = stack.pop() {
1535            let children_opt: Option<Vec<NodeId>> = match self.get_node_mut(current) {
1536                Some(node) => {
1537                    node.set_alive(false);
1538                    if node.has_extras() {
1539                        if let Some(scope) = node.owned_scope() {
1540                            scopes.push(scope);
1541                        }
1542                        for hook in node.take_lifecycles().into_iter() {
1543                            observers.push((current, hook));
1544                        }
1545                        node.clear_extras();
1546                    }
1547                    node.set_parent(None);
1548                    let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
1549                    node.set_generation(next_gen);
1550                    Some(take(node.get_mut_children()))
1551                }
1552                None => None,
1553            };
1554            let Some(children) = children_opt else {
1555                continue;
1556            };
1557            let next_live: usize = self.get_live_count().saturating_sub(1);
1558            self.set_live_count(next_live);
1559            if !self.portal_nodes().is_empty() {
1560                self.sync_portal_registration(current, false);
1561            }
1562            if self
1563                .text_selection()
1564                .map(|sel: SelectionState| sel.get_node_id())
1565                == Some(current)
1566            {
1567                self.set_text_selection(None);
1568            }
1569            self.get_mut_free_list().push(current.get_index());
1570            for child in children.into_iter() {
1571                stack.push(child);
1572            }
1573        }
1574        (scopes, observers)
1575    }
1576
1577    /// Recursively removes and disposes `id`, recycling all arena slots, running lifecycle hooks, and disposing scopes.
1578    ///
1579    /// # Arguments
1580    ///
1581    /// - `&Self` - Mutable scene tree.
1582    /// - `NodeId` - Subtree root handle to dispose.
1583    pub fn dispose_subtree(&mut self, id: NodeId) {
1584        let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
1585        finalize_disposed_subtree(scopes, observers);
1586    }
1587
1588    /// Updates keyboard focus to `target`, emitting `Blur` and `Focus` events.
1589    ///
1590    /// # Arguments
1591    ///
1592    /// - `&Self` - Mutable scene tree.
1593    /// - `Option<NodeId>` - Newly focused node, or `None` to clear focus.
1594    ///
1595    /// # Returns
1596    ///
1597    /// - `Vec<(UiEventHandler, UiEvent)>` - Callbacks to invoke outside the tree borrow.
1598    pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
1599        let prev: Option<NodeId> = self.get_focus().focused_node();
1600        if prev == target {
1601            return Vec::new();
1602        }
1603        let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
1604        if let Some(old_id) = prev {
1605            if let Some(old_node) = self.get_node_mut(old_id) {
1606                old_node.get_mut_interaction().set_focused(false);
1607                if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
1608                    callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
1609                }
1610            }
1611            self.mark_dirty(old_id, DIRTY_PAINT);
1612        }
1613        self.get_mut_focus().set_focused(target);
1614        if let Some(new_id) = target {
1615            if let Some(new_node) = self.get_node_mut(new_id) {
1616                new_node.get_mut_interaction().set_focused(true);
1617                if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
1618                    callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
1619                }
1620            }
1621            self.mark_dirty(new_id, DIRTY_PAINT);
1622        }
1623        callbacks
1624    }
1625
1626    /// Resolves whether `id` allows interactive text selection, walking ancestors unless an explicit opt-out is encountered.
1627    ///
1628    /// # Arguments
1629    ///
1630    /// - `&Self` - Scene tree reference.
1631    /// - `NodeId` - Target scene node handle.
1632    ///
1633    /// # Returns
1634    ///
1635    /// - `bool` - `true` when `id` or an ancestor enables `selectable` without an intervening explicit `selectable(false)`.
1636    #[must_use]
1637    pub fn is_node_selectable(&self, id: NodeId) -> bool {
1638        let mut cursor: Option<NodeId> = Some(id);
1639        while let Some(cur) = cursor {
1640            let Some(node) = self.get_node(cur) else {
1641                return false;
1642            };
1643            let text_style: &TextStyle = node.style_ref().text_ref();
1644            if text_style.get_selectable() {
1645                return true;
1646            }
1647            if text_style.get_selectable_explicit() {
1648                return false;
1649            }
1650            cursor = node.parent_id();
1651        }
1652        false
1653    }
1654
1655    /// Resolves the effective text selection highlight color for `id`, inheriting from ancestors or falling back to default tint.
1656    ///
1657    /// # Arguments
1658    ///
1659    /// - `&Self` - Scene tree reference.
1660    /// - `NodeId` - Target text node handle.
1661    ///
1662    /// # Returns
1663    ///
1664    /// - `Color` - Selection highlight fill color.
1665    #[must_use]
1666    pub fn effective_selection_color(&self, id: NodeId) -> Color {
1667        let mut cursor: Option<NodeId> = Some(id);
1668        while let Some(cur) = cursor {
1669            let Some(node) = self.get_node(cur) else {
1670                break;
1671            };
1672            if let Some(color) = node.style_ref().text_ref().selection_color() {
1673                return color;
1674            }
1675            cursor = node.parent_id();
1676        }
1677        DEFAULT_TEXT_SELECTION_COLOR
1678    }
1679
1680    /// Returns the active text selection state, if any.
1681    ///
1682    /// # Arguments
1683    ///
1684    /// - `&Self` - Scene tree reference.
1685    ///
1686    /// # Returns
1687    ///
1688    /// - `Option<SelectionState>` - Current selection state.
1689    #[must_use]
1690    pub fn text_selection(&self) -> Option<SelectionState> {
1691        let Self { text_selection, .. } = self;
1692        *text_selection
1693    }
1694
1695    /// Updates the active text selection state and marks affected text nodes dirty for repaint.
1696    ///
1697    /// # Arguments
1698    ///
1699    /// - `&Self` - Mutable scene tree.
1700    /// - `Option<SelectionState>` - Replacement selection state (`None` clears selection).
1701    pub fn set_text_selection(&mut self, selection: Option<SelectionState>) {
1702        let prev: Option<SelectionState> = self.text_selection();
1703        if prev == selection {
1704            return;
1705        }
1706        let Self { text_selection, .. } = self;
1707        *text_selection = selection;
1708        if let Some(old_sel) = prev {
1709            self.mark_dirty(old_sel.get_node_id(), DIRTY_PAINT);
1710        }
1711        if let Some(new_sel) = selection {
1712            self.mark_dirty(new_sel.get_node_id(), DIRTY_PAINT);
1713        }
1714    }
1715
1716    /// Clears any active text selection and repaints the previously selected node.
1717    ///
1718    /// # Arguments
1719    ///
1720    /// - `&Self` - Mutable scene tree.
1721    pub fn clear_text_selection(&mut self) {
1722        self.set_text_selection(None);
1723    }
1724
1725    /// Returns the currently selected UTF-8 substring when a non-empty selection exists on a live text node.
1726    ///
1727    /// # Arguments
1728    ///
1729    /// - `&Self` - Scene tree reference.
1730    ///
1731    /// # Returns
1732    ///
1733    /// - `Option<String>` - Selected text string, or `None` when no text is selected.
1734    #[must_use]
1735    pub fn get_selected_text(&self) -> Option<String> {
1736        let sel: SelectionState = self.text_selection()?;
1737        if sel.is_empty() {
1738            return None;
1739        }
1740        let node: &SceneNode = self.get_node(sel.get_node_id())?;
1741        let NodeKind::Text(content) = node.get_kind() else {
1742            return None;
1743        };
1744        let extracted: &str = sel.extract_from(content.as_str());
1745        if extracted.is_empty() {
1746            None
1747        } else {
1748            Some(extracted.to_string())
1749        }
1750    }
1751
1752    /// Selects the entire character range of selectable `NodeKind::Text` node `id`.
1753    ///
1754    /// # Arguments
1755    ///
1756    /// - `&Self` - Mutable scene tree.
1757    /// - `NodeId` - Target text node handle.
1758    ///
1759    /// # Returns
1760    ///
1761    /// - `bool` - `true` when `id` is a live selectable non-empty text node and selection was applied.
1762    pub fn select_all_text(&mut self, id: NodeId) -> bool {
1763        if !self.is_node_selectable(id) {
1764            return false;
1765        }
1766        let char_len: Option<usize> = self.get_node(id).and_then(|node: &SceneNode| {
1767            if let NodeKind::Text(content) = node.get_kind() {
1768                Some(content.chars().count())
1769            } else {
1770                None
1771            }
1772        });
1773        let Some(len) = char_len else {
1774            return false;
1775        };
1776        if len == 0 {
1777            return false;
1778        }
1779        self.set_text_selection(Some(SelectionState::new(id, 0, len)));
1780        true
1781    }
1782}
1783
1784/// Shared scene handle operations enabling surgical reactive node updates.
1785impl SceneHandle {
1786    /// Creates a new `SceneHandle` wrapping a fresh `SceneTree`.
1787    ///
1788    /// # Returns
1789    ///
1790    /// - `Self` - Shared scene handle.
1791    #[must_use]
1792    pub fn new_tree() -> Self {
1793        Self {
1794            inner: Rc::new(RefCell::new(SceneTree::default())),
1795        }
1796    }
1797
1798    /// Updates virtualized scroll metrics `(scroll_y, content_height)` on `id` for accurate scrollbar thumbs.
1799    ///
1800    /// # Arguments
1801    ///
1802    /// - `&Self` - Scene handle reference.
1803    /// - `NodeId` - Target virtualized scroll container.
1804    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
1805    /// - `f32` - Total virtualized content height in logical pixels.
1806    pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
1807        self.with_write(
1808            |tree: &mut SceneTree| {
1809                tree.set_virtual_scroll(id, scroll_y, content_height);
1810            },
1811            (),
1812        );
1813    }
1814
1815    /// Computes screen-space logical bounds for `id` subtracting ancestor scroll offsets.
1816    ///
1817    /// # Arguments
1818    ///
1819    /// - `&Self` - Scene handle reference.
1820    /// - `NodeId` - Target node handle.
1821    ///
1822    /// # Returns
1823    ///
1824    /// - `Option<Rect>` - Screen-space bounds if the node is alive.
1825    #[must_use]
1826    pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
1827        self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
1828    }
1829
1830    /// Starts or replaces a smooth paint/transform transition on the target node.
1831    ///
1832    /// # Arguments
1833    ///
1834    /// - `&Self` - Scene handle reference.
1835    /// - `NodeTransition` - Transition specification to run.
1836    pub fn start_transition(&self, transition: NodeTransition) {
1837        self.with_write(
1838            |tree: &mut SceneTree| {
1839                tree.start_transition(transition);
1840            },
1841            (),
1842        );
1843    }
1844
1845    /// Marks `id` dirty with `mask` for incremental repainting.
1846    ///
1847    /// # Arguments
1848    ///
1849    /// - `&Self` - Scene handle reference.
1850    /// - `NodeId` - Target node handle.
1851    /// - `u16` - Dirty flag bits.
1852    pub fn mark_dirty(&self, id: NodeId, mask: u16) {
1853        self.with_write(
1854            |tree: &mut SceneTree| {
1855                tree.mark_dirty(id, mask);
1856            },
1857            (),
1858        );
1859    }
1860
1861    /// Replaces all children of `parent` and finalizes disposed scopes and `Lifecycle` hooks outside the tree borrow.
1862    ///
1863    /// # Arguments
1864    ///
1865    /// - `&Self` - Scene handle reference.
1866    /// - `NodeId` - Parent container node.
1867    /// - `Vec<NodeId>` - Replacement ordered children.
1868    pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
1869        let (scopes, observers): DisposedSubtreePayload = self.with_write(
1870            |tree: &mut SceneTree| {
1871                let old_children: Vec<NodeId> = match tree.get_node_mut(parent) {
1872                    Some(node) => take(node.get_mut_children()),
1873                    None => return (Vec::new(), Vec::new()),
1874                };
1875                let mut all_scopes: Vec<Scope> = Vec::new();
1876                let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
1877                if new_children.is_empty() {
1878                    for old_child in old_children.into_iter() {
1879                        let (sc, ob): DisposedSubtreePayload =
1880                            tree.dispose_subtree_collect(old_child);
1881                        all_scopes.extend(sc);
1882                        all_obs.extend(ob);
1883                    }
1884                } else if old_children.len() > 16 && new_children.len() > 16 {
1885                    let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
1886                    for old_child in old_children.into_iter() {
1887                        if !keep_set.contains(&old_child) {
1888                            let (sc, ob): DisposedSubtreePayload =
1889                                tree.dispose_subtree_collect(old_child);
1890                            all_scopes.extend(sc);
1891                            all_obs.extend(ob);
1892                        }
1893                    }
1894                } else {
1895                    for old_child in old_children.into_iter() {
1896                        if !new_children.contains(&old_child) {
1897                            let (sc, ob): DisposedSubtreePayload =
1898                                tree.dispose_subtree_collect(old_child);
1899                            all_scopes.extend(sc);
1900                            all_obs.extend(ob);
1901                        }
1902                    }
1903                }
1904                for child in new_children.iter().copied() {
1905                    if let Some(child_node) = tree.get_node_mut(child) {
1906                        child_node.set_parent(Some(parent));
1907                    }
1908                }
1909                if let Some(parent_node) = tree.get_node_mut(parent) {
1910                    parent_node.set_children(new_children);
1911                }
1912                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1913                (all_scopes, all_obs)
1914            },
1915            (Vec::new(), Vec::new()),
1916        );
1917        finalize_disposed_subtree(scopes, observers);
1918    }
1919
1920    /// Removes `child` from `parent`, disposes its subtree, and invokes `on_unmount`/`on_destroy` outside any scene borrow.
1921    ///
1922    /// # Arguments
1923    ///
1924    /// - `&Self` - Scene handle reference.
1925    /// - `NodeId` - Parent container handle.
1926    /// - `NodeId` - Child subtree root handle to remove and destroy.
1927    pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
1928        let (scopes, observers): DisposedSubtreePayload = self.with_write(
1929            |tree: &mut SceneTree| {
1930                if let Some(pnode) = tree.get_node_mut(parent) {
1931                    pnode.get_mut_children().retain(|id: &NodeId| *id != child);
1932                }
1933                let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
1934                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1935                out
1936            },
1937            (Vec::new(), Vec::new()),
1938        );
1939        finalize_disposed_subtree(scopes, observers);
1940    }
1941
1942    /// Mutates a node's `Style` in place under one write lock, marking only minimal dirty flags when changed.
1943    ///
1944    /// # Arguments
1945    ///
1946    /// - `&Self` - Scene handle reference.
1947    /// - `NodeId` - Target node handle.
1948    /// - `F` - In-place style mutator closure receiving `&mut Style`.
1949    ///
1950    /// # Returns
1951    ///
1952    /// - `bool` - `true` when the node existed and its style changed.
1953    pub fn mutate_style<F>(&self, id: NodeId, mutator: F) -> bool
1954    where
1955        F: FnOnce(&mut Style),
1956    {
1957        self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
1958    }
1959
1960    /// Freezes a subtree visually (`Display::None`), cancels its transitions, and dispatches `Lifecycle::on_freeze` outside any scene borrow.
1961    ///
1962    /// # Arguments
1963    ///
1964    /// - `&Self` - Scene handle reference.
1965    /// - `NodeId` - Subtree root handle to freeze.
1966    pub fn freeze_subtree(&self, root: NodeId) {
1967        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
1968            |tree: &mut SceneTree| {
1969                let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
1970                tree.cancel_subtree_transitions(root);
1971                let changed: bool = if let Some(node) = tree.get_node_mut(root) {
1972                    let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
1973                    if layout.get_display() == Display::None {
1974                        false
1975                    } else {
1976                        layout.set_display(Display::None);
1977                        true
1978                    }
1979                } else {
1980                    false
1981                };
1982                if changed {
1983                    tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
1984                }
1985                obs
1986            },
1987            Vec::new(),
1988        );
1989        dispatch_lifecycle_freeze(&observers);
1990    }
1991
1992    /// Freezes a subtree immediately for lifecycle/effects while animating its visual exit to `Display::None`.
1993    ///
1994    /// # Arguments
1995    ///
1996    /// - `&Self` - Scene handle reference.
1997    /// - `NodeId` - Subtree root handle to freeze and animate out.
1998    /// - `NodeTransition` - Exit transition specification (`hide_on_complete` is enforced).
1999    pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
2000        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
2001            |tree: &mut SceneTree| {
2002                let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
2003                tree.cancel_subtree_transitions(root);
2004                let mut demoted_fixed: bool = false;
2005                if let Some(node) = tree.get_node_mut(root) {
2006                    let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
2007                    let st: &mut Style = node.get_mut_style();
2008                    demoted_fixed = !is_portal && st.layout_ref().get_position() == Position::Fixed;
2009                    st.get_mut_layout()
2010                        .set_position(Position::Absolute)
2011                        .set_top(Some(0.0))
2012                        .set_right(Some(0.0))
2013                        .set_bottom(None)
2014                        .set_left(Some(0.0))
2015                        .set_z_index(0);
2016                    st.get_mut_paint().set_pointer_events(PointerEvents::None);
2017                }
2018                if demoted_fixed {
2019                    tree.sync_portal_registration(root, false);
2020                }
2021                tree.start_transition(exit_transition.with_hide_on_complete(true));
2022                tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
2023                obs
2024            },
2025            Vec::new(),
2026        );
2027        dispatch_lifecycle_freeze(&observers);
2028    }
2029
2030    /// Resumes a previously frozen subtree (`Display::Flex`) and dispatches `Lifecycle::on_resume` outside any scene borrow.
2031    ///
2032    /// # Arguments
2033    ///
2034    /// - `&Self` - Scene handle reference.
2035    /// - `NodeId` - Subtree root handle to resume.
2036    pub fn resume_subtree(&self, root: NodeId) {
2037        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
2038            |tree: &mut SceneTree| {
2039                let mut unhidden: bool = false;
2040                if let Some(node) = tree.get_node_mut(root) {
2041                    let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
2042                    if layout.get_display() == Display::None {
2043                        layout.set_display(Display::Flex);
2044                        unhidden = true;
2045                    }
2046                }
2047                if unhidden {
2048                    tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
2049                } else {
2050                    tree.mark_dirty(root, DIRTY_PAINT);
2051                }
2052                tree.collect_subtree_lifecycles(root)
2053            },
2054            Vec::new(),
2055        );
2056        dispatch_lifecycle_resume(&observers);
2057    }
2058
2059    /// Dispatches `Lifecycle::on_activate` across all observers in the subtree rooted at `root`.
2060    ///
2061    /// # Arguments
2062    ///
2063    /// - `&Self` - Scene handle reference.
2064    /// - `NodeId` - Subtree root handle becoming active.
2065    pub fn activate_subtree(&self, root: NodeId) {
2066        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
2067            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
2068            Vec::new(),
2069        );
2070        dispatch_lifecycle_activate(&observers);
2071    }
2072
2073    /// Dispatches `Lifecycle::on_update` across all observers in the subtree rooted at `root`.
2074    ///
2075    /// # Arguments
2076    ///
2077    /// - `&Self` - Scene handle reference.
2078    /// - `NodeId` - Subtree root handle receiving updates.
2079    pub fn update_subtree(&self, root: NodeId) {
2080        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
2081            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
2082            Vec::new(),
2083        );
2084        dispatch_lifecycle_update(&observers);
2085    }
2086
2087    /// Dispatches `SystemEvent::Appear` to all `Lifecycle` observers and scoped hooks owned by `root`'s subtree.
2088    ///
2089    /// # Arguments
2090    ///
2091    /// - `&Self` - Scene handle reference.
2092    /// - `NodeId` - Page or component subtree root handle becoming visible.
2093    pub fn emit_subtree_appear(&self, root: NodeId) {
2094        let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
2095            |tree: &SceneTree| {
2096                (
2097                    tree.collect_subtree_lifecycles(root),
2098                    tree.collect_subtree_scope_ids(root),
2099                )
2100            },
2101            (Vec::new(), Vec::new()),
2102        );
2103        let ev: SystemEvent = SystemEvent::Appear;
2104        dispatch_lifecycle_system_event(&observers, &ev);
2105        dispatch_system_event_to_scopes(&scopes, &ev);
2106    }
2107
2108    /// Dispatches `SystemEvent::Disappear` to all `Lifecycle` observers and scoped hooks owned by `root`'s subtree.
2109    ///
2110    /// # Arguments
2111    ///
2112    /// - `&Self` - Scene handle reference.
2113    /// - `NodeId` - Page or component subtree root handle ceasing to be visible.
2114    pub fn emit_subtree_disappear(&self, root: NodeId) {
2115        let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
2116            |tree: &SceneTree| {
2117                (
2118                    tree.collect_subtree_lifecycles(root),
2119                    tree.collect_subtree_scope_ids(root),
2120                )
2121            },
2122            (Vec::new(), Vec::new()),
2123        );
2124        let ev: SystemEvent = SystemEvent::Disappear;
2125        dispatch_lifecycle_system_event(&observers, &ev);
2126        dispatch_system_event_to_scopes(&scopes, &ev);
2127    }
2128
2129    /// Returns `true` if any node transition is currently active.
2130    ///
2131    /// # Arguments
2132    ///
2133    /// - `&Self` - Scene handle reference.
2134    ///
2135    /// # Returns
2136    ///
2137    /// - `bool` - Whether animations are running.
2138    #[must_use]
2139    pub fn has_active_transitions(&self) -> bool {
2140        self.with_read(SceneTree::has_active_transitions, false)
2141    }
2142
2143    /// Returns the currently selected text substring across the retained scene, if any.
2144    ///
2145    /// # Arguments
2146    ///
2147    /// - `&Self` - Scene handle reference.
2148    ///
2149    /// # Returns
2150    ///
2151    /// - `Option<String>` - Active selected UTF-8 text.
2152    #[must_use]
2153    pub fn get_selected_text(&self) -> Option<String> {
2154        self.with_read(SceneTree::get_selected_text, None)
2155    }
2156
2157    /// Clears any active text selection across the retained scene.
2158    ///
2159    /// # Arguments
2160    ///
2161    /// - `&Self` - Scene handle reference.
2162    pub fn clear_text_selection(&self) {
2163        self.with_write(SceneTree::clear_text_selection, ());
2164    }
2165
2166    /// Executes `operation` with immutable access to the underlying `SceneTree`.
2167    ///
2168    /// # Arguments
2169    ///
2170    /// - `&Self` - Scene handle.
2171    /// - `F` - Reader closure.
2172    /// - `R` - Fallback if re-entrantly borrowed.
2173    ///
2174    /// # Returns
2175    ///
2176    /// - `R` - Closure result or fallback.
2177    pub fn with_read<F, R>(&self, operation: F, fallback: R) -> R
2178    where
2179        F: FnOnce(&SceneTree) -> R,
2180    {
2181        let Self { inner } = self;
2182        match inner.try_borrow() {
2183            Ok(guard) => operation(&guard),
2184            Err(_) => fallback,
2185        }
2186    }
2187
2188    /// Executes `operation` with mutable access to the underlying `SceneTree`.
2189    ///
2190    /// # Arguments
2191    ///
2192    /// - `&Self` - Scene handle.
2193    /// - `F` - Mutation closure.
2194    /// - `R` - Fallback if re-entrantly borrowed.
2195    ///
2196    /// # Returns
2197    ///
2198    /// - `R` - Closure result or fallback.
2199    pub fn with_write<F, R>(&self, operation: F, fallback: R) -> R
2200    where
2201        F: FnOnce(&mut SceneTree) -> R,
2202    {
2203        let Self { inner } = self;
2204        match inner.try_borrow_mut() {
2205            Ok(mut guard) => operation(&mut guard),
2206            Err(_) => fallback,
2207        }
2208    }
2209
2210    /// Binds a reactive text expression to `node_id` via a surgical `Effect`.
2211    ///
2212    /// # Arguments
2213    ///
2214    /// - `&Self` - Scene handle.
2215    /// - `NodeId` - Target text node.
2216    /// - `F` - Reactive text producer closure.
2217    ///
2218    /// # Returns
2219    ///
2220    /// - `Effect` - Registered reactive effect.
2221    pub fn bind_text<F>(&self, node_id: NodeId, mut producer: F) -> Effect
2222    where
2223        F: FnMut() -> String + 'static,
2224    {
2225        let handle: Self = self.clone();
2226        Effect::new(move || {
2227            let value: String = producer();
2228            handle.with_write(
2229                |tree: &mut SceneTree| {
2230                    tree.set_text(node_id, value);
2231                },
2232                (),
2233            );
2234        })
2235    }
2236
2237    /// Binds a reactive `Style` expression to `node_id` via a surgical `Effect`.
2238    ///
2239    /// # Arguments
2240    ///
2241    /// - `&Self` - Scene handle.
2242    /// - `NodeId` - Target node.
2243    /// - `F` - Reactive style producer closure.
2244    ///
2245    /// # Returns
2246    ///
2247    /// - `Effect` - Registered reactive effect.
2248    pub fn bind_style<F>(&self, node_id: NodeId, mut producer: F) -> Effect
2249    where
2250        F: FnMut() -> Style + 'static,
2251    {
2252        let handle: Self = self.clone();
2253        Effect::new(move || {
2254            let style: Style = producer();
2255            handle.with_write(
2256                |tree: &mut SceneTree| {
2257                    tree.set_style(node_id, style);
2258                },
2259                (),
2260            );
2261        })
2262    }
2263}
2264
2265/// High-level declarative building helpers on `Context`.
2266impl Context {
2267    /// Creates a new `Context` with reactive viewport, theme, and safe-area signals.
2268    ///
2269    /// # Arguments
2270    ///
2271    /// - `SceneHandle` - Shared scene handle.
2272    /// - `PlatformKind` - Active platform kind.
2273    ///
2274    /// # Returns
2275    ///
2276    /// - `Self` - Constructed build context.
2277    #[must_use]
2278    pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
2279        Self {
2280            scene,
2281            breakpoint: Signal::new(Breakpoint::Expanded),
2282            viewport_size: Signal::new(Size::new(1200.0, 800.0)),
2283            theme_mode: Signal::new(ThemeMode::Light),
2284            platform,
2285            safe_area: Signal::new(SafeAreaInsets::default()),
2286            gesture: Signal::new(None),
2287            swipe_drag_offset: Signal::new(0.0),
2288            system_back: Signal::new(0),
2289            dynamic_hub: DynamicUpdateHub::new(),
2290            fps_limit: Signal::new(None),
2291            live_fps: Signal::new(60.0),
2292            present_fps: Signal::new(0.0),
2293            is_idle: Signal::new(true),
2294            display_refresh_rate: Signal::new(60.0),
2295            active_touches: Signal::new(Vec::new()),
2296            exit_requested: Signal::new(false),
2297            app_state: Signal::new(AppState::Active),
2298            network_status: Signal::new(NetworkStatus::Online),
2299            keyboard_visible: Signal::new(false),
2300            keyboard_height: Signal::new(0.0),
2301            orientation: Signal::new(ScreenOrientation::Landscape),
2302            low_power_mode: Signal::new(false),
2303            locale: Signal::new(DEFAULT_SYSTEM_LOCALE.to_string()),
2304            window_focused: Signal::new(true),
2305            clock_ms: Rc::new(Cell::new(0)),
2306        }
2307    }
2308
2309    /// Returns the reactive `Signal<AppState>` tracking canonical cross-platform application lifecycle state.
2310    ///
2311    /// # Arguments
2312    ///
2313    /// - `&Self` - Context reference.
2314    ///
2315    /// # Returns
2316    ///
2317    /// - `Signal<AppState>` - Reactive lifecycle state signal.
2318    #[must_use]
2319    pub fn app_state_signal(&self) -> Signal<AppState> {
2320        self.get_app_state()
2321    }
2322
2323    /// Dispatches a page-level `SystemEvent::Appear` to all currently active non-frozen hooks and visible observers.
2324    ///
2325    /// # Arguments
2326    ///
2327    /// - `&Self` - Context reference.
2328    pub fn emit_page_appear(&self) {
2329        let ev: SystemEvent = SystemEvent::Appear;
2330        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
2331            .get_scene()
2332            .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
2333        dispatch_lifecycle_system_event(&observers, &ev);
2334        dispatch_system_event_listeners(&ev);
2335    }
2336
2337    /// Dispatches a page-level `SystemEvent::Disappear` to all currently active non-frozen hooks and visible observers.
2338    ///
2339    /// # Arguments
2340    ///
2341    /// - `&Self` - Context reference.
2342    pub fn emit_page_disappear(&self) {
2343        let ev: SystemEvent = SystemEvent::Disappear;
2344        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
2345            .get_scene()
2346            .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
2347        dispatch_lifecycle_system_event(&observers, &ev);
2348        dispatch_system_event_listeners(&ev);
2349    }
2350
2351    /// Dispatches `SystemEvent::Appear` strictly to `Lifecycle` components and scoped hooks within `root`'s subtree.
2352    ///
2353    /// # Arguments
2354    ///
2355    /// - `&Self` - Context reference.
2356    /// - `NodeId` - Routed page or component subtree root handle becoming active.
2357    pub fn emit_subtree_appear(&self, root: NodeId) {
2358        self.get_scene().emit_subtree_appear(root);
2359    }
2360
2361    /// Dispatches `SystemEvent::Disappear` strictly to `Lifecycle` components and scoped hooks within `root`'s subtree.
2362    ///
2363    /// # Arguments
2364    ///
2365    /// - `&Self` - Context reference.
2366    /// - `NodeId` - Routed page or component subtree root handle becoming hidden.
2367    pub fn emit_subtree_disappear(&self, root: NodeId) {
2368        self.get_scene().emit_subtree_disappear(root);
2369    }
2370
2371    /// Returns the monotonic runtime elapsed clock in milliseconds.
2372    ///
2373    /// # Arguments
2374    ///
2375    /// - `&Self` - Context reference.
2376    ///
2377    /// # Returns
2378    ///
2379    /// - `u64` - Elapsed runtime time in milliseconds.
2380    #[must_use]
2381    pub fn elapsed_ms(&self) -> u64 {
2382        let Self { clock_ms, .. } = self;
2383        clock_ms.get()
2384    }
2385
2386    /// Advances the context's monotonic runtime clock by `delta_ms` milliseconds.
2387    ///
2388    /// # Arguments
2389    ///
2390    /// - `&Self` - Context reference.
2391    /// - `u64` - Milliseconds elapsed since the previous frame.
2392    pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
2393        let Self { clock_ms, .. } = self;
2394        clock_ms.set(clock_ms.get().saturating_add(delta_ms));
2395    }
2396
2397    /// Requests graceful OS-level application termination across all platforms.
2398    ///
2399    /// # Arguments
2400    ///
2401    /// - `&Self` - Context reference.
2402    pub fn request_exit(&self) {
2403        let _: bool = self.get_exit_requested().set_if_changed(true);
2404        let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
2405    }
2406
2407    /// Copies `text` to the host OS or browser clipboard via native clipboard hooks.
2408    ///
2409    /// # Arguments
2410    ///
2411    /// - `&Self` - Context reference.
2412    /// - `&str` - UTF-8 text string to copy.
2413    ///
2414    /// # Returns
2415    ///
2416    /// - `bool` - `true` when a native or host clipboard bridge accepted `text`.
2417    pub fn copy_to_clipboard(&self, text: &str) -> bool {
2418        write_system_clipboard(text)
2419    }
2420
2421    /// Creates a `View` node with the given style.
2422    ///
2423    /// # Arguments
2424    ///
2425    /// - `&Self` - Build context.
2426    /// - `Style` - Initial style.
2427    ///
2428    /// # Returns
2429    ///
2430    /// - `NodeId` - Created node handle.
2431    pub fn view(&mut self, style: Style) -> NodeId {
2432        self.get_scene().with_write(
2433            |tree: &mut SceneTree| tree.create_view(style),
2434            NodeId::default(),
2435        )
2436    }
2437
2438    /// Creates a `Text` node with static initial text.
2439    ///
2440    /// # Arguments
2441    ///
2442    /// - `&Self` - Build context.
2443    /// - `String` - Text content.
2444    /// - `Style` - Text style.
2445    ///
2446    /// # Returns
2447    ///
2448    /// - `NodeId` - Created node handle.
2449    pub fn text(&mut self, content: String, style: Style) -> NodeId {
2450        self.get_scene().with_write(
2451            |tree: &mut SceneTree| tree.create_text(content, style),
2452            NodeId::default(),
2453        )
2454    }
2455
2456    /// Creates a reactive `Text` node whose content updates surgically whenever tracked signals change.
2457    ///
2458    /// # Arguments
2459    ///
2460    /// - `&Self` - Build context.
2461    /// - `Style` - Text style.
2462    /// - `F` - Reactive text producer.
2463    ///
2464    /// # Returns
2465    ///
2466    /// - `NodeId` - Created reactive text node handle.
2467    pub fn reactive_text<F>(&mut self, style: Style, producer: F) -> NodeId
2468    where
2469        F: FnMut() -> String + 'static,
2470    {
2471        let node_id: NodeId = self.text(String::new(), style);
2472        let handle: SceneHandle = self.get_scene().clone();
2473        let (scope, _): (Scope, Effect) =
2474            Scope::run(|_: Scope| handle.bind_text(node_id, producer));
2475        self.get_scene().with_write(
2476            |tree: &mut SceneTree| {
2477                tree.attach_scope(node_id, scope);
2478            },
2479            (),
2480        );
2481        node_id
2482    }
2483
2484    /// Creates a `ScrollView` node with the given style.
2485    ///
2486    /// # Arguments
2487    ///
2488    /// - `&Self` - Build context.
2489    /// - `Style` - Scroll container style.
2490    ///
2491    /// # Returns
2492    ///
2493    /// - `NodeId` - Created scroll view handle.
2494    pub fn scroll_view(&mut self, style: Style) -> NodeId {
2495        self.get_scene().with_write(
2496            |tree: &mut SceneTree| tree.create_scroll_view(style),
2497            NodeId::default(),
2498        )
2499    }
2500
2501    /// Creates an `Input` node with initial state and style.
2502    ///
2503    /// # Arguments
2504    ///
2505    /// - `&Self` - Build context.
2506    /// - `InputNodeState` - Initial input state.
2507    /// - `Style` - Input style.
2508    ///
2509    /// # Returns
2510    ///
2511    /// - `NodeId` - Created input handle.
2512    pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
2513        self.get_scene().with_write(
2514            |tree: &mut SceneTree| tree.create_input(state, style),
2515            NodeId::default(),
2516        )
2517    }
2518
2519    /// Creates an `Image` node with decoded RGBA8 pixel data.
2520    ///
2521    /// # Arguments
2522    ///
2523    /// - `&Self` - Build context.
2524    /// - `ImageBuffer` - Image buffer.
2525    /// - `Style` - Image style.
2526    ///
2527    /// # Returns
2528    ///
2529    /// - `NodeId` - Created image handle.
2530    pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
2531        self.get_scene().with_write(
2532            |tree: &mut SceneTree| tree.create_image(buffer, style),
2533            NodeId::default(),
2534        )
2535    }
2536
2537    /// Creates a `Canvas` node bound to a custom draw callback.
2538    ///
2539    /// # Arguments
2540    ///
2541    /// - `&Self` - Build context.
2542    /// - `Style` - Canvas style.
2543    /// - `F` - Draw callback receiving node bounds and mutable `DisplayList`.
2544    ///
2545    /// # Returns
2546    ///
2547    /// - `NodeId` - Created canvas handle.
2548    pub fn canvas<F>(&mut self, style: Style, painter: F) -> NodeId
2549    where
2550        F: FnMut(Rect, &mut DisplayList) + 'static,
2551    {
2552        let cb: CanvasDrawCallback = Rc::new(RefCell::new(painter));
2553        self.get_scene().with_write(
2554            |tree: &mut SceneTree| tree.create_canvas(style, cb),
2555            NodeId::default(),
2556        )
2557    }
2558
2559    /// Creates an overlay `Portal` node.
2560    ///
2561    /// # Arguments
2562    ///
2563    /// - `&Self` - Build context.
2564    /// - `Style` - Portal style.
2565    ///
2566    /// # Returns
2567    ///
2568    /// - `NodeId` - Created portal handle.
2569    pub fn portal(&mut self, style: Style) -> NodeId {
2570        self.get_scene().with_write(
2571            |tree: &mut SceneTree| tree.create_portal(style),
2572            NodeId::default(),
2573        )
2574    }
2575
2576    /// Creates a transparent logical `Fragment` grouping container for sibling nodes.
2577    ///
2578    /// # Arguments
2579    ///
2580    /// - `&Self` - Build context.
2581    ///
2582    /// # Returns
2583    ///
2584    /// - `NodeId` - Created fragment handle.
2585    pub fn fragment(&mut self) -> NodeId {
2586        self.get_scene().with_write(
2587            |tree: &mut SceneTree| tree.create_fragment(),
2588            NodeId::default(),
2589        )
2590    }
2591
2592    /// Appends `child` to `parent`.
2593    ///
2594    /// # Arguments
2595    ///
2596    /// - `&Self` - Build context.
2597    /// - `NodeId` - Parent container.
2598    /// - `NodeId` - Child node.
2599    pub fn append(&mut self, parent: NodeId, child: NodeId) {
2600        self.get_scene().with_write(
2601            |tree: &mut SceneTree| {
2602                tree.append_child(parent, child);
2603            },
2604            (),
2605        );
2606    }
2607
2608    /// Appends a slice of `children` to `parent` under a single scene write lock and dirty pass.
2609    ///
2610    /// # Arguments
2611    ///
2612    /// - `&Self` - Build context.
2613    /// - `NodeId` - Parent container.
2614    /// - `&[NodeId]` - Ordered child node slice.
2615    pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
2616        if children.is_empty() {
2617            return;
2618        }
2619        self.get_scene().with_write(
2620            |tree: &mut SceneTree| {
2621                tree.append_children(parent, children);
2622            },
2623            (),
2624        );
2625    }
2626
2627    /// Binds a reactive `Style` closure to `node_id` and attaches its disposal `Scope` automatically.
2628    ///
2629    /// # Arguments
2630    ///
2631    /// - `&Self` - Build context.
2632    /// - `NodeId` - Target scene node.
2633    /// - `F` - Reactive `Style` producer closure.
2634    pub fn bind_style<F>(&mut self, node_id: NodeId, producer: F)
2635    where
2636        F: FnMut() -> Style + 'static,
2637    {
2638        let handle: SceneHandle = self.get_scene().clone();
2639        let (scope, _): (Scope, Effect) =
2640            Scope::run(|_: Scope| handle.bind_style(node_id, producer));
2641        self.get_scene().with_write(
2642            |tree: &mut SceneTree| {
2643                tree.attach_scope(node_id, scope);
2644            },
2645            (),
2646        );
2647    }
2648
2649    /// Registers a pointer-enter handler on `node_id`.
2650    ///
2651    /// # Arguments
2652    ///
2653    /// - `&Self` - Build context.
2654    /// - `NodeId` - Target node handle.
2655    /// - `F` - Pointer-enter callback closure.
2656    pub fn on_pointer_enter<F>(&mut self, node_id: NodeId, callback: F)
2657    where
2658        F: FnMut(&UiEvent) + 'static,
2659    {
2660        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2661        self.get_scene().with_write(
2662            |tree: &mut SceneTree| {
2663                if let Some(node) = tree.get_node_mut(node_id) {
2664                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
2665                }
2666            },
2667            (),
2668        );
2669    }
2670
2671    /// Registers a pointer-leave handler on `node_id`.
2672    ///
2673    /// # Arguments
2674    ///
2675    /// - `&Self` - Build context.
2676    /// - `NodeId` - Target node handle.
2677    /// - `F` - Pointer-leave callback closure.
2678    pub fn on_pointer_leave<F>(&mut self, node_id: NodeId, callback: F)
2679    where
2680        F: FnMut(&UiEvent) + 'static,
2681    {
2682        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2683        self.get_scene().with_write(
2684            |tree: &mut SceneTree| {
2685                if let Some(node) = tree.get_node_mut(node_id) {
2686                    node.get_mut_handlers().set_on_pointer_leave(Some(handler));
2687                }
2688            },
2689            (),
2690        );
2691    }
2692
2693    /// Registers a focus-gained handler on `node_id` and marks it focusable.
2694    ///
2695    /// # Arguments
2696    ///
2697    /// - `&Self` - Build context.
2698    /// - `NodeId` - Target node handle.
2699    /// - `F` - Focus callback closure receiving `UiEventKind::Focus`.
2700    pub fn on_focus<F>(&mut self, node_id: NodeId, callback: F)
2701    where
2702        F: FnMut(&UiEvent) + 'static,
2703    {
2704        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2705        self.get_scene().with_write(
2706            |tree: &mut SceneTree| {
2707                if let Some(node) = tree.get_node_mut(node_id) {
2708                    node.get_mut_handlers().set_on_focus(Some(handler));
2709                    node.get_mut_interaction().set_focusable(true);
2710                }
2711            },
2712            (),
2713        );
2714    }
2715
2716    /// Registers a focus-lost handler on `node_id`.
2717    ///
2718    /// # Arguments
2719    ///
2720    /// - `&Self` - Build context.
2721    /// - `NodeId` - Target node handle.
2722    /// - `F` - Blur callback closure receiving `UiEventKind::Blur`.
2723    pub fn on_blur<F>(&mut self, node_id: NodeId, callback: F)
2724    where
2725        F: FnMut(&UiEvent) + 'static,
2726    {
2727        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2728        self.get_scene().with_write(
2729            |tree: &mut SceneTree| {
2730                if let Some(node) = tree.get_node_mut(node_id) {
2731                    node.get_mut_handlers().set_on_blur(Some(handler));
2732                }
2733            },
2734            (),
2735        );
2736    }
2737
2738    /// Configures whether `node_id` participates in keyboard focus navigation.
2739    ///
2740    /// # Arguments
2741    ///
2742    /// - `&Self` - Build context.
2743    /// - `NodeId` - Target node handle.
2744    /// - `bool` - Whether keyboard focus is enabled.
2745    pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
2746        self.get_scene().with_write(
2747            |tree: &mut SceneTree| {
2748                if let Some(node) = tree.get_node_mut(node_id) {
2749                    node.get_mut_interaction().set_focusable(focusable);
2750                }
2751            },
2752            (),
2753        );
2754    }
2755
2756    /// Registers a click handler on `node_id` and sets pointer cursor automatically.
2757    ///
2758    /// # Arguments
2759    ///
2760    /// - `&Self` - Build context.
2761    /// - `NodeId` - Target node.
2762    /// - `F` - Click callback closure.
2763    pub fn on_click<F>(&mut self, node_id: NodeId, callback: F)
2764    where
2765        F: FnMut(&UiEvent) + 'static,
2766    {
2767        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2768        self.get_scene().with_write(
2769            |tree: &mut SceneTree| {
2770                if let Some(node) = tree.get_node_mut(node_id) {
2771                    node.get_mut_handlers().set_on_click(Some(handler));
2772                    node.get_mut_interaction().set_focusable(true);
2773                    let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
2774                    if paint.get_cursor() == CursorIcon::Default {
2775                        paint.set_cursor(CursorIcon::Pointer);
2776                    }
2777                }
2778            },
2779            (),
2780        );
2781    }
2782
2783    /// Registers a change handler on an `Input` node.
2784    ///
2785    /// # Arguments
2786    ///
2787    /// - `&Self` - Build context.
2788    /// - `NodeId` - Target input node.
2789    /// - `F` - Change callback closure.
2790    pub fn on_change<F>(&mut self, node_id: NodeId, callback: F)
2791    where
2792        F: FnMut(&UiEvent) + 'static,
2793    {
2794        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2795        self.get_scene().with_write(
2796            |tree: &mut SceneTree| {
2797                if let Some(node) = tree.get_node_mut(node_id) {
2798                    node.get_mut_handlers().set_on_change(Some(handler));
2799                }
2800            },
2801            (),
2802        );
2803    }
2804
2805    /// Attaches semantic accessibility properties to `node_id`.
2806    ///
2807    /// # Arguments
2808    ///
2809    /// - `&Self` - Build context.
2810    /// - `NodeId` - Target scene node.
2811    /// - `A11yProps` - Semantic role, label, hint, and state metadata.
2812    pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
2813        self.get_scene().with_write(
2814            |tree: &mut SceneTree| {
2815                if let Some(node) = tree.get_node_mut(node_id) {
2816                    node.set_a11y(Some(props));
2817                }
2818            },
2819            (),
2820        );
2821    }
2822
2823    /// Registers a scroll handler on a scrollable container node.
2824    ///
2825    /// # Arguments
2826    ///
2827    /// - `&Self` - Build context.
2828    /// - `NodeId` - Target scroll container node.
2829    /// - `F` - Scroll callback closure receiving `UiEventKind::Scroll(delta)`.
2830    pub fn on_scroll<F>(&mut self, node_id: NodeId, callback: F)
2831    where
2832        F: FnMut(&UiEvent) + 'static,
2833    {
2834        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2835        self.get_scene().with_write(
2836            |tree: &mut SceneTree| {
2837                if let Some(node) = tree.get_node_mut(node_id) {
2838                    node.get_mut_handlers().set_on_scroll(Some(handler));
2839                }
2840            },
2841            (),
2842        );
2843    }
2844
2845    /// Registers a pointer-down handler on `node_id` for draggable interactive controls.
2846    ///
2847    /// # Arguments
2848    ///
2849    /// - `&Self` - Build context.
2850    /// - `NodeId` - Target node handle.
2851    /// - `F` - Pointer-down callback closure.
2852    pub fn on_pointer_down<F>(&mut self, node_id: NodeId, callback: F)
2853    where
2854        F: FnMut(&UiEvent) + 'static,
2855    {
2856        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2857        self.get_scene().with_write(
2858            |tree: &mut SceneTree| {
2859                if let Some(node) = tree.get_node_mut(node_id) {
2860                    node.get_mut_handlers().set_on_pointer_down(Some(handler));
2861                    let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
2862                    if paint.get_cursor() == CursorIcon::Default {
2863                        paint.set_cursor(CursorIcon::Pointer);
2864                    }
2865                }
2866            },
2867            (),
2868        );
2869    }
2870
2871    /// Registers a pointer-move handler on `node_id` receiving captured drag coordinates while pressed.
2872    ///
2873    /// # Arguments
2874    ///
2875    /// - `&Self` - Build context.
2876    /// - `NodeId` - Target node handle.
2877    /// - `F` - Pointer-move callback closure.
2878    pub fn on_pointer_move<F>(&mut self, node_id: NodeId, callback: F)
2879    where
2880        F: FnMut(&UiEvent) + 'static,
2881    {
2882        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2883        self.get_scene().with_write(
2884            |tree: &mut SceneTree| {
2885                if let Some(node) = tree.get_node_mut(node_id) {
2886                    node.get_mut_handlers().set_on_pointer_move(Some(handler));
2887                }
2888            },
2889            (),
2890        );
2891    }
2892
2893    /// Registers a pointer-up handler on `node_id` invoked when drag capture releases.
2894    ///
2895    /// # Arguments
2896    ///
2897    /// - `&Self` - Build context.
2898    /// - `NodeId` - Target node handle.
2899    /// - `F` - Pointer-up callback closure.
2900    pub fn on_pointer_up<F>(&mut self, node_id: NodeId, callback: F)
2901    where
2902        F: FnMut(&UiEvent) + 'static,
2903    {
2904        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2905        self.get_scene().with_write(
2906            |tree: &mut SceneTree| {
2907                if let Some(node) = tree.get_node_mut(node_id) {
2908                    node.get_mut_handlers().set_on_pointer_up(Some(handler));
2909                }
2910            },
2911            (),
2912        );
2913    }
2914
2915    /// Registers a hover handler on `node_id` invoked on both `PointerEnter` and `PointerLeave`.
2916    ///
2917    /// # Arguments
2918    ///
2919    /// - `&Self` - Build context.
2920    /// - `NodeId` - Target node handle.
2921    /// - `F` - Hover callback closure receiving `UiEventKind::PointerEnter` or `PointerLeave`.
2922    pub fn on_hover<F>(&mut self, node_id: NodeId, callback: F)
2923    where
2924        F: FnMut(&UiEvent) + 'static,
2925    {
2926        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2927        let leave_handler: UiEventHandler = handler.clone();
2928        self.get_scene().with_write(
2929            |tree: &mut SceneTree| {
2930                if let Some(node) = tree.get_node_mut(node_id) {
2931                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
2932                    node.get_mut_handlers()
2933                        .set_on_pointer_leave(Some(leave_handler));
2934                }
2935            },
2936            (),
2937        );
2938    }
2939
2940    /// Registers a keyboard key-down handler on `node_id` and marks it focusable.
2941    ///
2942    /// # Arguments
2943    ///
2944    /// - `&Self` - Build context.
2945    /// - `NodeId` - Target node handle.
2946    /// - `F` - Key-down callback closure receiving `UiEventKind::KeyDown`.
2947    pub fn on_key<F>(&mut self, node_id: NodeId, callback: F)
2948    where
2949        F: FnMut(&UiEvent) + 'static,
2950    {
2951        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
2952        self.get_scene().with_write(
2953            |tree: &mut SceneTree| {
2954                if let Some(node) = tree.get_node_mut(node_id) {
2955                    node.get_mut_handlers().set_on_key_down(Some(handler));
2956                    node.get_mut_interaction().set_focusable(true);
2957                }
2958            },
2959            (),
2960        );
2961    }
2962
2963    /// Records virtualized scroll progress on `node_id` so the overlay scrollbar tracks accurately.
2964    ///
2965    /// # Arguments
2966    ///
2967    /// - `&Self` - Build context.
2968    /// - `NodeId` - Target virtualized scroll container.
2969    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
2970    /// - `f32` - Full virtualized content height in logical pixels.
2971    pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
2972        self.get_scene()
2973            .set_virtual_scroll(node_id, scroll_y, content_height);
2974    }
2975
2976    /// Sets the concrete inner pixel scroll offset on `node_id` (used by virtualized lists for sub-pixel alignment).
2977    ///
2978    /// # Arguments
2979    ///
2980    /// - `&Self` - Build context.
2981    /// - `NodeId` - Target scroll container.
2982    /// - `Point` - Scroll offset `(x, y)` in logical pixels.
2983    pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
2984        self.get_scene().with_write(
2985            |tree: &mut SceneTree| {
2986                tree.set_scroll_offset(node_id, offset);
2987            },
2988            (),
2989        );
2990    }
2991
2992    /// Starts a smooth paint/transform transition on `transition.get_node()`.
2993    ///
2994    /// # Arguments
2995    ///
2996    /// - `&Self` - Build context.
2997    /// - `NodeTransition` - Transition specification.
2998    pub fn start_transition(&mut self, transition: NodeTransition) {
2999        self.get_scene().start_transition(transition);
3000    }
3001
3002    /// Mounts a reactive dynamic subtree whose children rebuild cleanly inside an isolated `Scope`.
3003    ///
3004    /// # Arguments
3005    ///
3006    /// - `&Self` - Build context.
3007    /// - `NodeId` - Host container node.
3008    /// - `F` - Reactive zero-`ctx` builder returning child `NodeId` values.
3009    pub fn bind_children<F>(&mut self, host: NodeId, mut builder: F)
3010    where
3011        F: FnMut() -> Vec<NodeId> + 'static,
3012    {
3013        let ctx_clone: Self = self.clone();
3014        let handle: SceneHandle = self.get_scene().clone();
3015        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
3016            Effect::new(move || {
3017                let (child_scope, children): (Scope, Vec<NodeId>) =
3018                    Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
3019                let first_opt: Option<NodeId> = children.first().copied();
3020                handle.replace_children_safe(host, children);
3021                if let Some(first) = first_opt {
3022                    handle.with_write(
3023                        |tree: &mut SceneTree| {
3024                            tree.attach_scope(first, child_scope);
3025                        },
3026                        (),
3027                    );
3028                }
3029            })
3030        });
3031        self.get_scene().with_write(
3032            |tree: &mut SceneTree| {
3033                tree.attach_scope(host, scope);
3034            },
3035            (),
3036        );
3037    }
3038}
3039
3040/// Restores the previously bound ambient `Context` when leaving scope.
3041impl Drop for ContextGuard {
3042    /// Restores the saved thread-local `Context`.
3043    ///
3044    /// # Arguments
3045    ///
3046    /// - `&Self` - Mutable scope guard being dropped.
3047    fn drop(&mut self) {
3048        let Self { previous } = self;
3049        let restored: Option<Context> = previous.take();
3050        ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
3051            *slot.borrow_mut() = restored;
3052        });
3053    }
3054}
3055
3056/// `NodeRefTarget` implementation storing a `NodeId` directly into a mutable local binding.
3057impl NodeRefTarget for NodeId {
3058    /// Assigns `id` to `self`.
3059    ///
3060    /// # Arguments
3061    ///
3062    /// - `&Self` - Target `NodeId` slot.
3063    /// - `NodeId` - Mounted node handle.
3064    fn bind_node_ref(&mut self, id: NodeId) {
3065        *self = id;
3066    }
3067}
3068
3069/// `NodeRefTarget` implementation storing a `NodeId` into an `Option<NodeId>`.
3070impl NodeRefTarget for Option<NodeId> {
3071    /// Assigns `Some(id)` to `self`.
3072    ///
3073    /// # Arguments
3074    ///
3075    /// - `&Self` - Target optional `NodeId` slot.
3076    /// - `NodeId` - Mounted node handle.
3077    fn bind_node_ref(&mut self, id: NodeId) {
3078        *self = Some(id);
3079    }
3080}
3081
3082/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<NodeId>`.
3083impl NodeRefTarget for Cell<NodeId> {
3084    /// Sets `self` to `id`.
3085    ///
3086    /// # Arguments
3087    ///
3088    /// - `&Self` - Target `Cell<NodeId>`.
3089    /// - `NodeId` - Mounted node handle.
3090    fn bind_node_ref(&mut self, id: NodeId) {
3091        self.set(id);
3092    }
3093}
3094
3095/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<NodeId>>`.
3096impl NodeRefTarget for Rc<Cell<NodeId>> {
3097    /// Sets the shared cell value to `id`.
3098    ///
3099    /// # Arguments
3100    ///
3101    /// - `&Self` - Target shared `Cell<NodeId>`.
3102    /// - `NodeId` - Mounted node handle.
3103    fn bind_node_ref(&mut self, id: NodeId) {
3104        self.set(id);
3105    }
3106}
3107
3108/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<Option<NodeId>>`.
3109impl NodeRefTarget for Cell<Option<NodeId>> {
3110    /// Sets `self` to `Some(id)`.
3111    ///
3112    /// # Arguments
3113    ///
3114    /// - `&Self` - Target `Cell<Option<NodeId>>`.
3115    /// - `NodeId` - Mounted node handle.
3116    fn bind_node_ref(&mut self, id: NodeId) {
3117        self.set(Some(id));
3118    }
3119}
3120
3121/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<Option<NodeId>>>`.
3122impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
3123    /// Sets the shared cell value to `Some(id)`.
3124    ///
3125    /// # Arguments
3126    ///
3127    /// - `&Self` - Target shared `Cell<Option<NodeId>>`.
3128    /// - `NodeId` - Mounted node handle.
3129    fn bind_node_ref(&mut self, id: NodeId) {
3130        self.set(Some(id));
3131    }
3132}
3133
3134/// `TextNodeContent` implementation mounting an owned `String` as a static text node.
3135impl TextNodeContent for String {
3136    /// Mounts a static text scene node from this `String`.
3137    ///
3138    /// # Arguments
3139    ///
3140    /// - `Self` - Owned text string.
3141    /// - `&mut Context` - Active scene build context.
3142    /// - `Style` - Resolved text style.
3143    ///
3144    /// # Returns
3145    ///
3146    /// - `NodeId` - Mounted text node handle.
3147    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3148        ctx.text(self, style)
3149    }
3150}
3151
3152/// `TextNodeContent` implementation mounting a string slice as a static text node.
3153impl TextNodeContent for &str {
3154    /// Mounts a static text scene node from this `&str`.
3155    ///
3156    /// # Arguments
3157    ///
3158    /// - `Self` - Borrowed text slice.
3159    /// - `&mut Context` - Active scene build context.
3160    /// - `Style` - Resolved text style.
3161    ///
3162    /// # Returns
3163    ///
3164    /// - `NodeId` - Mounted text node handle.
3165    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3166        ctx.text(self.to_string(), style)
3167    }
3168}
3169
3170/// `TextNodeContent` implementation mounting a borrowed `&String` as a static text node.
3171impl TextNodeContent for &String {
3172    /// Mounts a static text scene node from this `&String`.
3173    ///
3174    /// # Arguments
3175    ///
3176    /// - `Self` - Borrowed string reference.
3177    /// - `&mut Context` - Active scene build context.
3178    /// - `Style` - Resolved text style.
3179    ///
3180    /// # Returns
3181    ///
3182    /// - `NodeId` - Mounted text node handle.
3183    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3184        ctx.text(self.clone(), style)
3185    }
3186}
3187
3188/// `TextNodeContent` implementation mounting a `Cow<str>` as a static text node.
3189impl TextNodeContent for Cow<'_, str> {
3190    /// Mounts a static text scene node from this `Cow<str>`.
3191    ///
3192    /// # Arguments
3193    ///
3194    /// - `Self` - Copy-on-write string value.
3195    /// - `&mut Context` - Active scene build context.
3196    /// - `Style` - Resolved text style.
3197    ///
3198    /// # Returns
3199    ///
3200    /// - `NodeId` - Mounted text node handle.
3201    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
3202        ctx.text(self.into_owned(), style)
3203    }
3204}
3205
3206/// `TextNodeContent` implementation mounting any `FnMut() -> S` closure or function item as a reactive text node.
3207impl<F, S> TextNodeContent for F
3208where
3209    F: FnMut() -> S + 'static,
3210    S: Into<String>,
3211{
3212    /// Mounts a reactive text scene node bound to this closure or function item.
3213    ///
3214    /// # Arguments
3215    ///
3216    /// - `Self` - Reactive text producer closure.
3217    /// - `&mut Context` - Active scene build context.
3218    /// - `Style` - Resolved text style.
3219    ///
3220    /// # Returns
3221    ///
3222    /// - `NodeId` - Mounted reactive text node handle.
3223    fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
3224        ctx.reactive_text(style, move || self().into())
3225    }
3226}