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