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