Skip to main content

euv_core/scene/tree/
impl.rs

1use super::*;
2
3/// Forward iteration over a node's direct children via intrusive `next_sibling` links.
4impl Iterator for SceneChildIter<'_> {
5    type Item = NodeId;
6
7    /// Advances to the next direct child in O(1) with zero heap allocation.
8    ///
9    /// # Arguments
10    ///
11    /// - `&Self` - Mutable child iterator.
12    ///
13    /// # Returns
14    ///
15    /// - `Option<Self::Item>` - Next child handle or `None` when exhausted.
16    #[inline]
17    fn next(&mut self) -> Option<Self::Item> {
18        let Self {
19            meta,
20            topology,
21            head,
22            tail,
23            remaining,
24        } = self;
25        if *remaining == 0 || *head == NODE_INDEX_NONE {
26            return None;
27        }
28        let idx: u32 = *head;
29        *remaining -= 1;
30        if *remaining == 0 || idx == *tail {
31            *head = NODE_INDEX_NONE;
32            *tail = NODE_INDEX_NONE;
33        } else {
34            *head = topology[idx as usize].get_next_sibling();
35        }
36        let generation: u32 = meta[idx as usize].get_generation();
37        Some(NodeId::new(idx, generation))
38    }
39
40    /// Returns exact lower and upper bounds on remaining children.
41    ///
42    /// # Arguments
43    ///
44    /// - `&Self` - Child iterator reference.
45    ///
46    /// # Returns
47    ///
48    /// - `(usize, Option<usize>)` - Exact remaining child count bounds.
49    #[inline]
50    fn size_hint(&self) -> (usize, Option<usize>) {
51        let Self { remaining, .. } = *self;
52        (remaining, Some(remaining))
53    }
54}
55
56/// Reverse iteration over a node's direct children via intrusive `prev_sibling` links.
57impl DoubleEndedIterator for SceneChildIter<'_> {
58    /// Advances backward from the last child in O(1) with zero heap allocation.
59    ///
60    /// # Arguments
61    ///
62    /// - `&Self` - Mutable child iterator.
63    ///
64    /// # Returns
65    ///
66    /// - `Option<Self::Item>` - Previous child handle from the back or `None` when exhausted.
67    #[inline]
68    fn next_back(&mut self) -> Option<Self::Item> {
69        let Self {
70            meta,
71            topology,
72            head,
73            tail,
74            remaining,
75        } = self;
76        if *remaining == 0 || *tail == NODE_INDEX_NONE {
77            return None;
78        }
79        let idx: u32 = *tail;
80        *remaining -= 1;
81        if *remaining == 0 || idx == *head {
82            *head = NODE_INDEX_NONE;
83            *tail = NODE_INDEX_NONE;
84        } else {
85            *tail = topology[idx as usize].get_prev_sibling();
86        }
87        let generation: u32 = meta[idx as usize].get_generation();
88        Some(NodeId::new(idx, generation))
89    }
90}
91
92/// Exact-length marker for `SceneChildIter`.
93impl ExactSizeIterator for SceneChildIter<'_> {}
94
95/// Default scene tree with a pre-created root `View` node.
96impl Default for SceneTree {
97    /// Allocates a new `SceneTree` containing a root container node.
98    ///
99    /// # Returns
100    ///
101    /// - `Self` - Initialized scene tree.
102    fn default() -> Self {
103        let root_style: Style = Style::default()
104            .column()
105            .width(Length::Percent(100.0))
106            .height(Length::Percent(100.0));
107        let root_compact: CompactPaintStyle =
108            CompactPaintStyle::from_paint(root_style.paint_ref(), EFFECT_ID_NONE);
109        let root_node: SceneNode = SceneNode::new(1, NodeKind::View, root_style);
110        Self {
111            nodes: vec![root_node],
112            meta: vec![NodeMeta::new(1, NODE_FLAG_ALIVE, DIRTY_ALL)],
113            topology: vec![NodeTopology::default()],
114            compact_paints: vec![root_compact],
115            effect_table: EffectTable::new(),
116            free_list: Vec::new(),
117            live_count: 1,
118            live_lifecycle_count: 0,
119            root: NodeId::new(0, 1),
120            focus: FocusManager::default(),
121            revision: 1,
122            transitions: Vec::new(),
123            caret_visible: true,
124            portal_nodes: Vec::new(),
125            scroll_nodes: Vec::new(),
126            dirty_paint_nodes: Vec::new(),
127            full_damage_pending: true,
128            layout_damage_pending: true,
129            full_damage_overflow: false,
130            created_since_damage: 0,
131            extra_logical_damage: Vec::new(),
132            text_selection: None,
133            text_selection_spans: Vec::new(),
134            backdrop_blur_nodes: Vec::new(),
135            layout_invalidations: 1,
136            last_collect_composite_only: false,
137            theme_entries: HashMap::new(),
138            paint_epochs: vec![0],
139            has_stale_hidden_dirty: false,
140        }
141    }
142}
143
144/// Generation-guarded theme ownership and origin snapshot bookkeeping for in-place theme remaps.
145impl SceneTree {
146    /// Returns the live generation of `id`, or `None` when the handle is stale or disposed.
147    ///
148    /// # Arguments
149    ///
150    /// - `&Self` - Scene tree reference.
151    /// - `NodeId` - Target node handle.
152    ///
153    /// # Returns
154    ///
155    /// - `Option<u32>` - Live generation when `id` refers to an alive node.
156    fn live_generation(&self, id: NodeId) -> Option<u32> {
157        let meta: &NodeMeta = self.get_meta().get(id.as_usize())?;
158        ((meta.get_flags() & NODE_FLAG_ALIVE) != 0 && meta.get_generation() == id.get_generation())
159            .then_some(id.get_generation())
160    }
161
162    /// Returns the generation-validated theme entry for `id`.
163    ///
164    /// # Arguments
165    ///
166    /// - `&Self` - Scene tree reference.
167    /// - `NodeId` - Target node handle.
168    ///
169    /// # Returns
170    ///
171    /// - `Option<ThemeNodeEntry>` - Entry when present and belonging to the live generation.
172    fn theme_entry(&self, id: NodeId) -> Option<ThemeNodeEntry> {
173        let generation: u32 = self.live_generation(id)?;
174        let Self { theme_entries, .. } = self;
175        theme_entries
176            .get(&id.get_index())
177            .copied()
178            .filter(|entry: &ThemeNodeEntry| entry.get_generation() == generation)
179    }
180
181    /// Updates (or creates) the generation-validated theme entry for `id` via `apply`.
182    ///
183    /// # Arguments
184    ///
185    /// - `&Self` - Mutable scene tree.
186    /// - `NodeId` - Target node handle.
187    /// - `F` - Mutation applied to the fresh or existing entry.
188    fn update_theme_entry<F>(&mut self, id: NodeId, apply: F)
189    where
190        F: FnOnce(&mut ThemeNodeEntry),
191    {
192        let Some(generation) = self.live_generation(id) else {
193            return;
194        };
195        let Self { theme_entries, .. } = self;
196        let entry: &mut ThemeNodeEntry = theme_entries
197            .entry(id.get_index())
198            .or_insert_with(|| ThemeNodeEntry::new(generation, false, None));
199        if entry.get_generation() != generation {
200            *entry = ThemeNodeEntry::new(generation, false, None);
201        }
202        apply(entry);
203    }
204
205    /// Marks `id` as reactively theme-owned by its component so generic in-place theme remaps skip its paint.
206    ///
207    /// # Arguments
208    ///
209    /// - `&Self` - Mutable scene tree.
210    /// - `NodeId` - Target node handle.
211    /// - `bool` - Whether the component owns the node's themed paint.
212    pub fn set_theme_owned(&mut self, id: NodeId, owned: bool) {
213        if !owned && self.theme_entry(id).is_none() {
214            return;
215        }
216        self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
217            entry.set_owned(owned);
218        });
219    }
220
221    /// Returns whether `id` is reactively theme-owned by its component.
222    ///
223    /// # Arguments
224    ///
225    /// - `&Self` - Scene tree reference.
226    /// - `NodeId` - Target node handle.
227    ///
228    /// # Returns
229    ///
230    /// - `bool` - `true` when generic theme remaps must skip `id`.
231    #[must_use]
232    pub fn is_theme_owned(&self, id: NodeId) -> bool {
233        self.theme_entry(id)
234            .is_some_and(|entry: ThemeNodeEntry| entry.get_owned())
235    }
236
237    /// Returns the theme-origin paint snapshot recorded for `id`.
238    ///
239    /// # Arguments
240    ///
241    /// - `&Self` - Scene tree reference.
242    /// - `NodeId` - Target node handle.
243    ///
244    /// # Returns
245    ///
246    /// - `Option<ThemeBaseline>` - Recorded origin snapshot, if any.
247    #[must_use]
248    pub fn theme_baseline(&self, id: NodeId) -> Option<ThemeBaseline> {
249        self.theme_entry(id)
250            .and_then(|entry: ThemeNodeEntry| entry.get_baseline())
251    }
252
253    /// Records (or clears) the theme-origin paint snapshot for `id`.
254    ///
255    /// # Arguments
256    ///
257    /// - `&Self` - Mutable scene tree.
258    /// - `NodeId` - Target node handle.
259    /// - `Option<ThemeBaseline>` - Origin snapshot to store, or `None` to clear.
260    pub fn set_theme_baseline(&mut self, id: NodeId, baseline: Option<ThemeBaseline>) {
261        if baseline.is_none() && self.theme_entry(id).is_none() {
262            return;
263        }
264        self.update_theme_entry(id, |entry: &mut ThemeNodeEntry| {
265            entry.set_baseline(baseline);
266        });
267    }
268}
269
270/// Core retained scene graph mutation and traversal operations.
271impl SceneTree {
272    /// Registers or removes a backdrop-blur effect radius on `id` for effect-dependency damage propagation and paint emission.
273    ///
274    /// # Arguments
275    ///
276    /// - `&Self` - Mutable scene tree.
277    /// - `NodeId` - Target scene node handle.
278    /// - `f32` - Gaussian backdrop blur radius in logical pixels (`<= 0.0` removes backdrop blur).
279    pub fn set_backdrop_blur(&mut self, id: NodeId, blur_radius: f32) {
280        if self.get_node(id).is_none() {
281            return;
282        }
283        let clamped: f32 = if blur_radius.is_finite() {
284            blur_radius.clamp(0.0, 96.0)
285        } else {
286            0.0
287        };
288        let prev_radius: f32 = self.backdrop_blur_radius(id);
289        if (prev_radius - clamped).abs() <= 0.001 {
290            return;
291        }
292        if prev_radius > 0.0 {
293            self.record_node_logical_damage(id);
294        }
295        let blurs: &mut Vec<(NodeId, f32)> = self.get_mut_backdrop_blur_nodes();
296        if clamped <= 0.0 {
297            blurs.retain(|entry: &(NodeId, f32)| entry.0 != id);
298        } else if let Some(slot) = blurs
299            .iter_mut()
300            .find(|entry: &&mut (NodeId, f32)| entry.0 == id)
301        {
302            slot.1 = clamped;
303        } else {
304            blurs.push((id, clamped));
305        }
306        let paint_copy: Option<PaintStyle> =
307            self.get_node(id).map(|node: &SceneNode| *node.paint_ref());
308        if let Some(paint) = paint_copy {
309            self.sync_node_compact_paint(id.as_usize(), &paint, clamped);
310        }
311        self.mark_dirty(id, DIRTY_PAINT);
312    }
313
314    /// Returns the configured backdrop-blur radius in logical pixels for `id` (`0.0` when unset).
315    ///
316    /// # Arguments
317    ///
318    /// - `&Self` - Scene tree reference.
319    /// - `NodeId` - Target scene node handle.
320    ///
321    /// # Returns
322    ///
323    /// - `f32` - Active backdrop-blur radius in logical pixels.
324    #[must_use]
325    pub fn backdrop_blur_radius(&self, id: NodeId) -> f32 {
326        for &(nid, radius) in self.get_backdrop_blur_nodes().iter() {
327            if nid == id {
328                return radius;
329            }
330        }
331        0.0
332    }
333
334    /// Returns `true` when at least one live node has an active backdrop-blur effect.
335    ///
336    /// # Arguments
337    ///
338    /// - `&Self` - Scene tree reference.
339    ///
340    /// # Returns
341    ///
342    /// - `bool` - Whether backdrop-blur effect dependency tracking is active.
343    #[must_use]
344    pub fn has_backdrop_blur_nodes(&self) -> bool {
345        !self.get_backdrop_blur_nodes().is_empty()
346    }
347
348    /// Expands `damage` to include every visible backdrop-blur node whose sampling region intersects any damaged rect (fixpoint propagation).
349    ///
350    /// # Arguments
351    ///
352    /// - `&Self` - Scene tree reference.
353    /// - `&mut DamageRegion` - Active physical damage region to expand.
354    /// - `f32` - Active display scale factor.
355    ///
356    /// # Returns
357    ///
358    /// - `usize` - Number of backdrop-blur nodes added to `damage` due to overlapping underlying mutations.
359    pub fn propagate_effect_damage(&self, damage: &mut DamageRegion, scale: f32) -> usize {
360        if damage.get_full_damage() || self.get_backdrop_blur_nodes().is_empty() {
361            return 0;
362        }
363        let clamped_scale: f32 = scale.max(0.5);
364        let blur_count: usize = self.get_backdrop_blur_nodes().len();
365        let mut dirtied: Vec<bool> = vec![false; blur_count];
366        let mut total_added: usize = 0;
367        let mut changed: bool = true;
368        while changed && !damage.get_full_damage() {
369            changed = false;
370            if damage.bounds_rect().is_none() {
371                break;
372            }
373            for (idx, &(nid, blur_radius)) in self.get_backdrop_blur_nodes().iter().enumerate() {
374                if dirtied[idx] || blur_radius <= 0.0 || !self.is_node_visible(nid) {
375                    continue;
376                }
377                let Some(screen_rect) = self.node_screen_bounds(nid) else {
378                    continue;
379                };
380                if screen_rect.get_width() <= 0.0 || screen_rect.get_height() <= 0.0 {
381                    continue;
382                }
383                let sigma: f32 = (blur_radius * 0.5).max(0.75);
384                let halo: f32 = (sigma * 3.0).ceil() + 2.0;
385                let sample_logical: Rect = Rect::new(
386                    screen_rect.get_x() - halo,
387                    screen_rect.get_y() - halo,
388                    screen_rect.get_width() + halo * 2.0,
389                    screen_rect.get_height() + halo * 2.0,
390                );
391                let sample_phys: Rect =
392                    Self::scale_logical_to_phys_rect(sample_logical, clamped_scale);
393                let output_phys: Rect = Self::scale_logical_to_phys_rect(
394                    Rect::new(
395                        screen_rect.get_x() - 2.0,
396                        screen_rect.get_y() - 2.0,
397                        screen_rect.get_width() + 4.0,
398                        screen_rect.get_height() + 4.0,
399                    ),
400                    clamped_scale,
401                );
402                let (rects, count): ([Rect; 8], usize) =
403                    damage.normalized_rects(u32::MAX, u32::MAX);
404                let overlaps: bool = rects
405                    .iter()
406                    .take(count)
407                    .any(|r: &Rect| r.intersect(sample_phys).is_some());
408                if overlaps {
409                    damage.add_rect(output_phys);
410                    dirtied[idx] = true;
411                    total_added += 1;
412                    changed = true;
413                }
414            }
415        }
416        total_added
417    }
418    /// Returns the incrementally maintained slice of live `NodeKind::Portal` and `Position::Fixed` nodes.
419    ///
420    /// # Arguments
421    ///
422    /// - `&Self` - Scene tree reference.
423    ///
424    /// # Returns
425    ///
426    /// - `&[NodeId]` - Live top-layer portal and fixed-position node handles.
427    #[must_use]
428    #[inline(always)]
429    pub fn portal_nodes(&self) -> &[NodeId] {
430        let Self { portal_nodes, .. } = self;
431        portal_nodes.as_slice()
432    }
433
434    /// Returns `true` when at least one live `NodeKind::Portal` or `Position::Fixed` node is registered.
435    ///
436    /// # Arguments
437    ///
438    /// - `&Self` - Scene tree reference.
439    ///
440    /// # Returns
441    ///
442    /// - `bool` - Whether any top-layer portal or fixed node exists in the scene.
443    #[must_use]
444    #[inline(always)]
445    pub fn has_portal_nodes(&self) -> bool {
446        let Self { portal_nodes, .. } = self;
447        !portal_nodes.is_empty()
448    }
449
450    /// Synchronizes `id` membership in `portal_nodes` and `NODE_FLAG_IS_PORTAL` whenever a top-layer node is created, mutated, or disposed.
451    ///
452    /// # Arguments
453    ///
454    /// - `&Self` - Mutable scene tree.
455    /// - `NodeId` - Target node handle.
456    /// - `bool` - Whether the node currently qualifies as a `Portal` or `Position::Fixed` top-layer node.
457    fn sync_portal_registration(&mut self, id: NodeId, is_portal: bool) {
458        if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
459            let next: u16 = if is_portal {
460                meta.get_flags() | NODE_FLAG_IS_PORTAL
461            } else {
462                meta.get_flags() & !NODE_FLAG_IS_PORTAL
463            };
464            let _: &mut NodeMeta = meta.set_flags(next);
465        }
466        let portals: &mut Vec<NodeId> = self.get_mut_portal_nodes();
467        if is_portal {
468            if !portals.contains(&id) {
469                portals.push(id);
470            }
471        } else if !portals.is_empty() {
472            portals.retain(|existing: &NodeId| *existing != id);
473        }
474    }
475
476    /// Returns the incrementally maintained slice of live `Overflow::Scroll` container nodes.
477    ///
478    /// # Arguments
479    ///
480    /// - `&Self` - Scene tree reference.
481    ///
482    /// # Returns
483    ///
484    /// - `&[NodeId]` - Live scroll container node handles.
485    #[must_use]
486    #[inline(always)]
487    pub fn scroll_nodes(&self) -> &[NodeId] {
488        let Self { scroll_nodes, .. } = self;
489        scroll_nodes.as_slice()
490    }
491
492    /// Returns `true` when at least one live `Overflow::Scroll` container is registered.
493    ///
494    /// # Arguments
495    ///
496    /// - `&Self` - Scene tree reference.
497    ///
498    /// # Returns
499    ///
500    /// - `bool` - Whether any scroll container exists in the scene.
501    #[must_use]
502    #[inline(always)]
503    pub fn has_scroll_nodes(&self) -> bool {
504        let Self { scroll_nodes, .. } = self;
505        !scroll_nodes.is_empty()
506    }
507
508    /// Synchronizes `id` membership in `scroll_nodes` and `NODE_FLAG_IS_SCROLL_CONTAINER`.
509    ///
510    /// # Arguments
511    ///
512    /// - `&Self` - Mutable scene tree.
513    /// - `NodeId` - Target node handle.
514    /// - `bool` - Whether the node currently uses `Overflow::Scroll`.
515    fn sync_scroll_registration(&mut self, id: NodeId, is_scroll: bool) {
516        if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
517            let next: u16 = if is_scroll {
518                meta.get_flags() | NODE_FLAG_IS_SCROLL_CONTAINER
519            } else {
520                meta.get_flags() & !NODE_FLAG_IS_SCROLL_CONTAINER
521            };
522            let _: &mut NodeMeta = meta.set_flags(next);
523        }
524        let scrolls: &mut Vec<NodeId> = self.get_mut_scroll_nodes();
525        if is_scroll {
526            if !scrolls.contains(&id) {
527                scrolls.push(id);
528            }
529        } else if !scrolls.is_empty() {
530            scrolls.retain(|existing: &NodeId| *existing != id);
531        }
532    }
533
534    /// Synchronizes the 32-byte `CompactPaintStyle` and sparse `EffectTable` slot for node index `idx`.
535    ///
536    /// # Arguments
537    ///
538    /// - `&Self` - Mutable scene tree.
539    /// - `usize` - Node arena slot index.
540    /// - `&PaintStyle` - Current paint style reference.
541    /// - `f32` - Active backdrop blur radius in logical pixels.
542    fn sync_node_compact_paint(&mut self, idx: usize, paint: &PaintStyle, blur: f32) {
543        let prev_effect_id: u32 = self
544            .get_compact_paints()
545            .get(idx)
546            .map(CompactPaintStyle::get_effect_id)
547            .unwrap_or(EFFECT_ID_NONE);
548        let entry: PaintEffectEntry = PaintEffectEntry::from_paint_and_blur(paint, blur);
549        let next_effect_id: u32 = self.get_mut_effect_table().update(prev_effect_id, entry);
550        let compact: CompactPaintStyle = CompactPaintStyle::from_paint(paint, next_effect_id);
551        if let Some(slot) = self.get_mut_compact_paints().get_mut(idx) {
552            *slot = compact;
553        }
554    }
555
556    /// Returns the 32-byte `CompactPaintStyle` stored in dense SoA for live node `id`.
557    ///
558    /// # Arguments
559    ///
560    /// - `&Self` - Scene tree reference.
561    /// - `NodeId` - Target node handle.
562    ///
563    /// # Returns
564    ///
565    /// - `Option<&CompactPaintStyle>` - Borrowed 32-byte compact paint style if live.
566    #[must_use]
567    #[inline(always)]
568    pub fn compact_paint(&self, id: NodeId) -> Option<&CompactPaintStyle> {
569        let idx: usize = id.as_usize();
570        let meta: &NodeMeta = self.get_meta().get(idx)?;
571        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
572        {
573            return None;
574        }
575        self.get_compact_paints().get(idx)
576    }
577
578    /// Returns the sparse `PaintEffectEntry` for `id` in O(1) (`None` when `effect_id == EFFECT_ID_NONE`).
579    ///
580    /// # Arguments
581    ///
582    /// - `&Self` - Scene tree reference.
583    /// - `NodeId` - Target node handle.
584    ///
585    /// # Returns
586    ///
587    /// - `Option<&PaintEffectEntry>` - Borrowed rare paint effect entry if active.
588    #[must_use]
589    #[inline(always)]
590    pub fn paint_effect(&self, id: NodeId) -> Option<&PaintEffectEntry> {
591        let effect_id: u32 = self.compact_paint(id)?.get_effect_id();
592        self.get_effect_table().get(effect_id)
593    }
594
595    /// Returns a shared reference to the sparse `EffectTable` owned by this scene tree.
596    ///
597    /// # Arguments
598    ///
599    /// - `&Self` - Scene tree reference.
600    ///
601    /// # Returns
602    ///
603    /// - `&EffectTable` - Borrowed sparse effect table.
604    #[must_use]
605    #[inline(always)]
606    pub fn effect_table(&self) -> &EffectTable {
607        self.get_effect_table()
608    }
609
610    /// Returns whether live node `id` has lazily allocated cold `NodeExtras` metadata.
611    ///
612    /// # Arguments
613    ///
614    /// - `&Self` - Scene tree reference.
615    /// - `NodeId` - Target node handle.
616    ///
617    /// # Returns
618    ///
619    /// - `bool` - `true` when `NODE_FLAG_HAS_EXTRAS` is set on `id`.
620    #[must_use]
621    #[inline(always)]
622    pub fn has_extras(&self, id: NodeId) -> bool {
623        let Some(node) = self.get_node(id) else {
624            return false;
625        };
626        node.has_extras()
627    }
628
629    /// Returns whether live container `id` has at least one direct child with a non-zero `z_index` in O(1).
630    ///
631    /// # Arguments
632    ///
633    /// - `&Self` - Scene tree reference.
634    /// - `NodeId` - Parent container node handle.
635    ///
636    /// # Returns
637    ///
638    /// - `bool` - `true` when `NODE_FLAG_HAS_NONZERO_Z_CHILD` is set on `id`.
639    #[must_use]
640    #[inline(always)]
641    pub fn has_nonzero_z_child(&self, id: NodeId) -> bool {
642        let idx: usize = id.as_usize();
643        let Some(meta) = self.get_meta().get(idx) else {
644            return false;
645        };
646        (meta.get_flags() & NODE_FLAG_ALIVE) != 0
647            && meta.get_generation() == id.get_generation()
648            && (meta.get_flags() & NODE_FLAG_HAS_NONZERO_Z_CHILD) != 0
649    }
650
651    /// Returns whether live node `id` has any attached `Lifecycle` observer in O(1).
652    ///
653    /// # Arguments
654    ///
655    /// - `&Self` - Scene tree reference.
656    /// - `NodeId` - Target node handle.
657    ///
658    /// # Returns
659    ///
660    /// - `bool` - `true` when `NODE_FLAG_HAS_LIFECYCLE` is set on `id`.
661    #[must_use]
662    #[inline(always)]
663    pub fn has_lifecycle(&self, id: NodeId) -> bool {
664        let idx: usize = id.as_usize();
665        let Some(meta) = self.get_meta().get(idx) else {
666            return false;
667        };
668        (meta.get_flags() & NODE_FLAG_ALIVE) != 0
669            && meta.get_generation() == id.get_generation()
670            && (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
671    }
672
673    /// Returns whether live node `id` owns a reactive `Scope` in O(1).
674    ///
675    /// # Arguments
676    ///
677    /// - `&Self` - Scene tree reference.
678    /// - `NodeId` - Target node handle.
679    ///
680    /// # Returns
681    ///
682    /// - `bool` - `true` when `NODE_FLAG_HAS_SCOPE` is set on `id`.
683    #[must_use]
684    #[inline(always)]
685    pub fn has_scope(&self, id: NodeId) -> bool {
686        let idx: usize = id.as_usize();
687        let Some(meta) = self.get_meta().get(idx) else {
688            return false;
689        };
690        (meta.get_flags() & NODE_FLAG_ALIVE) != 0
691            && meta.get_generation() == id.get_generation()
692            && (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
693    }
694
695    /// Returns a zero-allocation double-ended iterator over the direct children of `parent`.
696    ///
697    /// # Arguments
698    ///
699    /// - `&Self` - Scene tree reference.
700    /// - `NodeId` - Parent container node handle.
701    ///
702    /// # Returns
703    ///
704    /// - `SceneChildIter<'_>` - Zero-alloc forward/reverse iterator over direct children.
705    #[must_use]
706    #[inline(always)]
707    pub fn children_iter(&self, parent: NodeId) -> SceneChildIter<'_> {
708        let idx: usize = parent.as_usize();
709        let valid: bool = self.get_meta().get(idx).is_some_and(|meta: &NodeMeta| {
710            (meta.get_flags() & NODE_FLAG_ALIVE) != 0
711                && meta.get_generation() == parent.get_generation()
712        });
713        if !valid {
714            return SceneChildIter {
715                meta: self.get_meta().as_slice(),
716                topology: self.get_topology().as_slice(),
717                head: NODE_INDEX_NONE,
718                tail: NODE_INDEX_NONE,
719                remaining: 0,
720            };
721        }
722        let topo: NodeTopology = self.get_topology()[idx];
723        SceneChildIter {
724            meta: self.get_meta().as_slice(),
725            topology: self.get_topology().as_slice(),
726            head: topo.get_first_child(),
727            tail: topo.get_last_child(),
728            remaining: topo.get_child_count() as usize,
729        }
730    }
731
732    /// Visits every direct child of `parent` in paint order with zero heap allocation.
733    ///
734    /// # Arguments
735    ///
736    /// - `&Self` - Scene tree reference.
737    /// - `NodeId` - Parent container node handle.
738    /// - `F` - Visitor callback invoked with each child `NodeId`.
739    #[inline]
740    pub fn for_each_child<F>(&self, parent: NodeId, mut visit: F)
741    where
742        F: FnMut(NodeId),
743    {
744        for child_id in self.children_iter(parent) {
745            visit(child_id);
746        }
747    }
748
749    /// Visits every direct child of `parent` in reverse paint order with zero heap allocation.
750    ///
751    /// # Arguments
752    ///
753    /// - `&Self` - Scene tree reference.
754    /// - `NodeId` - Parent container node handle.
755    /// - `F` - Visitor callback invoked with each child `NodeId` back-to-front.
756    #[inline]
757    pub fn for_each_child_rev<F>(&self, parent: NodeId, mut visit: F)
758    where
759        F: FnMut(NodeId),
760    {
761        for child_id in self.children_iter(parent).rev() {
762            visit(child_id);
763        }
764    }
765
766    /// Returns the number of direct children attached to `parent` in O(1).
767    ///
768    /// # Arguments
769    ///
770    /// - `&Self` - Scene tree reference.
771    /// - `NodeId` - Parent container node handle.
772    ///
773    /// # Returns
774    ///
775    /// - `usize` - Direct child count (`0` for leaves or stale handles).
776    #[must_use]
777    #[inline(always)]
778    pub fn child_count(&self, parent: NodeId) -> usize {
779        let idx: usize = parent.as_usize();
780        let Some(meta) = self.get_meta().get(idx) else {
781            return 0;
782        };
783        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
784            || meta.get_generation() != parent.get_generation()
785        {
786            return 0;
787        }
788        self.get_topology()[idx].get_child_count() as usize
789    }
790
791    /// Returns `true` when `parent` is live and has at least one direct child in O(1).
792    ///
793    /// # Arguments
794    ///
795    /// - `&Self` - Scene tree reference.
796    /// - `NodeId` - Parent container node handle.
797    ///
798    /// # Returns
799    ///
800    /// - `bool` - Whether `parent` has any direct children.
801    #[must_use]
802    #[inline(always)]
803    pub fn has_children(&self, parent: NodeId) -> bool {
804        self.child_count(parent) > 0
805    }
806
807    /// Returns the first direct child of `parent` in O(1).
808    ///
809    /// # Arguments
810    ///
811    /// - `&Self` - Scene tree reference.
812    /// - `NodeId` - Parent container node handle.
813    ///
814    /// # Returns
815    ///
816    /// - `Option<NodeId>` - First child handle if present.
817    #[must_use]
818    #[inline(always)]
819    pub fn first_child(&self, parent: NodeId) -> Option<NodeId> {
820        let idx: usize = parent.as_usize();
821        let meta: &NodeMeta = self.get_meta().get(idx)?;
822        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
823            || meta.get_generation() != parent.get_generation()
824        {
825            return None;
826        }
827        let first: u32 = self.get_topology()[idx].get_first_child();
828        if first == NODE_INDEX_NONE {
829            None
830        } else {
831            Some(NodeId::new(
832                first,
833                self.get_meta()[first as usize].get_generation(),
834            ))
835        }
836    }
837
838    /// Returns the last direct child of `parent` in O(1).
839    ///
840    /// # Arguments
841    ///
842    /// - `&Self` - Scene tree reference.
843    /// - `NodeId` - Parent container node handle.
844    ///
845    /// # Returns
846    ///
847    /// - `Option<NodeId>` - Last child handle if present.
848    #[must_use]
849    #[inline(always)]
850    pub fn last_child(&self, parent: NodeId) -> Option<NodeId> {
851        let idx: usize = parent.as_usize();
852        let meta: &NodeMeta = self.get_meta().get(idx)?;
853        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
854            || meta.get_generation() != parent.get_generation()
855        {
856            return None;
857        }
858        let last: u32 = self.get_topology()[idx].get_last_child();
859        if last == NODE_INDEX_NONE {
860            None
861        } else {
862            Some(NodeId::new(
863                last,
864                self.get_meta()[last as usize].get_generation(),
865            ))
866        }
867    }
868
869    /// Returns the next sibling after `id` in O(1).
870    ///
871    /// # Arguments
872    ///
873    /// - `&Self` - Scene tree reference.
874    /// - `NodeId` - Child node handle.
875    ///
876    /// # Returns
877    ///
878    /// - `Option<NodeId>` - Next sibling handle if present.
879    #[must_use]
880    #[inline(always)]
881    pub fn next_sibling(&self, id: NodeId) -> Option<NodeId> {
882        let idx: usize = id.as_usize();
883        let meta: &NodeMeta = self.get_meta().get(idx)?;
884        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
885        {
886            return None;
887        }
888        let next: u32 = self.get_topology()[idx].get_next_sibling();
889        if next == NODE_INDEX_NONE {
890            None
891        } else {
892            Some(NodeId::new(
893                next,
894                self.get_meta()[next as usize].get_generation(),
895            ))
896        }
897    }
898
899    /// Returns the previous sibling before `id` in O(1).
900    ///
901    /// # Arguments
902    ///
903    /// - `&Self` - Scene tree reference.
904    /// - `NodeId` - Child node handle.
905    ///
906    /// # Returns
907    ///
908    /// - `Option<NodeId>` - Previous sibling handle if present.
909    #[must_use]
910    #[inline(always)]
911    pub fn prev_sibling(&self, id: NodeId) -> Option<NodeId> {
912        let idx: usize = id.as_usize();
913        let meta: &NodeMeta = self.get_meta().get(idx)?;
914        if (meta.get_flags() & NODE_FLAG_ALIVE) == 0 || meta.get_generation() != id.get_generation()
915        {
916            return None;
917        }
918        let prev: u32 = self.get_topology()[idx].get_prev_sibling();
919        if prev == NODE_INDEX_NONE {
920            None
921        } else {
922            Some(NodeId::new(
923                prev,
924                self.get_meta()[prev as usize].get_generation(),
925            ))
926        }
927    }
928
929    /// Collects the direct children of `parent` into an owned `Vec<NodeId>` snapshot for callers that must mutate outside a borrow.
930    ///
931    /// # Arguments
932    ///
933    /// - `&Self` - Scene tree reference.
934    /// - `NodeId` - Parent container node handle.
935    ///
936    /// # Returns
937    ///
938    /// - `Vec<NodeId>` - Snapshot of ordered direct children.
939    #[must_use]
940    pub fn children_vec(&self, parent: NodeId) -> Vec<NodeId> {
941        self.children_iter(parent).collect()
942    }
943
944    /// Returns `true` when `candidate` equals `root` or descends from `root` in O(depth) with zero heap allocations.
945    ///
946    /// # Arguments
947    ///
948    /// - `&Self` - Scene tree reference.
949    /// - `NodeId` - Candidate descendant node handle.
950    /// - `NodeId` - Ancestor subtree root handle.
951    ///
952    /// # Returns
953    ///
954    /// - `bool` - Whether `candidate` lies inside the subtree rooted at `root`.
955    #[must_use]
956    pub fn is_in_subtree(&self, candidate: NodeId, root: NodeId) -> bool {
957        if candidate == root {
958            return true;
959        }
960        let mut cursor_idx: usize = candidate.as_usize();
961        let Some(start_meta) = self.get_meta().get(cursor_idx) else {
962            return false;
963        };
964        if (start_meta.get_flags() & NODE_FLAG_ALIVE) == 0
965            || start_meta.get_generation() != candidate.get_generation()
966        {
967            return false;
968        }
969        let root_idx: u32 = root.get_index();
970        let root_gen: u32 = root.get_generation();
971        let max_hops: usize = self.get_topology().len();
972        let mut hops: usize = 0;
973        while hops < max_hops {
974            let parent_idx: u32 = self.get_topology()[cursor_idx].get_parent();
975            if parent_idx == NODE_INDEX_NONE {
976                return false;
977            }
978            if parent_idx == root_idx
979                && self.get_meta()[parent_idx as usize].get_generation() == root_gen
980            {
981                return true;
982            }
983            cursor_idx = parent_idx as usize;
984            hops += 1;
985        }
986        false
987    }
988
989    /// Recomputes `NODE_FLAG_HAS_NONZERO_Z_CHILD` on `parent_idx` from its current direct children.
990    ///
991    /// # Arguments
992    ///
993    /// - `&Self` - Mutable scene tree.
994    /// - `usize` - Parent slot index.
995    fn recompute_nonzero_z_child(&mut self, parent_idx: usize) {
996        let mut any_nonzero: bool = false;
997        let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
998        while cur != NODE_INDEX_NONE {
999            let ci: usize = cur as usize;
1000            if self.get_nodes()[ci].layout_ref().get_z_index() != 0 {
1001                any_nonzero = true;
1002                break;
1003            }
1004            cur = self.get_topology()[ci].get_next_sibling();
1005        }
1006        if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
1007            let next: u16 = if any_nonzero {
1008                meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD
1009            } else {
1010                meta.get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD
1011            };
1012            let _: &mut NodeMeta = meta.set_flags(next);
1013        }
1014    }
1015
1016    /// Updates `NODE_FLAG_HAS_NONZERO_Z_CHILD` on `parent_idx` when a child's `z_index` changes from `prev_z` to `next_z`.
1017    ///
1018    /// # Arguments
1019    ///
1020    /// - `&Self` - Mutable scene tree.
1021    /// - `usize` - Parent slot index.
1022    /// - `i32` - Child's previous `z_index`.
1023    /// - `i32` - Child's updated `z_index`.
1024    fn sync_parent_nonzero_z(&mut self, parent_idx: usize, prev_z: i32, next_z: i32) {
1025        if next_z != 0 {
1026            if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
1027                let next: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
1028                let _: &mut NodeMeta = meta.set_flags(next);
1029            }
1030        } else if prev_z != 0 {
1031            self.recompute_nonzero_z_child(parent_idx);
1032        }
1033    }
1034
1035    /// Detaches `child_idx` from `parent_idx` in O(1) via intrusive doubly-linked sibling pointers.
1036    ///
1037    /// # Arguments
1038    ///
1039    /// - `&Self` - Mutable scene tree.
1040    /// - `usize` - Parent slot index.
1041    /// - `usize` - Child slot index currently attached to `parent_idx`.
1042    fn unlink_child_at(&mut self, parent_idx: usize, child_idx: usize) {
1043        let child_topo: NodeTopology = self.get_topology()[child_idx];
1044        if child_topo.get_parent() != parent_idx as u32 {
1045            return;
1046        }
1047        let prev: u32 = child_topo.get_prev_sibling();
1048        let next: u32 = child_topo.get_next_sibling();
1049        let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1050        if prev != NODE_INDEX_NONE {
1051            let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(next);
1052        } else {
1053            let _: &mut NodeTopology = topo[parent_idx].set_first_child(next);
1054        }
1055        if next != NODE_INDEX_NONE {
1056            let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(prev);
1057        } else {
1058            let _: &mut NodeTopology = topo[parent_idx].set_last_child(prev);
1059        }
1060        let next_count: u32 = topo[parent_idx].get_child_count().saturating_sub(1);
1061        let _: &mut NodeTopology = topo[parent_idx].set_child_count(next_count);
1062        let _: &mut NodeTopology = topo[child_idx]
1063            .set_parent(NODE_INDEX_NONE)
1064            .set_prev_sibling(NODE_INDEX_NONE)
1065            .set_next_sibling(NODE_INDEX_NONE);
1066        let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(None);
1067        let child_z: i32 = self.get_nodes()[child_idx].layout_ref().get_z_index();
1068        if child_z != 0 {
1069            self.recompute_nonzero_z_child(parent_idx);
1070        }
1071    }
1072
1073    /// Links an unattached `child_idx` at the tail of `parent_idx` in O(1) via intrusive doubly-linked sibling pointers.
1074    ///
1075    /// # Arguments
1076    ///
1077    /// - `&Self` - Mutable scene tree.
1078    /// - `usize` - Parent slot index.
1079    /// - `NodeId` - Parent node handle.
1080    /// - `usize` - Unattached child slot index.
1081    fn link_child_tail_at(&mut self, parent_idx: usize, parent_id: NodeId, child_idx: usize) {
1082        let child_u32: u32 = child_idx as u32;
1083        let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1084        let tail: u32 = topo[parent_idx].get_last_child();
1085        let _: &mut NodeTopology = topo[child_idx]
1086            .set_parent(parent_idx as u32)
1087            .set_prev_sibling(tail)
1088            .set_next_sibling(NODE_INDEX_NONE);
1089        if tail != NODE_INDEX_NONE {
1090            let _: &mut NodeTopology = topo[tail as usize].set_next_sibling(child_u32);
1091        } else {
1092            let _: &mut NodeTopology = topo[parent_idx].set_first_child(child_u32);
1093        }
1094        let next_count: u32 = topo[parent_idx].get_child_count().saturating_add(1);
1095        let _: &mut NodeTopology = topo[parent_idx]
1096            .set_last_child(child_u32)
1097            .set_child_count(next_count);
1098        let _: &mut SceneNode = self.get_mut_nodes()[child_idx].set_parent(Some(parent_id));
1099        if self.get_nodes()[child_idx].layout_ref().get_z_index() != 0 {
1100            let next_flags: u16 =
1101                self.get_meta()[parent_idx].get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
1102            let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(next_flags);
1103        }
1104    }
1105
1106    /// Detaches all direct children from `parent_idx` without disposing them, clearing `HAS_NONZERO_Z_CHILD`.
1107    ///
1108    /// # Arguments
1109    ///
1110    /// - `&Self` - Mutable scene tree.
1111    /// - `usize` - Parent slot index.
1112    fn unlink_all_children_at(&mut self, parent_idx: usize) {
1113        let mut cur: u32 = self.get_topology()[parent_idx].get_first_child();
1114        let _: &mut NodeTopology = self.get_mut_topology()[parent_idx]
1115            .set_first_child(NODE_INDEX_NONE)
1116            .set_last_child(NODE_INDEX_NONE)
1117            .set_child_count(0);
1118        let cleared: u16 = self.get_meta()[parent_idx].get_flags() & !NODE_FLAG_HAS_NONZERO_Z_CHILD;
1119        let _: &mut NodeMeta = self.get_mut_meta()[parent_idx].set_flags(cleared);
1120        while cur != NODE_INDEX_NONE {
1121            let ci: usize = cur as usize;
1122            let next: u32 = self.get_topology()[ci].get_next_sibling();
1123            let _: &mut NodeTopology = self.get_mut_topology()[ci]
1124                .set_parent(NODE_INDEX_NONE)
1125                .set_prev_sibling(NODE_INDEX_NONE)
1126                .set_next_sibling(NODE_INDEX_NONE);
1127            let _: &mut SceneNode = self.get_mut_nodes()[ci].set_parent(None);
1128            cur = next;
1129        }
1130    }
1131
1132    /// Reorders or filters `parent`'s direct children to match `new_children` without disposing detached nodes, returning `true` if modified.
1133    ///
1134    /// # Arguments
1135    ///
1136    /// - `&Self` - Mutable scene tree.
1137    /// - `NodeId` - Parent container node handle.
1138    /// - `&[NodeId]` - Desired ordered child handles.
1139    ///
1140    /// # Returns
1141    ///
1142    /// - `bool` - `true` when the parent's child sequence changed.
1143    pub fn set_children_detached(&mut self, parent: NodeId, new_children: &[NodeId]) -> bool {
1144        if self.get_node(parent).is_none() {
1145            return false;
1146        }
1147        if self.child_count(parent) == new_children.len()
1148            && self.children_iter(parent).eq(new_children.iter().copied())
1149        {
1150            return false;
1151        }
1152        let parent_idx: usize = parent.as_usize();
1153        self.unlink_all_children_at(parent_idx);
1154        for child in new_children.iter().copied() {
1155            if child == parent || self.get_node(child).is_none() {
1156                continue;
1157            }
1158            let child_idx: usize = child.as_usize();
1159            let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
1160            if prev_parent != NODE_INDEX_NONE {
1161                self.unlink_child_at(prev_parent as usize, child_idx);
1162            }
1163            self.link_child_tail_at(parent_idx, parent, child_idx);
1164        }
1165        let dirty_lay: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1166        let dirty_child: u16 = DIRTY_CHILDREN | DIRTY_PAINT;
1167        self.mark_dirty(parent, dirty_lay | dirty_child);
1168        true
1169    }
1170
1171    /// Replaces `old_child` under `parent` with `new_child` in O(1) without shifting sibling storage.
1172    ///
1173    /// # Arguments
1174    ///
1175    /// - `&Self` - Mutable scene tree.
1176    /// - `NodeId` - Parent container node handle.
1177    /// - `NodeId` - Existing direct child handle to detach.
1178    /// - `NodeId` - Replacement child handle to splice in place.
1179    ///
1180    /// # Returns
1181    ///
1182    /// - `bool` - `true` when `old_child` was replaced by `new_child`.
1183    pub fn replace_child(&mut self, parent: NodeId, old_child: NodeId, new_child: NodeId) -> bool {
1184        if old_child == new_child || new_child == parent {
1185            return false;
1186        }
1187        if self.get_node(parent).is_none()
1188            || self.get_node(old_child).is_none()
1189            || self.get_node(new_child).is_none()
1190        {
1191            return false;
1192        }
1193        let parent_idx: usize = parent.as_usize();
1194        let old_idx: usize = old_child.as_usize();
1195        let new_idx: usize = new_child.as_usize();
1196        if self.get_topology()[old_idx].get_parent() != parent_idx as u32 {
1197            return false;
1198        }
1199        let prev_parent: u32 = self.get_topology()[new_idx].get_parent();
1200        if prev_parent != NODE_INDEX_NONE {
1201            self.unlink_child_at(prev_parent as usize, new_idx);
1202        }
1203        let old_topo: NodeTopology = self.get_topology()[old_idx];
1204        let prev: u32 = old_topo.get_prev_sibling();
1205        let next: u32 = old_topo.get_next_sibling();
1206        let new_u32: u32 = new_idx as u32;
1207        let topo: &mut Vec<NodeTopology> = self.get_mut_topology();
1208        if prev != NODE_INDEX_NONE {
1209            let _: &mut NodeTopology = topo[prev as usize].set_next_sibling(new_u32);
1210        } else {
1211            let _: &mut NodeTopology = topo[parent_idx].set_first_child(new_u32);
1212        }
1213        if next != NODE_INDEX_NONE {
1214            let _: &mut NodeTopology = topo[next as usize].set_prev_sibling(new_u32);
1215        } else {
1216            let _: &mut NodeTopology = topo[parent_idx].set_last_child(new_u32);
1217        }
1218        let _: &mut NodeTopology = topo[new_idx]
1219            .set_parent(parent_idx as u32)
1220            .set_prev_sibling(prev)
1221            .set_next_sibling(next);
1222        let _: &mut NodeTopology = topo[old_idx]
1223            .set_parent(NODE_INDEX_NONE)
1224            .set_prev_sibling(NODE_INDEX_NONE)
1225            .set_next_sibling(NODE_INDEX_NONE);
1226        let _: &mut SceneNode = self.get_mut_nodes()[old_idx].set_parent(None);
1227        let _: &mut SceneNode = self.get_mut_nodes()[new_idx].set_parent(Some(parent));
1228        let old_z: i32 = self.get_nodes()[old_idx].layout_ref().get_z_index();
1229        let new_z: i32 = self.get_nodes()[new_idx].layout_ref().get_z_index();
1230        self.sync_parent_nonzero_z(parent_idx, old_z, new_z);
1231        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1232        true
1233    }
1234
1235    /// Allocates a new node of `kind` with initial `style`.
1236    ///
1237    /// # Arguments
1238    ///
1239    /// - `&Self` - Mutable scene tree.
1240    /// - `NodeKind` - Semantic node kind.
1241    /// - `Style` - Initial style.
1242    ///
1243    /// # Returns
1244    ///
1245    /// - `NodeId` - Generation-checked node handle.
1246    pub fn create_node(&mut self, kind: NodeKind, style: Style) -> NodeId {
1247        let is_portal: bool = matches!(kind, NodeKind::Portal)
1248            || style.layout_ref().get_position() == Position::Fixed;
1249        let is_scroll: bool = matches!(kind, NodeKind::ScrollView)
1250            || style.layout_ref().get_overflow() == Overflow::Scroll;
1251        let mut init_flags: u16 = NODE_FLAG_ALIVE;
1252        if is_portal {
1253            init_flags |= NODE_FLAG_IS_PORTAL;
1254        }
1255        if is_scroll {
1256            init_flags |= NODE_FLAG_IS_SCROLL_CONTAINER;
1257        }
1258        let effect_entry: PaintEffectEntry =
1259            PaintEffectEntry::from_paint_and_blur(style.paint_ref(), 0.0);
1260        let effect_id: u32 = self.get_mut_effect_table().insert(effect_entry);
1261        let compact_paint: CompactPaintStyle =
1262            CompactPaintStyle::from_paint(style.paint_ref(), effect_id);
1263        let id: NodeId = if let Some(index) = self.get_mut_free_list().pop() {
1264            let slot_idx: usize = index as usize;
1265            let slot: &mut SceneNode = &mut self.get_mut_nodes()[slot_idx];
1266            let next_gen: u32 = slot.get_generation().wrapping_add(1).max(1);
1267            *slot = SceneNode::new(next_gen, kind, style);
1268            self.get_mut_meta()[slot_idx] = NodeMeta::new(next_gen, init_flags, DIRTY_ALL);
1269            self.get_mut_topology()[slot_idx] = NodeTopology::default();
1270            self.get_mut_compact_paints()[slot_idx] = compact_paint;
1271            if let Some(ep) = self.get_mut_paint_epochs().get_mut(slot_idx) {
1272                *ep = ep.wrapping_add(1);
1273            }
1274            NodeId::new(index, next_gen)
1275        } else {
1276            let index: u32 = self.get_nodes().len() as u32;
1277            self.get_mut_nodes().push(SceneNode::new(1, kind, style));
1278            self.get_mut_meta()
1279                .push(NodeMeta::new(1, init_flags, DIRTY_ALL));
1280            self.get_mut_topology().push(NodeTopology::default());
1281            self.get_mut_compact_paints().push(compact_paint);
1282            self.get_mut_paint_epochs().push(0);
1283            NodeId::new(index, 1)
1284        };
1285        if is_portal {
1286            self.get_mut_portal_nodes().push(id);
1287            self.set_full_damage_pending(true);
1288            self.clear_dirty_paint_queue();
1289        }
1290        if is_scroll {
1291            self.get_mut_scroll_nodes().push(id);
1292        }
1293        let next_live: usize = self.get_live_count().saturating_add(1);
1294        self.set_live_count(next_live);
1295        let next_created: usize = self.get_created_since_damage().saturating_add(1);
1296        self.set_created_since_damage(next_created);
1297        self.set_layout_damage_pending(true);
1298        self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
1299        if next_created > DIRTY_PAINT_FULL_THRESHOLD {
1300            self.set_full_damage_pending(true);
1301            self.set_full_damage_overflow(true);
1302            self.clear_dirty_paint_queue();
1303        } else if !self.get_full_damage_pending() {
1304            if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
1305                self.set_full_damage_pending(true);
1306                self.set_full_damage_overflow(true);
1307                self.clear_dirty_paint_queue();
1308            } else {
1309                self.get_mut_dirty_paint_nodes().push(id);
1310                if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
1311                    let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
1312                    let _: &mut NodeMeta = meta.set_flags(next_flags);
1313                }
1314            }
1315        }
1316        let next_rev: u64 = self.get_revision().wrapping_add(1);
1317        self.set_revision(next_rev);
1318        notify_frame_needed();
1319        id
1320    }
1321
1322    /// Creates a container `View` node.
1323    ///
1324    /// # Arguments
1325    ///
1326    /// - `&Self` - Mutable scene tree.
1327    /// - `Style` - Initial box style.
1328    ///
1329    /// # Returns
1330    ///
1331    /// - `NodeId` - Created node handle.
1332    pub fn create_view(&mut self, style: Style) -> NodeId {
1333        self.create_node(NodeKind::View, style)
1334    }
1335
1336    /// Creates a `Text` node holding `content`.
1337    ///
1338    /// # Arguments
1339    ///
1340    /// - `&Self` - Mutable scene tree.
1341    /// - `String` - Initial UTF-8 text.
1342    /// - `Style` - Initial text and box style.
1343    ///
1344    /// # Returns
1345    ///
1346    /// - `NodeId` - Created text node handle.
1347    pub fn create_text(&mut self, content: String, style: Style) -> NodeId {
1348        self.create_node(NodeKind::Text(content), style)
1349    }
1350
1351    /// Creates an editable `Input` node.
1352    ///
1353    /// # Arguments
1354    ///
1355    /// - `&Self` - Mutable scene tree.
1356    /// - `InputNodeState` - Initial input state.
1357    /// - `Style` - Initial input style.
1358    ///
1359    /// # Returns
1360    ///
1361    /// - `NodeId` - Created input node handle.
1362    pub fn create_input(&mut self, state: InputNodeState, style: Style) -> NodeId {
1363        self.create_node(NodeKind::Input(state), style)
1364    }
1365
1366    /// Creates an `Image` node displaying `buffer`.
1367    ///
1368    /// # Arguments
1369    ///
1370    /// - `&Self` - Mutable scene tree.
1371    /// - `ImageBuffer` - Decoded RGBA8 image buffer.
1372    /// - `Style` - Initial image style.
1373    ///
1374    /// # Returns
1375    ///
1376    /// - `NodeId` - Created image node handle.
1377    pub fn create_image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
1378        self.create_node(NodeKind::Image(buffer), style)
1379    }
1380
1381    /// Creates a `ScrollView` container with `Overflow::Scroll`.
1382    ///
1383    /// # Arguments
1384    ///
1385    /// - `&Self` - Mutable scene tree.
1386    /// - `Style` - Initial scroll container style.
1387    ///
1388    /// # Returns
1389    ///
1390    /// - `NodeId` - Created scroll view handle.
1391    pub fn create_scroll_view(&mut self, style: Style) -> NodeId {
1392        self.create_node(NodeKind::ScrollView, style.overflow(Overflow::Scroll))
1393    }
1394
1395    /// Creates a custom `Canvas` node bound to `painter` using `CanvasCaching::DynamicPerFrame`.
1396    ///
1397    /// # Arguments
1398    ///
1399    /// - `&Self` - Mutable scene tree.
1400    /// - `Style` - Initial canvas style.
1401    /// - `CanvasDrawCallback` - Draw callback invoked on each paint pass.
1402    ///
1403    /// # Returns
1404    ///
1405    /// - `NodeId` - Created canvas node handle.
1406    pub fn create_canvas(&mut self, style: Style, painter: CanvasDrawCallback) -> NodeId {
1407        self.create_canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
1408    }
1409
1410    /// Creates a custom `Canvas` node bound to `painter` with an explicit `CanvasCaching` policy.
1411    ///
1412    /// # Arguments
1413    ///
1414    /// - `&Self` - Mutable scene tree.
1415    /// - `Style` - Initial canvas style.
1416    /// - `CanvasCaching` - Fragment caching strategy (`DynamicPerFrame` or `RetainedStatic`).
1417    /// - `CanvasDrawCallback` - Draw callback invoked on paint.
1418    ///
1419    /// # Returns
1420    ///
1421    /// - `NodeId` - Created canvas node handle.
1422    pub fn create_canvas_with_caching(
1423        &mut self,
1424        style: Style,
1425        caching: CanvasCaching,
1426        painter: CanvasDrawCallback,
1427    ) -> NodeId {
1428        let id: NodeId = self.create_node(NodeKind::Canvas(caching), style);
1429        if let Some(node) = self.get_node_mut(id) {
1430            node.set_canvas_painter(Some(painter));
1431        }
1432        if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
1433            let next: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
1434            let _: &mut NodeMeta = meta.set_flags(next);
1435        }
1436        id
1437    }
1438
1439    /// Creates an overlay `Portal` node rendered in the top stacking context.
1440    ///
1441    /// # Arguments
1442    ///
1443    /// - `&Self` - Mutable scene tree.
1444    /// - `Style` - Initial portal style.
1445    ///
1446    /// # Returns
1447    ///
1448    /// - `NodeId` - Created portal node handle.
1449    pub fn create_portal(&mut self, style: Style) -> NodeId {
1450        self.create_node(NodeKind::Portal, style)
1451    }
1452
1453    /// Creates a logical `Fragment` grouping node.
1454    ///
1455    /// # Arguments
1456    ///
1457    /// - `&Self` - Mutable scene tree.
1458    ///
1459    /// # Returns
1460    ///
1461    /// - `NodeId` - Created fragment node handle.
1462    pub fn create_fragment(&mut self) -> NodeId {
1463        self.create_node(NodeKind::Fragment, Style::default())
1464    }
1465
1466    /// Returns an immutable reference to a live node matching `id`.
1467    ///
1468    /// # Arguments
1469    ///
1470    /// - `&Self` - Scene tree reference.
1471    /// - `NodeId` - Node handle.
1472    ///
1473    /// # Returns
1474    ///
1475    /// - `Option<&SceneNode>` - Live node reference if valid.
1476    #[must_use]
1477    pub fn get_node(&self, id: NodeId) -> Option<&SceneNode> {
1478        let node: &SceneNode = self.get_nodes().get(id.as_usize())?;
1479        if node.get_alive() && node.get_generation() == id.get_generation() {
1480            Some(node)
1481        } else {
1482            None
1483        }
1484    }
1485
1486    /// Returns a mutable reference to a live node matching `id`.
1487    ///
1488    /// # Arguments
1489    ///
1490    /// - `&Self` - Mutable scene tree.
1491    /// - `NodeId` - Node handle.
1492    ///
1493    /// # Returns
1494    ///
1495    /// - `Option<&mut SceneNode>` - Mutable live node reference if valid.
1496    pub fn get_node_mut(&mut self, id: NodeId) -> Option<&mut SceneNode> {
1497        let node: &mut SceneNode = self.get_mut_nodes().get_mut(id.as_usize())?;
1498        if node.get_alive() && node.get_generation() == id.get_generation() {
1499            Some(node)
1500        } else {
1501            None
1502        }
1503    }
1504
1505    /// Returns total count of live scene nodes in O(1).
1506    ///
1507    /// # Arguments
1508    ///
1509    /// - `&Self` - Scene tree reference.
1510    ///
1511    /// # Returns
1512    ///
1513    /// - `usize` - Number of live nodes in the arena.
1514    #[must_use]
1515    #[inline(always)]
1516    pub fn live_node_count(&self) -> usize {
1517        self.get_live_count()
1518    }
1519
1520    /// Appends `child` to `parent` in O(1) via intrusive sibling links and marks layout and paint dirty upward.
1521    ///
1522    /// # Arguments
1523    ///
1524    /// - `&Self` - Mutable scene tree.
1525    /// - `NodeId` - Parent container node.
1526    /// - `NodeId` - Child node to attach.
1527    pub fn append_child(&mut self, parent: NodeId, child: NodeId) {
1528        if parent == child || self.get_node(parent).is_none() || self.get_node(child).is_none() {
1529            return;
1530        }
1531        let parent_idx: usize = parent.as_usize();
1532        let child_idx: usize = child.as_usize();
1533        let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
1534        if let Some(old_parent) = prev_parent {
1535            if old_parent != parent {
1536                self.record_subtree_logical_damage(child);
1537            }
1538            self.unlink_child_at(old_parent.as_usize(), child_idx);
1539            if old_parent != parent {
1540                self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
1541            }
1542        }
1543        self.link_child_tail_at(parent_idx, parent, child_idx);
1544        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1545    }
1546
1547    /// Appends multiple `children` to `parent` in a single dirty-marking pass with zero heap allocations.
1548    ///
1549    /// # Arguments
1550    ///
1551    /// - `&Self` - Mutable scene tree.
1552    /// - `NodeId` - Parent container node.
1553    /// - `&[NodeId]` - Ordered child nodes to append.
1554    pub fn append_children(&mut self, parent: NodeId, children: &[NodeId]) {
1555        if children.is_empty() || self.get_node(parent).is_none() {
1556            return;
1557        }
1558        let parent_idx: usize = parent.as_usize();
1559        let mut attached_any: bool = false;
1560        for child in children.iter().copied() {
1561            if child == parent || self.get_node(child).is_none() {
1562                continue;
1563            }
1564            let child_idx: usize = child.as_usize();
1565            let prev_parent: Option<NodeId> = self.get_nodes()[child_idx].parent_id();
1566            if let Some(old_parent) = prev_parent {
1567                if old_parent != parent {
1568                    self.record_subtree_logical_damage(child);
1569                }
1570                self.unlink_child_at(old_parent.as_usize(), child_idx);
1571                if old_parent != parent {
1572                    self.mark_dirty(old_parent, DIRTY_CHILDREN_CHANGE_MASK);
1573                }
1574            }
1575            self.link_child_tail_at(parent_idx, parent, child_idx);
1576            attached_any = true;
1577        }
1578        if attached_any {
1579            self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1580        }
1581    }
1582
1583    /// Replaces all children of `parent` with `new_children`, disposing previous subtrees cleanly.
1584    ///
1585    /// # Arguments
1586    ///
1587    /// - `&Self` - Mutable scene tree.
1588    /// - `NodeId` - Parent container node.
1589    /// - `Vec<NodeId>` - Replacement ordered children.
1590    pub fn replace_children(&mut self, parent: NodeId, new_children: Vec<NodeId>) {
1591        if self.get_node(parent).is_none() {
1592            return;
1593        }
1594        let parent_idx: usize = parent.as_usize();
1595        let old_children: Vec<NodeId> = self.children_vec(parent);
1596        self.unlink_all_children_at(parent_idx);
1597        if new_children.is_empty() {
1598            for old_child in old_children.into_iter() {
1599                self.dispose_subtree(old_child);
1600            }
1601        } else if old_children.len() > 16 && new_children.len() > 16 {
1602            let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
1603            for old_child in old_children.into_iter() {
1604                if !keep_set.contains(&old_child) {
1605                    self.dispose_subtree(old_child);
1606                }
1607            }
1608        } else {
1609            for old_child in old_children.into_iter() {
1610                if !new_children.contains(&old_child) {
1611                    self.dispose_subtree(old_child);
1612                }
1613            }
1614        }
1615        for child in new_children.into_iter() {
1616            if child == parent || self.get_node(child).is_none() {
1617                continue;
1618            }
1619            let child_idx: usize = child.as_usize();
1620            let prev_parent: u32 = self.get_topology()[child_idx].get_parent();
1621            if prev_parent != NODE_INDEX_NONE {
1622                self.unlink_child_at(prev_parent as usize, child_idx);
1623            }
1624            self.link_child_tail_at(parent_idx, parent, child_idx);
1625        }
1626        self.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
1627    }
1628
1629    /// Returns `true` when `prev` and `next` paint styles differ solely in `transform` or non-zero-crossing `opacity`.
1630    ///
1631    /// # Arguments
1632    ///
1633    /// - `&PaintStyle` - Previous paint style reference.
1634    /// - `&PaintStyle` - Candidate replacement paint style reference.
1635    ///
1636    /// # Returns
1637    ///
1638    /// - `bool` - `true` when the change qualifies for the composite-only pass without repainting node contents.
1639    #[inline]
1640    fn is_composite_only_paint_change(prev: &PaintStyle, next: &PaintStyle) -> bool {
1641        let same_static: bool = prev.background_color() == next.background_color()
1642            && prev.background_gradient() == next.background_gradient()
1643            && prev.get_border() == next.get_border()
1644            && prev.get_radius() == next.get_radius()
1645            && prev.box_shadow() == next.box_shadow()
1646            && prev.focus_ring_border() == next.focus_ring_border()
1647            && prev.get_cursor() == next.get_cursor()
1648            && prev.get_pointer_events() == next.get_pointer_events();
1649        let same_vis: bool = (prev.get_opacity() > 0.0) == (next.get_opacity() > 0.0);
1650        let composite_changed: bool = prev.get_transform() != next.get_transform()
1651            || (prev.get_opacity() - next.get_opacity()).abs() > 0.0001;
1652        same_static && same_vis && composite_changed
1653    }
1654
1655    /// Computes the minimal dirty bitmask and optional portal update comparing `prev` and `next` styles by reference.
1656    ///
1657    /// # Arguments
1658    ///
1659    /// - `&Style` - Previous compiled style reference.
1660    /// - `&Style` - Candidate replacement style reference.
1661    /// - `bool` - Whether the target node is already `NodeKind::Portal`.
1662    ///
1663    /// # Returns
1664    ///
1665    /// - `(u16, Option<bool>)` - Tuple `(dirty_mask, portal_update)`; `dirty_mask == DIRTY_NONE` on no-op writes.
1666    #[inline]
1667    fn diff_style_change(prev: &Style, next: &Style, is_portal_kind: bool) -> (u16, Option<bool>) {
1668        let layout_changed: bool = prev.layout_ref() != next.layout_ref();
1669        let text_metrics_changed: bool = !prev.text_ref().same_layout_metrics(next.text_ref());
1670        if layout_changed || text_metrics_changed {
1671            let prev_fixed: bool = prev.layout_ref().get_position() == Position::Fixed;
1672            let next_fixed: bool = next.layout_ref().get_position() == Position::Fixed;
1673            let portal_update: Option<bool> = if !is_portal_kind && prev_fixed != next_fixed {
1674                Some(next_fixed)
1675            } else {
1676                None
1677            };
1678            let layout_bits: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
1679            let visual_bits: u16 = DIRTY_TEXT | DIRTY_PAINT;
1680            let mask: u16 = layout_bits | visual_bits;
1681            return (mask, portal_update);
1682        }
1683        let paint_changed: bool = prev.paint_ref() != next.paint_ref();
1684        let text_visual_changed: bool = prev.text_ref() != next.text_ref();
1685        if paint_changed && !text_visual_changed {
1686            if Self::is_composite_only_paint_change(prev.paint_ref(), next.paint_ref()) {
1687                return (DIRTY_COMPOSITE, None);
1688            }
1689            return (DIRTY_PAINT, None);
1690        }
1691        if paint_changed || text_visual_changed {
1692            (DIRTY_PAINT, None)
1693        } else {
1694            (DIRTY_NONE, None)
1695        }
1696    }
1697
1698    /// Returns `true` when transitioning from `prev` to `next` paint style can shrink shadows, borders, transforms, or hide children.
1699    ///
1700    /// # Arguments
1701    ///
1702    /// - `&PaintStyle` - Previous paint style reference.
1703    /// - `&PaintStyle` - Replacement paint style reference.
1704    ///
1705    /// # Returns
1706    ///
1707    /// - `bool` - Whether the node's pre-mutation conservative bounds must be snapshotted before overwriting style.
1708    #[inline]
1709    fn needs_pre_paint_damage(prev: &PaintStyle, next: &PaintStyle) -> bool {
1710        let shadow_changed: bool = prev.box_shadow() != next.box_shadow();
1711        let transform_changed: bool = prev.get_transform() != next.get_transform();
1712        let border_shrank: bool = prev.get_border().get_width() > next.get_border().get_width();
1713        let focus_removed: bool =
1714            prev.focus_ring_border().is_some() && next.focus_ring_border().is_none();
1715        let opacity_toggled_zero: bool = (prev.get_opacity() > 0.0) != (next.get_opacity() > 0.0);
1716        let a: bool = shadow_changed || transform_changed;
1717        let b: bool = border_shrank || focus_removed;
1718        let ab: bool = a || b;
1719        ab || opacity_toggled_zero
1720    }
1721
1722    /// Surgically updates a node's `Style`, marking only `DIRTY_PAINT` for pure paint changes and skipping no-op writes.
1723    ///
1724    /// # Arguments
1725    ///
1726    /// - `&Self` - Mutable scene tree.
1727    /// - `NodeId` - Target node handle.
1728    /// - `Style` - Replacement compiled style.
1729    pub fn set_style(&mut self, id: NodeId, style: Style) {
1730        let has_children: bool = self.has_children(id);
1731        let Some(node) = self.get_node(id) else {
1732            return;
1733        };
1734        let is_portal_kind: bool = matches!(node.get_kind(), NodeKind::Portal);
1735        let is_scroll_kind: bool = matches!(node.get_kind(), NodeKind::ScrollView);
1736        let prev: &Style = node.style_ref();
1737        let (dirty_mask, portal_update): (u16, Option<bool>) =
1738            Self::diff_style_change(prev, &style, is_portal_kind);
1739        if dirty_mask == DIRTY_NONE {
1740            return;
1741        }
1742        let prev_scroll: bool =
1743            is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
1744        let next_scroll: bool =
1745            is_scroll_kind || style.layout_ref().get_overflow() == Overflow::Scroll;
1746        let scroll_update: Option<bool> = if prev_scroll != next_scroll {
1747            Some(next_scroll)
1748        } else {
1749            None
1750        };
1751        let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), style.paint_ref());
1752        let subtree_hidden: bool = pre_paint
1753            && (prev.paint_ref().get_opacity() > 0.0) != (style.paint_ref().get_opacity() > 0.0)
1754            && has_children;
1755        let prev_z: i32 = prev.layout_ref().get_z_index();
1756        let parent_idx: u32 = self.get_topology()[id.as_usize()].get_parent();
1757        if subtree_hidden {
1758            self.record_subtree_logical_damage(id);
1759        } else if pre_paint {
1760            self.record_node_logical_damage(id);
1761        }
1762        let hiding_now: bool = style.layout_ref().get_display() == Display::None
1763            || style.paint_ref().get_opacity() <= 0.001
1764            || style.paint_ref().get_pointer_events() == PointerEvents::None;
1765        let next_z: i32 = style.layout_ref().get_z_index();
1766        let next_paint: PaintStyle = *style.paint_ref();
1767        if let Some(node) = self.get_node_mut(id) {
1768            node.set_style(style);
1769        }
1770        let blur: f32 = self.backdrop_blur_radius(id);
1771        self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
1772        if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
1773            self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
1774        }
1775        if hiding_now {
1776            self.clear_subtree_hover(id);
1777        }
1778        if let Some(is_portal) = portal_update {
1779            self.sync_portal_registration(id, is_portal);
1780        }
1781        if let Some(is_scroll) = scroll_update {
1782            self.sync_scroll_registration(id, is_scroll);
1783        }
1784        self.mark_dirty(id, dirty_mask);
1785    }
1786
1787    /// Mutates a node's `Style` in place and marks the minimal dirty mask (`DIRTY_PAINT` vs layout) only if changed.
1788    ///
1789    /// # Arguments
1790    ///
1791    /// - `&Self` - Mutable scene tree.
1792    /// - `NodeId` - Target node handle.
1793    /// - `F` - In-place style mutator closure receiving `&mut Style`.
1794    ///
1795    /// # Returns
1796    ///
1797    /// - `bool` - `true` when the node existed and its style changed.
1798    pub fn mutate_style<F>(&mut self, id: NodeId, mutator: F) -> bool
1799    where
1800        F: FnOnce(&mut Style),
1801    {
1802        let has_children: bool = self.has_children(id);
1803        let prev_opt: Option<(Style, bool, bool, u32)> =
1804            self.get_node(id).map(|node: &SceneNode| {
1805                (
1806                    *node.style_ref(),
1807                    matches!(node.get_kind(), NodeKind::Portal),
1808                    matches!(node.get_kind(), NodeKind::ScrollView),
1809                    self.get_topology()[id.as_usize()].get_parent(),
1810                )
1811            });
1812        let Some((prev, is_portal_kind, is_scroll_kind, parent_idx)) = prev_opt else {
1813            return false;
1814        };
1815        let mut next: Style = prev;
1816        mutator(&mut next);
1817        let (dirty_mask, portal_update): (u16, Option<bool>) =
1818            Self::diff_style_change(&prev, &next, is_portal_kind);
1819        if dirty_mask == DIRTY_NONE {
1820            return false;
1821        }
1822        let prev_scroll: bool =
1823            is_scroll_kind || prev.layout_ref().get_overflow() == Overflow::Scroll;
1824        let next_scroll: bool =
1825            is_scroll_kind || next.layout_ref().get_overflow() == Overflow::Scroll;
1826        let scroll_update: Option<bool> = if prev_scroll != next_scroll {
1827            Some(next_scroll)
1828        } else {
1829            None
1830        };
1831        let pre_paint: bool = Self::needs_pre_paint_damage(prev.paint_ref(), next.paint_ref());
1832        if pre_paint {
1833            let opacity_toggled_zero: bool =
1834                (prev.paint_ref().get_opacity() > 0.0) != (next.paint_ref().get_opacity() > 0.0);
1835            if opacity_toggled_zero && has_children {
1836                self.record_subtree_logical_damage(id);
1837            } else {
1838                self.record_node_logical_damage(id);
1839            }
1840        }
1841        let hiding_now: bool = next.layout_ref().get_display() == Display::None
1842            || next.paint_ref().get_opacity() <= 0.001
1843            || next.paint_ref().get_pointer_events() == PointerEvents::None;
1844        let prev_z: i32 = prev.layout_ref().get_z_index();
1845        let next_z: i32 = next.layout_ref().get_z_index();
1846        let next_paint: PaintStyle = *next.paint_ref();
1847        if let Some(node) = self.get_node_mut(id) {
1848            node.set_style(next);
1849        }
1850        let blur: f32 = self.backdrop_blur_radius(id);
1851        self.sync_node_compact_paint(id.as_usize(), &next_paint, blur);
1852        if prev_z != next_z && parent_idx != NODE_INDEX_NONE {
1853            self.sync_parent_nonzero_z(parent_idx as usize, prev_z, next_z);
1854        }
1855        if hiding_now {
1856            self.clear_subtree_hover(id);
1857        }
1858        if let Some(is_portal) = portal_update {
1859            self.sync_portal_registration(id, is_portal);
1860        }
1861        if let Some(is_scroll) = scroll_update {
1862            self.sync_scroll_registration(id, is_scroll);
1863        }
1864        self.mark_dirty(id, dirty_mask);
1865        true
1866    }
1867
1868    /// Surgically updates the UTF-8 string of a `NodeKind::Text` node.
1869    ///
1870    /// # Arguments
1871    ///
1872    /// - `&Self` - Mutable scene tree.
1873    /// - `NodeId` - Target text node handle.
1874    /// - `String` - Replacement text string.
1875    pub fn set_text(&mut self, id: NodeId, text: String) {
1876        let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
1877            Some(node) => {
1878                let layout: &LayoutStyle = node.style_ref().layout_ref();
1879                let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
1880                    && matches!(layout.get_height(), Length::Px(_));
1881                match node.get_mut_kind() {
1882                    NodeKind::Text(current) => {
1883                        if *current == text {
1884                            (false, has_fixed)
1885                        } else {
1886                            *current = text;
1887                            (true, has_fixed)
1888                        }
1889                    }
1890                    _ => (false, false),
1891                }
1892            }
1893            None => (false, false),
1894        };
1895        if changed {
1896            let mask: u16 = if fixed_size {
1897                DIRTY_PAINT
1898            } else {
1899                DIRTY_TEXT_CHANGE_MASK
1900            };
1901            self.mark_dirty(id, mask);
1902        }
1903    }
1904
1905    /// Replaces the UTF-8 contents of a `NodeKind::Text` node in place from a borrowed `&str`, reusing existing `String` capacity with zero allocation.
1906    ///
1907    /// # Arguments
1908    ///
1909    /// - `&Self` - Mutable scene tree.
1910    /// - `NodeId` - Target text node handle.
1911    /// - `&str` - Replacement text slice.
1912    pub fn set_text_str(&mut self, id: NodeId, text: &str) {
1913        let (changed, fixed_size): (bool, bool) = match self.get_node_mut(id) {
1914            Some(node) => {
1915                let layout: &LayoutStyle = node.style_ref().layout_ref();
1916                let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
1917                    && matches!(layout.get_height(), Length::Px(_));
1918                match node.get_mut_kind() {
1919                    NodeKind::Text(current) => {
1920                        if current.as_str() == text {
1921                            (false, has_fixed)
1922                        } else {
1923                            current.clear();
1924                            current.push_str(text);
1925                            (true, has_fixed)
1926                        }
1927                    }
1928                    _ => (false, false),
1929                }
1930            }
1931            None => (false, false),
1932        };
1933        if changed {
1934            let mask: u16 = if fixed_size {
1935                DIRTY_PAINT
1936            } else {
1937                DIRTY_TEXT_CHANGE_MASK
1938            };
1939            self.mark_dirty(id, mask);
1940        }
1941    }
1942
1943    /// Mutates a `NodeKind::Text` node's backing `String` buffer directly in place via `mutate` with zero heap allocations.
1944    ///
1945    /// # Arguments
1946    ///
1947    /// - `&Self` - Mutable scene tree.
1948    /// - `NodeId` - Target text node handle.
1949    /// - `F` - Closure writing the updated text into the existing `&mut String` buffer.
1950    pub fn mutate_text<F>(&mut self, id: NodeId, mutate: F)
1951    where
1952        F: FnOnce(&mut String),
1953    {
1954        let (updated, fixed_size): (bool, bool) = match self.get_node_mut(id) {
1955            Some(node) => {
1956                let layout: &LayoutStyle = node.style_ref().layout_ref();
1957                let has_fixed: bool = matches!(layout.get_width(), Length::Px(_))
1958                    && matches!(layout.get_height(), Length::Px(_));
1959                match node.get_mut_kind() {
1960                    NodeKind::Text(current) => {
1961                        mutate(current);
1962                        (true, has_fixed)
1963                    }
1964                    _ => (false, false),
1965                }
1966            }
1967            None => (false, false),
1968        };
1969        if updated {
1970            let mask: u16 = if fixed_size {
1971                DIRTY_PAINT
1972            } else {
1973                DIRTY_TEXT_CHANGE_MASK
1974            };
1975            self.mark_dirty(id, mask);
1976        }
1977    }
1978
1979    /// Updates scroll offset on a scroll container without triggering full subtree re-layout.
1980    ///
1981    /// # Arguments
1982    ///
1983    /// - `&Self` - Mutable scene tree.
1984    /// - `NodeId` - Target scroll container handle.
1985    /// - `Point` - New scroll offset clamped to content bounds.
1986    pub fn set_scroll_offset(&mut self, id: NodeId, offset: Point) {
1987        let changed: bool = match self.get_node_mut(id) {
1988            Some(node) => {
1989                let layout_box: LayoutBox = node.get_layout_box();
1990                let unlaid_out: bool = layout_box.get_content_size().get_width() <= 0.0
1991                    && layout_box.get_content_size().get_height() <= 0.0
1992                    && layout_box.get_content_bounds().get_width() <= 0.0
1993                    && layout_box.get_content_bounds().get_height() <= 0.0;
1994                let clamped: Point = if unlaid_out || node.virtual_scroll_metrics().is_some() {
1995                    Point::new(offset.get_x().max(0.0), offset.get_y().max(0.0))
1996                } else {
1997                    let max_x: f32 = (layout_box.get_content_size().get_width()
1998                        - layout_box.get_content_bounds().get_width())
1999                    .max(0.0);
2000                    let max_y: f32 = (layout_box.get_content_size().get_height()
2001                        - layout_box.get_content_bounds().get_height())
2002                    .max(0.0);
2003                    Point::new(
2004                        offset.get_x().clamp(0.0, max_x),
2005                        offset.get_y().clamp(0.0, max_y),
2006                    )
2007                };
2008                if layout_box.get_scroll_offset() == clamped {
2009                    false
2010                } else {
2011                    node.get_mut_layout_box().set_scroll_offset(clamped);
2012                    true
2013                }
2014            }
2015            None => false,
2016        };
2017        if changed {
2018            self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
2019        }
2020    }
2021
2022    /// Records virtualized scroll progress `(scroll_y, content_height)` on `id` for overlay scrollbar rendering.
2023    ///
2024    /// # Arguments
2025    ///
2026    /// - `&Self` - Mutable scene tree.
2027    /// - `NodeId` - Target virtualized scroll container.
2028    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
2029    /// - `f32` - Full virtualized content height in logical pixels.
2030    pub fn set_virtual_scroll(&mut self, id: NodeId, scroll_y: f32, content_height: f32) {
2031        let mut changed: bool = false;
2032        let mut prev_metrics: Option<(f32, f32)> = None;
2033        let next_metrics: (f32, f32) = (scroll_y.max(0.0), content_height.max(1.0));
2034        let mut scrollbar_bounds: Option<(Rect, f32, f32)> = None;
2035        if let Some(node) = self.get_node_mut(id) {
2036            let prev: Option<(f32, f32)> = node.virtual_scroll_metrics();
2037            prev_metrics = prev;
2038            let next: Option<(f32, f32)> = Some(next_metrics);
2039            if prev != next {
2040                changed = true;
2041                node.set_virtual_scroll(next);
2042                let raw_b: Rect = node.get_layout_box().get_bounds();
2043                let bw: f32 = node.style_ref().paint_ref().get_border().get_width();
2044                let view_h: f32 = node
2045                    .get_layout_box()
2046                    .get_content_bounds()
2047                    .get_height()
2048                    .max(1.0);
2049                if raw_b.get_width() > 0.0 && raw_b.get_height() > 0.0 {
2050                    scrollbar_bounds = Some((raw_b, bw, view_h));
2051                }
2052            }
2053        }
2054        if changed {
2055            if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2056                let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_EXTRAS;
2057                let _: &mut NodeMeta = meta.set_flags(next_flags);
2058            }
2059            let show_scrollbar: bool = self
2060                .get_node(self.get_root())
2061                .map(|r: &SceneNode| {
2062                    let rb: Rect = r.get_layout_box().get_bounds();
2063                    rb.get_width().min(rb.get_height()) >= 540.0
2064                })
2065                .unwrap_or(true);
2066            if !show_scrollbar {
2067                let next_rev: u64 = self.get_revision().wrapping_add(1);
2068                self.set_revision(next_rev);
2069            } else if let Some((raw_b, bw, view_h)) = scrollbar_bounds
2070                && let Some(screen_b) = self.node_screen_bounds(id)
2071                && screen_b.get_width() > 0.0
2072                && screen_b.get_height() > 0.0
2073            {
2074                let inner_y: f32 = screen_b.get_y() + bw;
2075                let inner_h: f32 = (raw_b.get_height() - bw * 2.0).max(1.0);
2076                let track_y: f32 = inner_y + 3.0;
2077                let track_h: f32 = (inner_h - 6.0).max(16.0);
2078                let n_max_sy: f32 = (next_metrics.1 - view_h).max(0.0);
2079                let n_ratio: f32 = (view_h / next_metrics.1.max(view_h)).clamp(0.0, 1.0);
2080                let n_thumb_h: f32 = (track_h * n_ratio).clamp(20.0_f32.min(track_h), track_h);
2081                let n_frac: f32 = if n_max_sy > 1.0 {
2082                    (next_metrics.0 / n_max_sy).clamp(0.0, 1.0)
2083                } else {
2084                    0.0
2085                };
2086                let ny0: f32 = track_y + (track_h - n_thumb_h) * n_frac;
2087                let ny1: f32 = ny0 + n_thumb_h;
2088                let (y0, y1): (f32, f32) = match prev_metrics {
2089                    Some((py, ph)) => {
2090                        let p_max_sy: f32 = (ph - view_h).max(0.0);
2091                        let p_ratio: f32 = (view_h / ph.max(view_h)).clamp(0.0, 1.0);
2092                        let p_thumb_h: f32 =
2093                            (track_h * p_ratio).clamp(20.0_f32.min(track_h), track_h);
2094                        let p_frac: f32 = if p_max_sy > 1.0 {
2095                            (py / p_max_sy).clamp(0.0, 1.0)
2096                        } else {
2097                            0.0
2098                        };
2099                        let py0: f32 = track_y + (track_h - p_thumb_h) * p_frac;
2100                        let py1: f32 = py0 + p_thumb_h;
2101                        (py0.min(ny0) - 4.0, py1.max(ny1) + 4.0)
2102                    }
2103                    None => (screen_b.get_y(), screen_b.bottom()),
2104                };
2105                let clamped_y0: f32 = y0.max(screen_b.get_y());
2106                let clamped_y1: f32 = y1.min(screen_b.bottom());
2107                let strip_x: f32 = (screen_b.right() - bw - 12.0).max(screen_b.get_x());
2108                let strip_w: f32 = (screen_b.right() - strip_x + 2.0).max(1.0);
2109                let strip_rect: Rect = Rect::new(
2110                    strip_x,
2111                    clamped_y0,
2112                    strip_w,
2113                    (clamped_y1 - clamped_y0).max(1.0),
2114                );
2115                if !self.get_full_damage_pending() {
2116                    if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2117                        self.set_full_damage_pending(true);
2118                        self.set_full_damage_overflow(true);
2119                        self.get_mut_extra_logical_damage().clear();
2120                    } else {
2121                        self.get_mut_extra_logical_damage().push(strip_rect);
2122                    }
2123                }
2124                let next_rev: u64 = self.get_revision().wrapping_add(1);
2125                self.set_revision(next_rev);
2126            } else {
2127                self.mark_dirty(id, DIRTY_SCROLL | DIRTY_COMPOSITE);
2128            }
2129        }
2130    }
2131
2132    /// Computes screen-space logical bounds for `id` after applying ancestor scroll offsets and transforms.
2133    ///
2134    /// Returns `Some(Rect::default())` when `id` or any ancestor has `Display::None`, preserving zero-area semantics even when descendants retain warm layout caches.
2135    ///
2136    /// # Arguments
2137    ///
2138    /// - `&Self` - Scene tree reference.
2139    /// - `NodeId` - Target node handle.
2140    ///
2141    /// # Returns
2142    ///
2143    /// - `Option<Rect>` - Screen-space rectangle if the node is alive.
2144    #[must_use]
2145    pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
2146        let node: &SceneNode = self.get_node(id)?;
2147        let (off, tx, ty, sx, sy): (Point, f32, f32, f32, f32) =
2148            match self.node_scroll_and_transform(node) {
2149                Some(vals) => vals,
2150                None => return Some(Rect::default()),
2151            };
2152        let raw: Rect = node.get_layout_box().get_bounds();
2153        Some(Rect::new(
2154            raw.get_x() - off.get_x() + tx,
2155            raw.get_y() - off.get_y() + ty,
2156            raw.get_width() * sx,
2157            raw.get_height() * sy,
2158        ))
2159    }
2160
2161    /// Computes accumulated ancestor scroll offset and combined 2D transform for `node` in a single ancestor walk.
2162    ///
2163    /// # Arguments
2164    ///
2165    /// - `&Self` - Scene tree reference.
2166    /// - `&SceneNode` - Borrowed target scene node.
2167    ///
2168    /// # Returns
2169    ///
2170    /// - `Option<(Point, f32, f32, f32, f32)>` - Tuple `(scroll_offset, tx, ty, scale_x, scale_y)`, or `None` when `node` or any ancestor has `Display::None`.
2171    #[inline]
2172    fn node_scroll_and_transform(&self, node: &SceneNode) -> Option<(Point, f32, f32, f32, f32)> {
2173        let style: &Style = node.style_ref();
2174        if style.layout_ref().get_display() == Display::None {
2175            return None;
2176        }
2177        let tr: Transform2D = style.paint_ref().get_transform();
2178        let mut tx: f32 = tr.get_translate_x();
2179        let mut ty: f32 = tr.get_translate_y();
2180        let sx_scale: f32 = tr.get_scale_x();
2181        let sy_scale: f32 = tr.get_scale_y();
2182        let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
2183            || style.layout_ref().get_position() == Position::Fixed;
2184        let mut stop_transform: bool = false;
2185        let mut scroll_x: f32 = 0.0;
2186        let mut scroll_y: f32 = 0.0;
2187        let mut cursor: Option<NodeId> = node.parent_id();
2188        while let Some(pid) = cursor {
2189            if let Some(pnode) = self.get_node(pid) {
2190                let pstyle: &Style = pnode.style_ref();
2191                if pstyle.layout_ref().get_display() == Display::None {
2192                    return None;
2193                }
2194                if !stop_transform {
2195                    let ptr: Transform2D = pstyle.paint_ref().get_transform();
2196                    tx += ptr.get_translate_x();
2197                    ty += ptr.get_translate_y();
2198                    if !start_top_layer {
2199                        let off: Point = pnode.get_layout_box().get_scroll_offset();
2200                        scroll_x += off.get_x();
2201                        scroll_y += off.get_y();
2202                    }
2203                    let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
2204                        || pstyle.layout_ref().get_position() == Position::Fixed;
2205                    if parent_top_layer {
2206                        stop_transform = true;
2207                    }
2208                }
2209                cursor = pnode.parent_id();
2210            } else {
2211                break;
2212            }
2213        }
2214        Some((Point::new(scroll_x, scroll_y), tx, ty, sx_scale, sy_scale))
2215    }
2216
2217    /// Computes a conservative logical screen-space paint rectangle for `id` including ancestor scroll, transform, border, focus ring, and `3 * sigma` shadow halo.
2218    ///
2219    /// Returns `None` when a non-axis-aligned rotation or ancestor scale requires a safe full-viewport fallback.
2220    ///
2221    /// # Arguments
2222    ///
2223    /// - `&Self` - Scene tree reference.
2224    /// - `NodeId` - Target scene node handle.
2225    ///
2226    /// # Returns
2227    ///
2228    /// - `Option<Rect>` - Conservative logical screen bounds, `Some(Rect::default())` when unmeasured, or `None` for unsafe fallback.
2229    #[must_use]
2230    pub(crate) fn node_conservative_logical_rect(&self, id: NodeId) -> Option<Rect> {
2231        let node: &SceneNode = self.get_node(id)?;
2232        let raw_bounds: Rect = node.get_layout_box().get_bounds();
2233        if raw_bounds.get_width() <= 0.0 || raw_bounds.get_height() <= 0.0 {
2234            return Some(Rect::default());
2235        }
2236        let style: &Style = node.style_ref();
2237        let paint: &PaintStyle = style.paint_ref();
2238        let tr: Transform2D = paint.get_transform();
2239        if tr.get_rotation_rad().abs() > 0.0001
2240            || tr.get_scale_x() <= 0.0
2241            || tr.get_scale_y() <= 0.0
2242        {
2243            return None;
2244        }
2245        let border_w: f32 = paint.get_border().get_width();
2246        let focus_pad: f32 = if paint.focus_ring_border().is_some() {
2247            12.0
2248        } else {
2249            0.0
2250        };
2251        let mut margin: f32 = if border_w > 0.0 {
2252            10.0_f32.max(border_w + 6.0).max(focus_pad)
2253        } else {
2254            4.0_f32.max(focus_pad)
2255        };
2256        if let Some(shadow) = paint.box_shadow() {
2257            let blur_sigma: f32 = (shadow.get_blur_radius().max(0.5) * 0.5).clamp(0.75, 48.0);
2258            let blur_pad: f32 = (blur_sigma * 3.0).ceil() + 4.0;
2259            let spread: f32 = shadow.get_spread_radius().max(0.0);
2260            let off_max: f32 = shadow.get_offset_x().abs().max(shadow.get_offset_y().abs());
2261            margin = margin.max(blur_pad + spread + off_max + 4.0);
2262        }
2263        let backdrop_blur: f32 = self.backdrop_blur_radius(id);
2264        if backdrop_blur > 0.0 {
2265            let sigma: f32 = (backdrop_blur * 0.5).max(0.75);
2266            let blur_halo: f32 = (sigma * 3.0).ceil() + 4.0;
2267            margin = margin.max(blur_halo);
2268        }
2269        let tx: f32 = tr.get_translate_x();
2270        let ty: f32 = tr.get_translate_y();
2271        let sx: f32 = tr.get_scale_x();
2272        let sy: f32 = tr.get_scale_y();
2273        let base_rect: Rect = Rect::new(
2274            raw_bounds.get_x() - margin,
2275            raw_bounds.get_y() - margin,
2276            raw_bounds.get_width() + margin * 2.0,
2277            raw_bounds.get_height() + margin * 2.0,
2278        );
2279        let shifted_x: bool = tx != 0.0 || sx != 1.0;
2280        let shifted_y: bool = ty != 0.0 || sy != 1.0;
2281        let mut cur_rect: Rect = if shifted_x || shifted_y {
2282            let scale_pad_x: f32 = ((sx - 1.0).abs() * raw_bounds.get_width()).max(0.0);
2283            let scale_pad_y: f32 = ((sy - 1.0).abs() * raw_bounds.get_height()).max(0.0);
2284            let shifted_rect: Rect = Rect::new(
2285                raw_bounds.get_x() + tx - margin - scale_pad_x,
2286                raw_bounds.get_y() + ty - margin - scale_pad_y,
2287                raw_bounds.get_width() * sx + (margin + scale_pad_x) * 2.0,
2288                raw_bounds.get_height() * sy + (margin + scale_pad_y) * 2.0,
2289            );
2290            base_rect.union(shifted_rect)
2291        } else {
2292            base_rect
2293        };
2294        let start_top_layer: bool = matches!(node.get_kind(), NodeKind::Portal)
2295            || style.layout_ref().get_position() == Position::Fixed;
2296        let mut cursor: Option<NodeId> = node.parent_id();
2297        while let Some(pid) = cursor {
2298            let Some(pnode) = self.get_node(pid) else {
2299                break;
2300            };
2301            let pstyle: &Style = pnode.style_ref();
2302            let ptr: Transform2D = pstyle.paint_ref().get_transform();
2303            if ptr.get_rotation_rad().abs() > 0.0001
2304                || (ptr.get_scale_x() - 1.0).abs() > 0.001
2305                || (ptr.get_scale_y() - 1.0).abs() > 0.001
2306            {
2307                return None;
2308            }
2309            if !start_top_layer {
2310                let off: Point = pnode.get_layout_box().get_scroll_offset();
2311                cur_rect = Rect::new(
2312                    cur_rect.get_x() - off.get_x(),
2313                    cur_rect.get_y() - off.get_y(),
2314                    cur_rect.get_width(),
2315                    cur_rect.get_height(),
2316                );
2317                let p_ov: Overflow = pstyle.layout_ref().get_overflow();
2318                if matches!(p_ov, Overflow::Hidden | Overflow::Scroll) {
2319                    let pb: Rect = pnode.get_layout_box().get_bounds();
2320                    if pb.get_width() > 0.0 && pb.get_height() > 0.0 {
2321                        let clip_box: Rect = Rect::new(
2322                            pb.get_x() - 1.0,
2323                            pb.get_y() - 1.0,
2324                            pb.get_width() + 2.0,
2325                            pb.get_height() + 2.0,
2326                        );
2327                        match cur_rect.intersect(clip_box) {
2328                            Some(clipped) => cur_rect = clipped,
2329                            None => return Some(Rect::default()),
2330                        }
2331                    }
2332                }
2333            }
2334            let ptx: f32 = ptr.get_translate_x();
2335            let pty: f32 = ptr.get_translate_y();
2336            if ptx != 0.0 || pty != 0.0 {
2337                cur_rect = Rect::new(
2338                    cur_rect.get_x() + ptx,
2339                    cur_rect.get_y() + pty,
2340                    cur_rect.get_width(),
2341                    cur_rect.get_height(),
2342                );
2343            }
2344            let parent_top_layer: bool = matches!(pnode.get_kind(), NodeKind::Portal)
2345                || pstyle.layout_ref().get_position() == Position::Fixed;
2346            if parent_top_layer {
2347                break;
2348            }
2349            cursor = pnode.parent_id();
2350        }
2351        Some(cur_rect)
2352    }
2353
2354    /// Converts a conservative logical screen rectangle into an exact outward-rounded physical pixel rectangle.
2355    ///
2356    /// # Arguments
2357    ///
2358    /// - `Rect` - Conservative logical screen rectangle.
2359    /// - `f32` - Active display scale factor.
2360    ///
2361    /// # Returns
2362    ///
2363    /// - `Rect` - Physical pixel rectangle guaranteed to enclose all covered pixels.
2364    #[must_use]
2365    pub(crate) fn scale_logical_to_phys_rect(logical: Rect, scale: f32) -> Rect {
2366        let x0: f32 = (logical.get_x() * scale).floor();
2367        let y0: f32 = (logical.get_y() * scale).floor();
2368        let x1: f32 = (logical.right() * scale).ceil();
2369        let y1: f32 = (logical.bottom() * scale).ceil();
2370        Rect::new(x0, y0, (x1 - x0).max(0.0), (y1 - y0).max(0.0))
2371    }
2372
2373    /// Records the current conservative logical bounds of `id` into `extra_logical_damage` prior to destructive mutation.
2374    ///
2375    /// # Arguments
2376    ///
2377    /// - `&Self` - Mutable scene tree.
2378    /// - `NodeId` - Target scene node handle.
2379    fn record_node_logical_damage(&mut self, id: NodeId) {
2380        if self.get_full_damage_pending() {
2381            return;
2382        }
2383        let rect_opt: Option<Rect> = self.node_conservative_logical_rect(id);
2384        match rect_opt {
2385            Some(rect) => {
2386                if rect.get_width() <= 0.0 || rect.get_height() <= 0.0 {
2387                    return;
2388                }
2389                if self.get_extra_logical_damage().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2390                    self.set_full_damage_pending(true);
2391                    self.set_full_damage_overflow(true);
2392                    self.get_mut_extra_logical_damage().clear();
2393                } else {
2394                    self.get_mut_extra_logical_damage().push(rect);
2395                }
2396            }
2397            None => {
2398                self.set_full_damage_pending(true);
2399            }
2400        }
2401    }
2402
2403    /// Records pre-mutation conservative logical bounds for every live laid-out node in the subtree rooted at `root`.
2404    ///
2405    /// # Arguments
2406    ///
2407    /// - `&Self` - Mutable scene tree.
2408    /// - `NodeId` - Subtree root handle.
2409    fn record_subtree_logical_damage(&mut self, root: NodeId) {
2410        if self.get_full_damage_pending() {
2411            return;
2412        }
2413        let mut stack: Vec<NodeId> = vec![root];
2414        let mut visited: usize = 0;
2415        while let Some(current) = stack.pop() {
2416            let Some(raw_bounds) = self
2417                .get_node(current)
2418                .map(|node: &SceneNode| node.layout_box_ref().get_bounds())
2419            else {
2420                continue;
2421            };
2422            visited += 1;
2423            if visited > DIRTY_PAINT_FULL_THRESHOLD {
2424                self.set_full_damage_pending(true);
2425                self.set_full_damage_overflow(true);
2426                self.get_mut_extra_logical_damage().clear();
2427                return;
2428            }
2429            for child in self.children_iter(current) {
2430                stack.push(child);
2431            }
2432            if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
2433                self.record_node_logical_damage(current);
2434                if self.get_full_damage_pending() {
2435                    return;
2436                }
2437            }
2438        }
2439    }
2440
2441    /// Starts or smoothly retargets a paint/transform transition on `transition.get_node()`.
2442    ///
2443    /// # Arguments
2444    ///
2445    /// - `&Self` - Mutable scene tree.
2446    /// - `NodeTransition` - Transition specification to run.
2447    pub fn start_transition(&mut self, mut transition: NodeTransition) {
2448        let target: NodeId = transition.get_node();
2449        let had_active: bool = self
2450            .get_transitions()
2451            .iter()
2452            .any(|tr: &NodeTransition| tr.get_node() == target);
2453        self.get_mut_transitions()
2454            .retain(|tr: &NodeTransition| tr.get_node() != target);
2455        if had_active && let Some(node) = self.get_node(target) {
2456            let paint: PaintStyle = node.get_style().get_paint();
2457            let tr: Transform2D = paint.get_transform();
2458            let cur_op: f32 = paint.get_opacity();
2459            let cur_tx: f32 = tr.get_translate_x();
2460            let cur_ty: f32 = tr.get_translate_y();
2461            let cur_sc: f32 = tr.get_scale_x();
2462            let full_dist: f32 = (transition.get_to_tx() - transition.get_from_tx())
2463                .hypot(transition.get_to_ty() - transition.get_from_ty())
2464                .max((transition.get_to_opacity() - transition.get_from_opacity()).abs() * 100.0);
2465            let rem_dist: f32 = (transition.get_to_tx() - cur_tx)
2466                .hypot(transition.get_to_ty() - cur_ty)
2467                .max((transition.get_to_opacity() - cur_op).abs() * 100.0);
2468            if full_dist > 0.01 {
2469                let ratio: f32 = (rem_dist / full_dist).clamp(0.20, 1.0);
2470                transition.set_duration((transition.get_duration() * ratio).max(0.05));
2471            }
2472            transition.set_from_opacity(cur_op);
2473            transition.set_from_tx(cur_tx);
2474            transition.set_from_ty(cur_ty);
2475            transition.set_from_scale(cur_sc);
2476        }
2477        self.record_node_logical_damage(target);
2478        let (opacity, transform): (f32, Transform2D) = transition.sample();
2479        let mut unhidden: bool = false;
2480        if let Some(node) = self.get_node_mut(target) {
2481            let style: &mut Style = node.get_mut_style();
2482            if !transition.get_hide_on_complete()
2483                && style.layout_ref().get_display() == Display::None
2484            {
2485                style.get_mut_layout().set_display(Display::Flex);
2486                unhidden = true;
2487            }
2488            style.get_mut_paint().set_opacity(opacity);
2489            style.get_mut_paint().set_transform(transform);
2490        }
2491        if unhidden {
2492            let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2493            self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
2494        } else {
2495            self.mark_dirty(target, DIRTY_COMPOSITE);
2496        }
2497        self.get_mut_transitions().push(transition);
2498    }
2499
2500    /// Advances all active transitions by `dt_secs` and returns `true` if any node updated.
2501    ///
2502    /// # Arguments
2503    ///
2504    /// - `&Self` - Mutable scene tree.
2505    /// - `f32` - Elapsed frame time in seconds.
2506    ///
2507    /// # Returns
2508    ///
2509    /// - `bool` - Whether at least one transition ticked on this frame.
2510    pub fn tick_transitions(&mut self, dt_secs: f32) -> bool {
2511        let len: usize = self.get_transitions().len();
2512        if len == 0 {
2513            return false;
2514        }
2515        let step: f32 = dt_secs.clamp(0.001, 0.05);
2516        let mut any_updated: bool = false;
2517        let mut write_idx: usize = 0;
2518        for read_idx in 0..len {
2519            let target: NodeId = self.get_transitions()[read_idx].get_node();
2520            if self.get_node(target).is_none() {
2521                continue;
2522            }
2523            let (done, sample_opt, hide): (bool, Option<(f32, Transform2D)>, bool) = {
2524                let tr: &mut NodeTransition = &mut self.get_mut_transitions()[read_idx];
2525                let total_span: f32 = tr.get_delay() + tr.get_duration();
2526                let prev_elapsed: f32 = tr.get_elapsed();
2527                let next_elapsed: f32 = (prev_elapsed + step).min(total_span);
2528                tr.set_elapsed(next_elapsed);
2529                let is_done: bool = tr.is_complete();
2530                let in_hold: bool =
2531                    prev_elapsed > 0.0 && next_elapsed <= tr.get_delay() && !is_done;
2532                if in_hold {
2533                    (is_done, None, false)
2534                } else {
2535                    let sampled: (f32, Transform2D) = tr.sample();
2536                    let should_hide: bool = is_done && tr.get_hide_on_complete();
2537                    (is_done, Some(sampled), should_hide)
2538                }
2539            };
2540            if let Some((opacity, transform)) = sample_opt {
2541                self.record_node_logical_damage(target);
2542                if let Some(node) = self.get_node_mut(target) {
2543                    let style: &mut Style = node.get_mut_style();
2544                    style.get_mut_paint().set_opacity(opacity);
2545                    style.get_mut_paint().set_transform(transform);
2546                    if hide {
2547                        style.get_mut_layout().set_display(Display::None);
2548                    }
2549                }
2550                if hide {
2551                    self.clear_subtree_hover(target);
2552                    let layout_dirty: u16 = DIRTY_LAYOUT | DIRTY_SUBTREE_LAYOUT;
2553                    self.mark_dirty(target, layout_dirty | DIRTY_PAINT);
2554                } else {
2555                    self.mark_dirty(target, DIRTY_COMPOSITE);
2556                }
2557                any_updated = true;
2558            }
2559            if !done {
2560                if write_idx != read_idx {
2561                    self.get_mut_transitions().swap(write_idx, read_idx);
2562                }
2563                write_idx += 1;
2564            }
2565        }
2566        self.get_mut_transitions().truncate(write_idx);
2567        any_updated
2568    }
2569
2570    /// Clears transient hover, pressed, and focus flags within `root`'s subtree in O(depth) using `FocusManager` ancestor checks.
2571    ///
2572    /// # Arguments
2573    ///
2574    /// - `&Self` - Mutable scene tree.
2575    /// - `NodeId` - Root node being hidden.
2576    pub(crate) fn clear_subtree_hover(&mut self, root: NodeId) {
2577        let hovered_opt: Option<NodeId> = self.get_focus().hovered_node();
2578        if let Some(hovered_id) = hovered_opt
2579            && self.is_in_subtree(hovered_id, root)
2580        {
2581            self.get_mut_focus().set_hovered(None);
2582            if let Some(node) = self.get_node_mut(hovered_id) {
2583                node.get_mut_interaction().set_hovered(false);
2584            }
2585        }
2586        let pressed_opt: Option<NodeId> = self.get_focus().pressed_node();
2587        if let Some(pressed_id) = pressed_opt
2588            && self.is_in_subtree(pressed_id, root)
2589        {
2590            self.get_mut_focus().set_pressed(None);
2591            if let Some(node) = self.get_node_mut(pressed_id) {
2592                node.get_mut_interaction().set_pressed(false);
2593            }
2594        }
2595        let focused_opt: Option<NodeId> = self.get_focus().focused_node();
2596        if let Some(focused_id) = focused_opt
2597            && self.is_in_subtree(focused_id, root)
2598        {
2599            self.get_mut_focus().set_focused(None);
2600            if let Some(node) = self.get_node_mut(focused_id) {
2601                node.get_mut_interaction().set_focused(false);
2602            }
2603        }
2604    }
2605
2606    /// Returns `true` while one or more node transitions are still running.
2607    ///
2608    /// # Arguments
2609    ///
2610    /// - `&Self` - Scene tree reference.
2611    ///
2612    /// # Returns
2613    ///
2614    /// - `bool` - Whether animations are active.
2615    #[must_use]
2616    pub fn has_active_transitions(&self) -> bool {
2617        !self.get_transitions().is_empty()
2618    }
2619
2620    /// Attaches a `Lifecycle` hook observer onto `id` for mount, activate, freeze, resume, unmount, and destroy dispatch.
2621    ///
2622    /// # Arguments
2623    ///
2624    /// - `&Self` - Mutable scene tree.
2625    /// - `NodeId` - Target scene node handle.
2626    /// - `Rc<dyn Lifecycle>` - Shared lifecycle hook observer.
2627    pub fn attach_lifecycle(&mut self, id: NodeId, hook: Rc<dyn Lifecycle>) {
2628        let attached: bool = if let Some(node) = self.get_node_mut(id) {
2629            node.add_lifecycle(hook);
2630            true
2631        } else {
2632            false
2633        };
2634        if attached {
2635            if let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2636                let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_LIFECYCLE;
2637                let next_flags: u16 = meta.get_flags() | add_flags;
2638                let _: &mut NodeMeta = meta.set_flags(next_flags);
2639            }
2640            let next_lc: usize = self.get_live_lifecycle_count().saturating_add(1);
2641            self.set_live_lifecycle_count(next_lc);
2642        }
2643    }
2644
2645    /// Collects all `(NodeId, Rc<dyn Lifecycle>)` observers in the subtree rooted at `root`.
2646    ///
2647    /// # Arguments
2648    ///
2649    /// - `&Self` - Scene tree reference.
2650    /// - `NodeId` - Subtree root handle.
2651    ///
2652    /// # Returns
2653    ///
2654    /// - `Vec<(NodeId, Rc<dyn Lifecycle>)>` - Ordered observers in pre-order traversal.
2655    #[must_use]
2656    pub fn collect_subtree_lifecycles(&self, root: NodeId) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
2657        if self.get_live_lifecycle_count() == 0 {
2658            return Vec::new();
2659        }
2660        let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
2661        let mut stack: Vec<NodeId> = vec![root];
2662        while let Some(current) = stack.pop() {
2663            let idx: usize = current.as_usize();
2664            let Some(meta) = self.get_meta().get(idx) else {
2665                continue;
2666            };
2667            if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
2668                || meta.get_generation() != current.get_generation()
2669            {
2670                continue;
2671            }
2672            if (meta.get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0 {
2673                for hook in self.get_nodes()[idx].lifecycle_observers().into_iter() {
2674                    out.push((current, hook));
2675                }
2676            }
2677            for child in self.children_iter(current).rev() {
2678                stack.push(child);
2679            }
2680        }
2681        out
2682    }
2683
2684    /// Collects all `Lifecycle` observers attached to visible (`Display != None`) nodes across the entire tree.
2685    ///
2686    /// # Arguments
2687    ///
2688    /// - `&Self` - Scene tree reference.
2689    ///
2690    /// # Returns
2691    ///
2692    /// - `Vec<(NodeId, Rc<dyn Lifecycle>)>` - Visible `(node, lifecycle)` observer pairs in pre-order.
2693    #[must_use]
2694    pub fn collect_visible_lifecycles(&self) -> Vec<(NodeId, Rc<dyn Lifecycle>)> {
2695        if self.get_live_lifecycle_count() == 0 {
2696            return Vec::new();
2697        }
2698        let mut out: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
2699        let mut stack: Vec<NodeId> = vec![self.get_root()];
2700        while let Some(current) = stack.pop() {
2701            if let Some(node) = self.get_node(current) {
2702                if node.layout_ref().get_display() == Display::None {
2703                    continue;
2704                }
2705                if (self.get_meta()[current.as_usize()].get_flags() & NODE_FLAG_HAS_LIFECYCLE) != 0
2706                {
2707                    for hook in node.lifecycle_observers().into_iter() {
2708                        out.push((current, hook));
2709                    }
2710                }
2711                for child in self.children_iter(current).rev() {
2712                    stack.push(child);
2713                }
2714            }
2715        }
2716        out
2717    }
2718
2719    /// Collects all reactive `ScopeId`s attached to nodes within the subtree rooted at `root`.
2720    ///
2721    /// # Arguments
2722    ///
2723    /// - `&Self` - Scene tree reference.
2724    /// - `NodeId` - Subtree root handle.
2725    ///
2726    /// # Returns
2727    ///
2728    /// - `Vec<ScopeId>` - Owned scope identifiers discovered within `root`.
2729    #[must_use]
2730    pub fn collect_subtree_scope_ids(&self, root: NodeId) -> Vec<ScopeId> {
2731        let mut out: Vec<ScopeId> = Vec::new();
2732        let mut stack: Vec<NodeId> = vec![root];
2733        while let Some(current) = stack.pop() {
2734            let idx: usize = current.as_usize();
2735            let Some(meta) = self.get_meta().get(idx) else {
2736                continue;
2737            };
2738            if (meta.get_flags() & NODE_FLAG_ALIVE) == 0
2739                || meta.get_generation() != current.get_generation()
2740            {
2741                continue;
2742            }
2743            if (meta.get_flags() & NODE_FLAG_HAS_SCOPE) != 0
2744                && let Some(scope) = self.get_nodes()[idx].owned_scope()
2745            {
2746                out.push(scope.id());
2747            }
2748            for child in self.children_iter(current).rev() {
2749                stack.push(child);
2750            }
2751        }
2752        out
2753    }
2754
2755    /// Cancels any active paint/transform transitions targeting nodes within the subtree rooted at `root`.
2756    ///
2757    /// # Arguments
2758    ///
2759    /// - `&Self` - Mutable scene tree.
2760    /// - `NodeId` - Subtree root handle.
2761    pub fn cancel_subtree_transitions(&mut self, root: NodeId) {
2762        if self.get_transitions().is_empty() {
2763            return;
2764        }
2765        let mut ids: HashSet<NodeId> = HashSet::new();
2766        let mut stack: Vec<NodeId> = vec![root];
2767        while let Some(current) = stack.pop() {
2768            if ids.insert(current) && self.get_node(current).is_some() {
2769                for child in self.children_iter(current) {
2770                    stack.push(child);
2771                }
2772            }
2773        }
2774        self.get_mut_transitions()
2775            .retain(|tr: &NodeTransition| !ids.contains(&tr.get_node()));
2776    }
2777
2778    /// Attaches a reactive `Scope` to `id` so it automatically disposes when the node unmounts.
2779    ///
2780    /// # Arguments
2781    ///
2782    /// - `&Self` - Mutable scene tree.
2783    /// - `NodeId` - Target node handle.
2784    /// - `Scope` - Reactive ownership scope.
2785    pub fn attach_scope(&mut self, id: NodeId, scope: Scope) {
2786        let attached: bool = if let Some(node) = self.get_node_mut(id) {
2787            if let Some(existing) = node.owned_scope() {
2788                existing.enter(|| {
2789                    on_cleanup(move || {
2790                        scope.dispose();
2791                    });
2792                });
2793            } else {
2794                node.set_scope(Some(scope));
2795            }
2796            true
2797        } else {
2798            false
2799        };
2800        if attached && let Some(meta) = self.get_mut_meta().get_mut(id.as_usize()) {
2801            let add_flags: u16 = NODE_FLAG_HAS_EXTRAS + NODE_FLAG_HAS_SCOPE;
2802            let next_flags: u16 = meta.get_flags() | add_flags;
2803            let _: &mut NodeMeta = meta.set_flags(next_flags);
2804        }
2805    }
2806
2807    /// Returns the monotonic per-node paint invalidation epoch for `id` in O(1).
2808    ///
2809    /// # Arguments
2810    ///
2811    /// - `&Self` - Scene tree reference.
2812    /// - `NodeId` - Target node handle.
2813    ///
2814    /// # Returns
2815    ///
2816    /// - `u32` - Wrapping monotonic paint epoch incremented on every paint/layout/content invalidation.
2817    #[must_use]
2818    #[inline(always)]
2819    pub(crate) fn node_paint_epoch(&self, id: NodeId) -> u32 {
2820        self.get_paint_epochs()
2821            .get(id.as_usize())
2822            .copied()
2823            .unwrap_or(0)
2824    }
2825
2826    /// Returns `true` when the root node currently carries any layout-pass dirty flag.
2827    ///
2828    /// # Arguments
2829    ///
2830    /// - `&Self` - Scene tree reference.
2831    ///
2832    /// # Returns
2833    ///
2834    /// - `bool` - Whether the root node requires a layout pass.
2835    #[must_use]
2836    #[inline(always)]
2837    pub(crate) fn root_has_layout_dirty(&self) -> bool {
2838        let root_id: NodeId = self.get_root();
2839        self.get_node(root_id).is_some_and(|root_node: &SceneNode| {
2840            root_node.get_dirty().intersects(DIRTY_LAYOUT_PASS_MASK)
2841        })
2842    }
2843
2844    /// Clears `dirty_paint_nodes` while resetting `NODE_FLAG_IN_DIRTY_PAINT_QUEUE` on every queued slot.
2845    ///
2846    /// # Arguments
2847    ///
2848    /// - `&Self` - Mutable scene tree.
2849    fn clear_dirty_paint_queue(&mut self) {
2850        let Self {
2851            dirty_paint_nodes,
2852            meta,
2853            ..
2854        } = self;
2855        for nid in dirty_paint_nodes.drain(..) {
2856            if let Some(slot_meta) = meta.get_mut(nid.as_usize()) {
2857                let next_flags: u16 = slot_meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
2858                let _: &mut NodeMeta = slot_meta.set_flags(next_flags);
2859            }
2860        }
2861    }
2862
2863    /// Marks `id` dirty with `mask` and propagates subtree dirty bits to ancestors in O(depth).
2864    ///
2865    /// # Arguments
2866    ///
2867    /// - `&Self` - Mutable scene tree.
2868    /// - `NodeId` - Mutated node handle.
2869    /// - `u16` - Dirty flag bits to set.
2870    pub fn mark_dirty(&mut self, id: NodeId, mask: u16) {
2871        let check_layout_registries: bool = (mask & DIRTY_LAYOUT) != 0;
2872        let (mut parent_opt, portal_state, scroll_state, nonzero_z_state): (
2873            Option<NodeId>,
2874            Option<bool>,
2875            Option<bool>,
2876            Option<bool>,
2877        ) = match self.get_node_mut(id) {
2878            Some(node) => {
2879                node.get_mut_dirty().insert(mask);
2880                let (portal_opt, scroll_opt, nz_z_opt): (Option<bool>, Option<bool>, Option<bool>) =
2881                    if check_layout_registries {
2882                        let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal)
2883                            || node.layout_ref().get_position() == Position::Fixed;
2884                        let is_scroll: bool = matches!(node.get_kind(), NodeKind::ScrollView)
2885                            || node.layout_ref().get_overflow() == Overflow::Scroll;
2886                        let has_nz_z: bool = node.layout_ref().get_z_index() != 0;
2887                        (Some(is_portal), Some(is_scroll), Some(has_nz_z))
2888                    } else {
2889                        (None, None, None)
2890                    };
2891                (node.parent_id(), portal_opt, scroll_opt, nz_z_opt)
2892            }
2893            None => return,
2894        };
2895        let node_idx: usize = id.as_usize();
2896        if (mask & (DIRTY_PAINT | DIRTY_FULL_DAMAGE_MASK)) != 0
2897            && let Some(epoch) = self.get_mut_paint_epochs().get_mut(node_idx)
2898        {
2899            *epoch = epoch.wrapping_add(1);
2900        }
2901        let prev_meta_flags: u16 = if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
2902            let next_dirty: u16 = meta.get_dirty() | mask;
2903            let _: &mut NodeMeta = meta.set_dirty(next_dirty);
2904            meta.get_flags()
2905        } else {
2906            0
2907        };
2908        if let Some(is_portal) = portal_state {
2909            let was_portal: bool = (prev_meta_flags & NODE_FLAG_IS_PORTAL) != 0;
2910            if is_portal != was_portal {
2911                self.sync_portal_registration(id, is_portal);
2912            }
2913        }
2914        if let Some(is_scroll) = scroll_state {
2915            let was_scroll: bool = (prev_meta_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0;
2916            if is_scroll != was_scroll {
2917                self.sync_scroll_registration(id, is_scroll);
2918            }
2919        }
2920        if let Some(has_nz_z) = nonzero_z_state
2921            && let Some(parent_id) = parent_opt
2922        {
2923            let parent_idx: usize = parent_id.as_usize();
2924            if has_nz_z {
2925                if let Some(meta) = self.get_mut_meta().get_mut(parent_idx) {
2926                    let next_flags: u16 = meta.get_flags() | NODE_FLAG_HAS_NONZERO_Z_CHILD;
2927                    let _: &mut NodeMeta = meta.set_flags(next_flags);
2928                }
2929            } else if self.has_nonzero_z_child(parent_id) {
2930                self.recompute_nonzero_z_child(parent_idx);
2931            }
2932        }
2933        if (mask & DIRTY_FULL_DAMAGE_MASK) != 0 {
2934            self.set_layout_damage_pending(true);
2935            self.set_layout_invalidations(self.get_layout_invalidations().saturating_add(1));
2936        }
2937        let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
2938        if !self.get_full_damage_pending()
2939            && (mask & visual_mask) != 0
2940            && (prev_meta_flags & NODE_FLAG_IN_DIRTY_PAINT_QUEUE) == 0
2941        {
2942            if self.get_dirty_paint_nodes().len() >= DIRTY_PAINT_FULL_THRESHOLD {
2943                self.set_full_damage_pending(true);
2944                self.set_full_damage_overflow(true);
2945                self.clear_dirty_paint_queue();
2946            } else {
2947                self.get_mut_dirty_paint_nodes().push(id);
2948                if let Some(meta) = self.get_mut_meta().get_mut(node_idx) {
2949                    let next_flags: u16 = meta.get_flags() | NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
2950                    let _: &mut NodeMeta = meta.set_flags(next_flags);
2951                }
2952            }
2953        }
2954        let mut ancestor_mask: u16 = DIRTY_NONE;
2955        if (mask & DIRTY_ANCESTOR_LAYOUT_TRIGGER) != 0 {
2956            ancestor_mask |= DIRTY_SUBTREE_LAYOUT;
2957        }
2958        if (mask & DIRTY_ANCESTOR_PAINT_TRIGGER) != 0 {
2959            ancestor_mask |= DIRTY_SUBTREE_PAINT;
2960        }
2961        if (mask & DIRTY_ANCESTOR_COMPOSITE_TRIGGER) != 0 {
2962            ancestor_mask |= DIRTY_SUBTREE_COMPOSITE;
2963        }
2964        if ancestor_mask != DIRTY_NONE {
2965            let root_has_mask: bool = {
2966                let root_id: NodeId = self.get_root();
2967                self.get_node(root_id)
2968                    .map(|root_node: &SceneNode| {
2969                        (root_node.get_dirty().get_bits() & ancestor_mask) == ancestor_mask
2970                    })
2971                    .unwrap_or(true)
2972            };
2973            let can_early_break: bool = root_has_mask && !self.get_has_stale_hidden_dirty();
2974            while let Some(ancestor_id) = parent_opt {
2975                let ancestor_idx: usize = ancestor_id.as_usize();
2976                if let Some(ancestor) = self.get_node_mut(ancestor_id) {
2977                    let already: bool =
2978                        (ancestor.get_dirty().get_bits() & ancestor_mask) == ancestor_mask;
2979                    ancestor.get_mut_dirty().insert(ancestor_mask);
2980                    parent_opt = ancestor.parent_id();
2981                    if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
2982                        let next_dirty: u16 = meta.get_dirty() | ancestor_mask;
2983                        let _: &mut NodeMeta = meta.set_dirty(next_dirty);
2984                    }
2985                    if already && can_early_break {
2986                        break;
2987                    }
2988                } else {
2989                    break;
2990                }
2991            }
2992        }
2993        let next_rev: u64 = self.get_revision().wrapping_add(1);
2994        self.set_revision(next_rev);
2995        notify_frame_needed();
2996    }
2997
2998    /// Returns `true` when `id` and every ancestor up to the root are alive, attached, non-`Display::None`, and visibly opaque.
2999    ///
3000    /// # Arguments
3001    ///
3002    /// - `&Self` - Scene tree reference.
3003    /// - `NodeId` - Target node handle.
3004    ///
3005    /// # Returns
3006    ///
3007    /// - `bool` - Whether the node is visibly rendered in the scene.
3008    #[must_use]
3009    pub fn is_node_visible(&self, id: NodeId) -> bool {
3010        let root: NodeId = self.get_root();
3011        let mut cursor: Option<NodeId> = Some(id);
3012        while let Some(cur) = cursor {
3013            let Some(node) = self.get_node(cur) else {
3014                return false;
3015            };
3016            let style: &Style = node.style_ref();
3017            if style.get_layout().get_display() == Display::None
3018                || style.get_paint().get_opacity() <= 0.001
3019            {
3020                return false;
3021            }
3022            if cur == root {
3023                return true;
3024            }
3025            cursor = node.parent_id();
3026        }
3027        false
3028    }
3029
3030    /// Collects the tight physical damage region from dirty paint/scroll nodes in O(dirty) and clears paint dirty flags.
3031    ///
3032    /// # Arguments
3033    ///
3034    /// - `&Self` - Mutable scene tree.
3035    /// - `f32` - Active display scale factor.
3036    ///
3037    /// # Returns
3038    ///
3039    /// - `DamageRegion` - Minimal damaged region, full damage on structural/layout change, or clean when idle.
3040    pub fn collect_paint_damage(&mut self, scale: f32) -> DamageRegion {
3041        let (damage, _): (DamageRegion, bool) = self.collect_surgical_paint_damage(scale, false);
3042        damage
3043    }
3044
3045    /// Collects tight physical paint/scroll/removed-node damage while optionally deferring layout bounds diffing to `LayoutEngine`.
3046    ///
3047    /// # Arguments
3048    ///
3049    /// - `&Self` - Mutable scene tree.
3050    /// - `f32` - Active display scale factor.
3051    /// - `bool` - When `true`, allows surgical pre/post-layout damage diffing instead of promoting all layout mutations to full redraw.
3052    ///
3053    /// # Returns
3054    ///
3055    /// - `(DamageRegion, bool)` - Collected damage region and whether a layout pass is still pending.
3056    pub(crate) fn collect_surgical_paint_damage(
3057        &mut self,
3058        scale: f32,
3059        allow_partial_layout: bool,
3060    ) -> (DamageRegion, bool) {
3061        let clear_mask: u16 = DIRTY_PAINT_CLEAR_MASK;
3062        let layout_pending: bool = self.get_layout_damage_pending();
3063        let no_paint_nodes: bool = self.get_dirty_paint_nodes().is_empty();
3064        let no_extra: bool = self.get_extra_logical_damage().is_empty();
3065        if !self.get_full_damage_pending() && !layout_pending && no_paint_nodes && no_extra {
3066            self.set_created_since_damage(0);
3067            self.set_last_collect_composite_only(false);
3068            return (DamageRegion::default(), false);
3069        }
3070        let mut full: bool =
3071            self.get_full_damage_pending() || (!allow_partial_layout && layout_pending);
3072        let mut saw_paint_or_layout: bool = layout_pending;
3073        let mut saw_composite_or_scroll: bool = false;
3074        let mut region: DamageRegion = DamageRegion::default();
3075        if !full {
3076            let extra_len: usize = self.get_extra_logical_damage().len();
3077            for i in 0..extra_len {
3078                let logical_rect: Rect = self.get_extra_logical_damage()[i];
3079                if logical_rect.get_width() > 0.0 && logical_rect.get_height() > 0.0 {
3080                    region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
3081                }
3082            }
3083            let dirty_len: usize = self.get_dirty_paint_nodes().len();
3084            let visual_mask: u16 = DIRTY_PAINT + DIRTY_SCROLL + DIRTY_COMPOSITE;
3085            for i in 0..dirty_len {
3086                let nid: NodeId = self.get_dirty_paint_nodes()[i];
3087                let Some(node) = self.get_node(nid) else {
3088                    continue;
3089                };
3090                let bits: u16 = node.get_dirty().get_bits();
3091                let has_layout_bits: bool = (bits & DIRTY_LAYOUT_PASS_MASK) != 0;
3092                if (bits & (DIRTY_PAINT | DIRTY_LAYOUT_PASS_MASK)) != 0 {
3093                    saw_paint_or_layout = true;
3094                }
3095                if (bits & (DIRTY_COMPOSITE | DIRTY_SCROLL)) != 0 {
3096                    saw_composite_or_scroll = true;
3097                }
3098                if !allow_partial_layout && (bits & DIRTY_FULL_DAMAGE_MASK) != 0 {
3099                    full = true;
3100                    break;
3101                }
3102                if (bits & DIRTY_SCROLL) != 0 && has_layout_bits {
3103                    full = true;
3104                    break;
3105                }
3106                if (bits & visual_mask) == 0 {
3107                    continue;
3108                }
3109                let raw_bounds: Rect = node.get_layout_box().get_bounds();
3110                if raw_bounds.get_width() > 0.0 && raw_bounds.get_height() > 0.0 {
3111                    match self.node_conservative_logical_rect(nid) {
3112                        Some(logical_rect) => {
3113                            region.add_rect(Self::scale_logical_to_phys_rect(logical_rect, scale));
3114                        }
3115                        None => {
3116                            full = true;
3117                            break;
3118                        }
3119                    }
3120                } else if (bits & (DIRTY_PAINT | DIRTY_COMPOSITE)) != 0
3121                    && !has_layout_bits
3122                    && node.style_ref().layout_ref().get_display() != Display::None
3123                {
3124                    full = true;
3125                    break;
3126                }
3127            }
3128        }
3129        self.set_last_collect_composite_only(
3130            !full && !layout_pending && !saw_paint_or_layout && saw_composite_or_scroll,
3131        );
3132        self.set_layout_damage_pending(false);
3133        self.set_created_since_damage(0);
3134        self.get_mut_extra_logical_damage().clear();
3135        if !full {
3136            let dirty_len: usize = self.get_dirty_paint_nodes().len();
3137            let ancestor_clear: u16 = DIRTY_SUBTREE_PAINT | DIRTY_SUBTREE_COMPOSITE;
3138            for i in 0..dirty_len {
3139                let nid: NodeId = self.get_dirty_paint_nodes()[i];
3140                let mut parent_opt: Option<NodeId> = match self.get_node_mut(nid) {
3141                    Some(node) => {
3142                        node.get_mut_dirty().remove(clear_mask);
3143                        node.parent_id()
3144                    }
3145                    None => None,
3146                };
3147                if let Some(meta) = self.get_mut_meta().get_mut(nid.get_index() as usize) {
3148                    let next_dirty: u16 = meta.get_dirty() & !clear_mask;
3149                    let next_flags: u16 = meta.get_flags() & !NODE_FLAG_IN_DIRTY_PAINT_QUEUE;
3150                    let _: &mut NodeMeta = meta.set_dirty(next_dirty).set_flags(next_flags);
3151                }
3152                while let Some(ancestor_id) = parent_opt {
3153                    let ancestor_idx: usize = ancestor_id.get_index() as usize;
3154                    if let Some(ancestor) = self.get_node_mut(ancestor_id) {
3155                        if (ancestor.get_dirty().get_bits() & ancestor_clear) == 0 {
3156                            break;
3157                        }
3158                        ancestor.get_mut_dirty().remove(ancestor_clear);
3159                        parent_opt = ancestor.parent_id();
3160                    } else {
3161                        break;
3162                    }
3163                    if let Some(meta) = self.get_mut_meta().get_mut(ancestor_idx) {
3164                        let next_dirty: u16 = meta.get_dirty() & !ancestor_clear;
3165                        let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3166                    }
3167                }
3168            }
3169            self.get_mut_dirty_paint_nodes().clear();
3170            return (region, layout_pending);
3171        }
3172        self.set_full_damage_pending(false);
3173        self.clear_dirty_paint_queue();
3174        let node_count: usize = self.get_nodes().len();
3175        for idx in 0..node_count {
3176            let should_clear: bool = {
3177                let node: &SceneNode = &self.get_nodes()[idx];
3178                node.get_alive() && (node.get_dirty().get_bits() & clear_mask) != 0
3179            };
3180            if should_clear {
3181                self.get_mut_nodes()[idx].get_mut_dirty().remove(clear_mask);
3182                if let Some(meta) = self.get_mut_meta().get_mut(idx) {
3183                    let next_dirty: u16 = meta.get_dirty() & !clear_mask;
3184                    let _: &mut NodeMeta = meta.set_dirty(next_dirty);
3185                }
3186            }
3187        }
3188        (DamageRegion::full(), layout_pending)
3189    }
3190
3191    /// Consumes and returns whether the most recent dirty-paint accumulation overflowed `DIRTY_PAINT_FULL_THRESHOLD`.
3192    ///
3193    /// # Arguments
3194    ///
3195    /// - `&Self` - Mutable scene tree.
3196    ///
3197    /// # Returns
3198    ///
3199    /// - `bool` - `true` if dirty paint nodes overflowed into full damage.
3200    pub(crate) fn take_full_damage_overflow(&mut self) -> bool {
3201        let was_overflow: bool = self.get_full_damage_overflow();
3202        self.set_full_damage_overflow(false);
3203        was_overflow
3204    }
3205
3206    /// Recursively detaches and recycles `id`, returning all owned `Scope`s and `Lifecycle` observers for borrow-safe finalization.
3207    ///
3208    /// # Arguments
3209    ///
3210    /// - `&Self` - Mutable scene tree.
3211    /// - `NodeId` - Subtree root handle to dispose.
3212    ///
3213    /// # Returns
3214    ///
3215    /// - `DisposedSubtreePayload` - Collected scopes and lifecycle observers to finalize outside any borrow.
3216    pub fn dispose_subtree_collect(&mut self, id: NodeId) -> DisposedSubtreePayload {
3217        if id == self.get_root() || self.get_node(id).is_none() {
3218            return (Vec::new(), Vec::new());
3219        }
3220        self.record_subtree_logical_damage(id);
3221        self.cancel_subtree_transitions(id);
3222        let root_parent: u32 = self.get_topology()[id.as_usize()].get_parent();
3223        if root_parent != NODE_INDEX_NONE {
3224            self.unlink_child_at(root_parent as usize, id.as_usize());
3225        }
3226        let mut stack: Vec<NodeId> = vec![id];
3227        let mut scopes: Vec<Scope> = Vec::new();
3228        let mut observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
3229        while let Some(current) = stack.pop() {
3230            let cur_idx: usize = current.as_usize();
3231            let mut next_child: u32 = self.get_topology()[cur_idx].get_first_child();
3232            let mut removed_lifecycles: usize = 0;
3233            let (was_alive, prev_flags): (bool, u16) = match self.get_node_mut(current) {
3234                Some(node) => {
3235                    node.set_alive(false);
3236                    node.set_kind(NodeKind::View);
3237                    if node.has_extras() {
3238                        if let Some(scope) = node.owned_scope() {
3239                            scopes.push(scope);
3240                        }
3241                        let drained: Vec<Rc<dyn Lifecycle>> = node.take_lifecycles();
3242                        removed_lifecycles = drained.len();
3243                        for hook in drained.into_iter() {
3244                            observers.push((current, hook));
3245                        }
3246                        node.clear_extras();
3247                    }
3248                    node.set_parent(None);
3249                    let next_gen: u32 = node.get_generation().wrapping_add(1).max(1);
3250                    node.set_generation(next_gen);
3251                    (true, self.get_meta()[cur_idx].get_flags())
3252                }
3253                None => (false, 0),
3254            };
3255            if !was_alive {
3256                continue;
3257            }
3258            while next_child != NODE_INDEX_NONE {
3259                let ci: usize = next_child as usize;
3260                let sibling: u32 = self.get_topology()[ci].get_next_sibling();
3261                let child_gen: u32 = self.get_meta()[ci].get_generation();
3262                stack.push(NodeId::new(next_child, child_gen));
3263                next_child = sibling;
3264            }
3265            let next_gen: u32 = self.get_nodes()[cur_idx].get_generation();
3266            self.get_mut_meta()[cur_idx] = NodeMeta::new(next_gen, 0, DIRTY_NONE);
3267            self.get_mut_topology()[cur_idx] = NodeTopology::default();
3268            let prev_effect_id: u32 = self.get_compact_paints()[cur_idx].get_effect_id();
3269            if prev_effect_id != EFFECT_ID_NONE {
3270                self.get_mut_effect_table().remove(prev_effect_id);
3271                let _: &mut CompactPaintStyle =
3272                    self.get_mut_compact_paints()[cur_idx].set_effect_id(EFFECT_ID_NONE);
3273            }
3274            let next_live: usize = self.get_live_count().saturating_sub(1);
3275            self.set_live_count(next_live);
3276            if removed_lifecycles > 0 {
3277                let next_lc: usize = self
3278                    .get_live_lifecycle_count()
3279                    .saturating_sub(removed_lifecycles);
3280                self.set_live_lifecycle_count(next_lc);
3281            }
3282            if (prev_flags & NODE_FLAG_IS_PORTAL) != 0 && !self.portal_nodes().is_empty() {
3283                self.sync_portal_registration(current, false);
3284            }
3285            if (prev_flags & NODE_FLAG_IS_SCROLL_CONTAINER) != 0 && !self.scroll_nodes().is_empty()
3286            {
3287                self.sync_scroll_registration(current, false);
3288            }
3289            if !self.get_backdrop_blur_nodes().is_empty() {
3290                self.get_mut_backdrop_blur_nodes()
3291                    .retain(|entry: &(NodeId, f32)| entry.0 != current);
3292            }
3293            if self.get_focus().focused_node() == Some(current) {
3294                self.get_mut_focus().set_focused(None);
3295            }
3296            if self.get_focus().hovered_node() == Some(current) {
3297                self.get_mut_focus().set_hovered(None);
3298            }
3299            if self.get_focus().pressed_node() == Some(current) {
3300                self.get_mut_focus().set_pressed(None);
3301            }
3302            let sel_hits_current: bool =
3303                self.text_selection().is_some_and(|sel: SelectionState| {
3304                    sel.get_anchor_node() == current || sel.get_focus_node() == current
3305                }) || self
3306                    .text_selection_spans_ref()
3307                    .iter()
3308                    .any(|&(nid, _, _): &(NodeId, usize, usize)| nid == current);
3309            if sel_hits_current {
3310                self.set_text_selection(None);
3311            }
3312            self.get_mut_free_list().push(current.get_index());
3313        }
3314        (scopes, observers)
3315    }
3316
3317    /// Recursively removes and disposes `id`, recycling all arena slots, running lifecycle hooks, and disposing scopes.
3318    ///
3319    /// # Arguments
3320    ///
3321    /// - `&Self` - Mutable scene tree.
3322    /// - `NodeId` - Subtree root handle to dispose.
3323    pub fn dispose_subtree(&mut self, id: NodeId) {
3324        let (scopes, observers): DisposedSubtreePayload = self.dispose_subtree_collect(id);
3325        finalize_disposed_subtree(scopes, observers);
3326    }
3327
3328    /// Updates keyboard focus to `target`, emitting `Blur` and `Focus` events.
3329    ///
3330    /// # Arguments
3331    ///
3332    /// - `&Self` - Mutable scene tree.
3333    /// - `Option<NodeId>` - Newly focused node, or `None` to clear focus.
3334    ///
3335    /// # Returns
3336    ///
3337    /// - `Vec<(UiEventHandler, UiEvent)>` - Callbacks to invoke outside the tree borrow.
3338    pub fn update_focus(&mut self, target: Option<NodeId>) -> Vec<(UiEventHandler, UiEvent)> {
3339        let prev: Option<NodeId> = self.get_focus().focused_node();
3340        if prev == target {
3341            return Vec::new();
3342        }
3343        let mut callbacks: Vec<(UiEventHandler, UiEvent)> = Vec::new();
3344        if let Some(old_id) = prev {
3345            if let Some(old_node) = self.get_node_mut(old_id) {
3346                old_node.get_mut_interaction().set_focused(false);
3347                if let Some(handler) = old_node.get_handlers().handler_for(&UiEventKind::Blur) {
3348                    callbacks.push((handler, UiEvent::new(old_id, UiEventKind::Blur)));
3349                }
3350            }
3351            self.mark_dirty(old_id, DIRTY_PAINT);
3352        }
3353        self.get_mut_focus().set_focused(target);
3354        if let Some(new_id) = target {
3355            if let Some(new_node) = self.get_node_mut(new_id) {
3356                new_node.get_mut_interaction().set_focused(true);
3357                if let Some(handler) = new_node.get_handlers().handler_for(&UiEventKind::Focus) {
3358                    callbacks.push((handler, UiEvent::new(new_id, UiEventKind::Focus)));
3359                }
3360            }
3361            self.mark_dirty(new_id, DIRTY_PAINT);
3362        }
3363        callbacks
3364    }
3365
3366    /// Resolves the effective `TextSelectMode` for `id`, inheriting from ancestors until an explicit mode is encountered (`TextSelectMode::None` by default).
3367    ///
3368    /// # Arguments
3369    ///
3370    /// - `&Self` - Scene tree reference.
3371    /// - `NodeId` - Target scene node handle.
3372    ///
3373    /// # Returns
3374    ///
3375    /// - `TextSelectMode` - Effective text selection and copy mode for `id`.
3376    #[must_use]
3377    pub fn effective_text_select_mode(&self, id: NodeId) -> TextSelectMode {
3378        let mut cursor: Option<NodeId> = Some(id);
3379        while let Some(cur) = cursor {
3380            let Some(node) = self.get_node(cur) else {
3381                return TextSelectMode::None;
3382            };
3383            if let Some(mode) = node.style_ref().text_ref().text_select_mode() {
3384                return mode;
3385            }
3386            cursor = node.parent_id();
3387        }
3388        TextSelectMode::None
3389    }
3390
3391    /// Resolves whether `id` allows interactive text selection (`effective_text_select_mode(id) != TextSelectMode::None`).
3392    ///
3393    /// # Arguments
3394    ///
3395    /// - `&Self` - Scene tree reference.
3396    /// - `NodeId` - Target scene node handle.
3397    ///
3398    /// # Returns
3399    ///
3400    /// - `bool` - `true` when `id` resolves to `TextSelectMode::SelectAndCopy` or `TextSelectMode::All`.
3401    #[must_use]
3402    pub fn is_node_selectable(&self, id: NodeId) -> bool {
3403        self.effective_text_select_mode(id) != TextSelectMode::None
3404    }
3405
3406    /// Walks ancestors from `id` to locate the outermost contiguous container sharing its non-`None` `TextSelectMode` without crossing a `Portal`.
3407    ///
3408    /// # Arguments
3409    ///
3410    /// - `&Self` - Scene tree reference.
3411    /// - `NodeId` - Starting node handle.
3412    ///
3413    /// # Returns
3414    ///
3415    /// - `Option<(NodeId, TextSelectMode)>` - Scope container root and active non-`None` mode.
3416    #[must_use]
3417    pub(crate) fn selectable_scope_root(&self, id: NodeId) -> Option<(NodeId, TextSelectMode)> {
3418        let target_mode: TextSelectMode = self.effective_text_select_mode(id);
3419        if target_mode == TextSelectMode::None {
3420            return None;
3421        }
3422        let mut scope: NodeId = id;
3423        loop {
3424            let cur_node: &SceneNode = self.get_node(scope)?;
3425            if matches!(cur_node.get_kind(), NodeKind::Portal) {
3426                break;
3427            }
3428            let Some(parent_id) = cur_node.parent_id() else {
3429                break;
3430            };
3431            if self.effective_text_select_mode(parent_id) != target_mode {
3432                break;
3433            }
3434            scope = parent_id;
3435        }
3436        Some((scope, target_mode))
3437    }
3438
3439    /// Collects all visible live selectable `NodeKind::Text` nodes in reading (DFS pre-order) order inside `id`'s selectable scope, skipping any opt-out (`TextSelectMode::None`) or differently configured descendants.
3440    ///
3441    /// # Arguments
3442    ///
3443    /// - `&Self` - Scene tree reference.
3444    /// - `NodeId` - Anchor or hit node inside a selectable container.
3445    ///
3446    /// # Returns
3447    ///
3448    /// - `Vec<NodeId>` - Ordered selectable text node handles within the same scope.
3449    #[must_use]
3450    pub(crate) fn selectable_scope_text_nodes(&self, id: NodeId) -> Vec<NodeId> {
3451        let Some((scope_root, target_mode)) = self.selectable_scope_root(id) else {
3452            return Vec::new();
3453        };
3454        let mut out: Vec<NodeId> = Vec::new();
3455        let mut stack: Vec<NodeId> = vec![scope_root];
3456        while let Some(cid) = stack.pop() {
3457            let Some(node) = self.get_node(cid) else {
3458                continue;
3459            };
3460            if !node.get_alive() || node.style_ref().get_layout().get_display() == Display::None {
3461                continue;
3462            }
3463            if cid != scope_root {
3464                if matches!(node.get_kind(), NodeKind::Portal) {
3465                    continue;
3466                }
3467                if node
3468                    .style_ref()
3469                    .text_ref()
3470                    .text_select_mode()
3471                    .is_some_and(|m: TextSelectMode| m != target_mode)
3472                {
3473                    continue;
3474                }
3475            }
3476            if matches!(node.get_kind(), NodeKind::Text(_)) {
3477                out.push(cid);
3478            } else {
3479                let start_len: usize = stack.len();
3480                stack.extend(self.children_iter(cid));
3481                stack[start_len..].reverse();
3482            }
3483        }
3484        out
3485    }
3486
3487    /// Computes the logical screen-space text content rectangle for a `NodeKind::Text` node.
3488    ///
3489    /// # Arguments
3490    ///
3491    /// - `&Self` - Scene tree reference.
3492    /// - `NodeId` - Target text node handle.
3493    ///
3494    /// # Returns
3495    ///
3496    /// - `Option<Rect>` - Logical screen-space content bounding rectangle.
3497    #[must_use]
3498    pub(crate) fn text_node_screen_content_rect(&self, node_id: NodeId) -> Option<Rect> {
3499        let node: &SceneNode = self.get_node(node_id)?;
3500        let lbox: LayoutBox = node.get_layout_box();
3501        let outer: Rect = lbox.get_bounds();
3502        let content_rect: Rect = lbox.get_content_bounds();
3503        let screen_outer: Rect = self.node_screen_bounds(node_id).unwrap_or(outer);
3504        Some(Rect::new(
3505            screen_outer.get_x() + (content_rect.get_x() - outer.get_x()),
3506            screen_outer.get_y() + (content_rect.get_y() - outer.get_y()),
3507            content_rect.get_width(),
3508            content_rect.get_height(),
3509        ))
3510    }
3511
3512    /// Returns `true` when `cur_id` sits on a distinct visual line/row from `prev_id`.
3513    ///
3514    /// # Arguments
3515    ///
3516    /// - `&Self` - Scene tree reference.
3517    /// - `NodeId` - Previous text node handle.
3518    /// - `NodeId` - Next text node handle.
3519    ///
3520    /// # Returns
3521    ///
3522    /// - `bool` - `true` when a newline separator belongs between `prev_id` and `cur_id`.
3523    #[must_use]
3524    fn is_new_visual_row(&self, prev_id: NodeId, cur_id: NodeId) -> bool {
3525        let prev_rect: Option<Rect> = self.text_node_screen_content_rect(prev_id);
3526        let cur_rect: Option<Rect> = self.text_node_screen_content_rect(cur_id);
3527        if let (Some(pr), Some(cr)) = (prev_rect, cur_rect)
3528            && pr.get_height() > 0.0
3529            && cr.get_height() > 0.0
3530        {
3531            let prev_cy: f32 = pr.get_y() + pr.get_height() * 0.5;
3532            let cur_cy: f32 = cr.get_y() + cr.get_height() * 0.5;
3533            let threshold: f32 = (pr.get_height().min(cr.get_height()) * 0.5).max(4.0);
3534            return (cur_cy - prev_cy).abs() > threshold;
3535        }
3536        let prev_parent: Option<NodeId> = self.get_node(prev_id).and_then(SceneNode::parent_id);
3537        let cur_parent: Option<NodeId> = self.get_node(cur_id).and_then(SceneNode::parent_id);
3538        if let (Some(pp), Some(cp)) = (prev_parent, cur_parent)
3539            && pp == cp
3540            && let Some(pnode) = self.get_node(pp)
3541            && pnode.style_ref().get_layout().get_flex_direction() == FlexDirection::Row
3542        {
3543            return false;
3544        }
3545        true
3546    }
3547
3548    /// Resolves the ordered per-node `(node_id, start_char, end_char)` spans covered by `selection`.
3549    ///
3550    /// # Arguments
3551    ///
3552    /// - `&Self` - Scene tree reference.
3553    /// - `SelectionState` - Active selection endpoints.
3554    ///
3555    /// # Returns
3556    ///
3557    /// - `Vec<(NodeId, usize, usize)>` - Ordered per-node character spans.
3558    #[must_use]
3559    fn resolve_selection_spans(&self, selection: SelectionState) -> Vec<(NodeId, usize, usize)> {
3560        if selection.is_empty() {
3561            return Vec::new();
3562        }
3563        if selection.is_single_node() {
3564            let nid: NodeId = selection.get_anchor_node();
3565            let Some(node) = self.get_node(nid) else {
3566                return Vec::new();
3567            };
3568            let NodeKind::Text(content) = node.get_kind() else {
3569                return Vec::new();
3570            };
3571            let len: usize = content.chars().count();
3572            let (raw_s, raw_e): (usize, usize) = selection.ordered_range();
3573            let start_c: usize = raw_s.min(len);
3574            let end_c: usize = raw_e.min(len);
3575            return if start_c < end_c {
3576                vec![(nid, start_c, end_c)]
3577            } else {
3578                Vec::new()
3579            };
3580        }
3581        let anchor_id: NodeId = selection.get_anchor_node();
3582        let focus_id: NodeId = selection.get_focus_node();
3583        let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_id);
3584        let anchor_pos: Option<usize> = nodes.iter().position(|n: &NodeId| *n == anchor_id);
3585        let focus_pos: Option<usize> = nodes.iter().position(|n: &NodeId| *n == focus_id);
3586        let (Some(a_pos), Some(f_pos)) = (anchor_pos, focus_pos) else {
3587            return Vec::new();
3588        };
3589        let (start_pos, start_ch, end_pos, end_ch): (usize, usize, usize, usize) = if a_pos <= f_pos
3590        {
3591            (
3592                a_pos,
3593                selection.get_anchor_char(),
3594                f_pos,
3595                selection.get_focus_char(),
3596            )
3597        } else {
3598            (
3599                f_pos,
3600                selection.get_focus_char(),
3601                a_pos,
3602                selection.get_anchor_char(),
3603            )
3604        };
3605        let mut spans: Vec<(NodeId, usize, usize)> =
3606            Vec::with_capacity(end_pos.saturating_sub(start_pos) + 1);
3607        for (idx, &nid) in nodes.iter().enumerate().take(end_pos + 1).skip(start_pos) {
3608            let Some(node) = self.get_node(nid) else {
3609                continue;
3610            };
3611            let NodeKind::Text(content) = node.get_kind() else {
3612                continue;
3613            };
3614            let len: usize = content.chars().count();
3615            let s: usize = if idx == start_pos {
3616                start_ch.min(len)
3617            } else {
3618                0
3619            };
3620            let e: usize = if idx == end_pos { end_ch.min(len) } else { len };
3621            if s < e || (idx > start_pos && idx < end_pos) {
3622                spans.push((nid, s, e));
3623            }
3624        }
3625        spans
3626    }
3627
3628    /// Returns the precomputed per-node selection spans slice for fast render-time highlight queries.
3629    ///
3630    /// # Arguments
3631    ///
3632    /// - `&Self` - Scene tree reference.
3633    ///
3634    /// # Returns
3635    ///
3636    /// - `&[(NodeId, usize, usize)]` - Precomputed selected node character ranges.
3637    #[must_use]
3638    pub(crate) fn text_selection_spans_ref(&self) -> &[(NodeId, usize, usize)] {
3639        let Self {
3640            text_selection_spans,
3641            ..
3642        } = self;
3643        text_selection_spans.as_slice()
3644    }
3645
3646    /// Returns the highlighted `(start_char, end_char)` character range for `id` if it participates in the active selection.
3647    ///
3648    /// # Arguments
3649    ///
3650    /// - `&Self` - Scene tree reference.
3651    /// - `NodeId` - Target text node handle.
3652    ///
3653    /// # Returns
3654    ///
3655    /// - `Option<(usize, usize)>` - Non-empty ordered character range for `id`, or `None`.
3656    #[must_use]
3657    pub(crate) fn text_selection_range_for(&self, id: NodeId) -> Option<(usize, usize)> {
3658        let spans: &[(NodeId, usize, usize)] = self.text_selection_spans_ref();
3659        if spans.is_empty() {
3660            return None;
3661        }
3662        for &(nid, s, e) in spans.iter() {
3663            if nid == id {
3664                return if s < e { Some((s, e)) } else { None };
3665            }
3666        }
3667        None
3668    }
3669
3670    /// Returns `true` when `id` equals `ancestor` or has `ancestor` in its parent chain.
3671    ///
3672    /// # Arguments
3673    ///
3674    /// - `&Self` - Scene tree reference.
3675    /// - `NodeId` - Candidate descendant handle.
3676    /// - `NodeId` - Candidate ancestor handle.
3677    ///
3678    /// # Returns
3679    ///
3680    /// - `bool` - Whether `id` lies within `ancestor`'s subtree.
3681    #[must_use]
3682    pub(crate) fn is_descendant_of(&self, id: NodeId, ancestor: NodeId) -> bool {
3683        let mut cursor: Option<NodeId> = Some(id);
3684        while let Some(cur) = cursor {
3685            if cur == ancestor {
3686                return true;
3687            }
3688            cursor = self.get_node(cur).and_then(SceneNode::parent_id);
3689        }
3690        false
3691    }
3692
3693    /// Resolves the effective text selection highlight color for `id`, inheriting from ancestors or falling back to default tint.
3694    ///
3695    /// # Arguments
3696    ///
3697    /// - `&Self` - Scene tree reference.
3698    /// - `NodeId` - Target text node handle.
3699    ///
3700    /// # Returns
3701    ///
3702    /// - `Color` - Selection highlight fill color.
3703    #[must_use]
3704    pub fn effective_selection_color(&self, id: NodeId) -> Color {
3705        let mut cursor: Option<NodeId> = Some(id);
3706        while let Some(cur) = cursor {
3707            let Some(node) = self.get_node(cur) else {
3708                break;
3709            };
3710            if let Some(color) = node.style_ref().text_ref().selection_color() {
3711                return color;
3712            }
3713            cursor = node.parent_id();
3714        }
3715        DEFAULT_TEXT_SELECTION_COLOR
3716    }
3717
3718    /// Returns the active text selection state, if any.
3719    ///
3720    /// # Arguments
3721    ///
3722    /// - `&Self` - Scene tree reference.
3723    ///
3724    /// # Returns
3725    ///
3726    /// - `Option<SelectionState>` - Current selection state.
3727    #[must_use]
3728    pub fn text_selection(&self) -> Option<SelectionState> {
3729        let Self { text_selection, .. } = self;
3730        *text_selection
3731    }
3732
3733    /// Updates the active text selection state, recomputes all spanned text node ranges, and marks every previously and newly selected node dirty for repaint.
3734    ///
3735    /// # Arguments
3736    ///
3737    /// - `&Self` - Mutable scene tree.
3738    /// - `Option<SelectionState>` - Replacement selection state (`None` clears selection).
3739    pub fn set_text_selection(&mut self, selection: Option<SelectionState>) {
3740        let prev: Option<SelectionState> = self.text_selection();
3741        if prev == selection {
3742            return;
3743        }
3744        let mut dirty_ids: Vec<NodeId> =
3745            Vec::with_capacity(self.text_selection_spans_ref().len() + 4);
3746        for &(nid, _, _) in self.text_selection_spans_ref().iter() {
3747            dirty_ids.push(nid);
3748        }
3749        if let Some(old_sel) = prev {
3750            dirty_ids.push(old_sel.get_anchor_node());
3751            if !old_sel.is_single_node() {
3752                dirty_ids.push(old_sel.get_focus_node());
3753            }
3754        }
3755        let next_spans: Vec<(NodeId, usize, usize)> = selection
3756            .map(|sel: SelectionState| self.resolve_selection_spans(sel))
3757            .unwrap_or_default();
3758        for &(nid, _, _) in next_spans.iter() {
3759            dirty_ids.push(nid);
3760        }
3761        if let Some(new_sel) = selection {
3762            dirty_ids.push(new_sel.get_anchor_node());
3763            if !new_sel.is_single_node() {
3764                dirty_ids.push(new_sel.get_focus_node());
3765            }
3766        }
3767        let Self {
3768            text_selection,
3769            text_selection_spans,
3770            ..
3771        } = self;
3772        *text_selection = selection;
3773        *text_selection_spans = next_spans;
3774        for nid in dirty_ids.into_iter() {
3775            self.mark_dirty(nid, DIRTY_PAINT);
3776        }
3777    }
3778
3779    /// Clears any active text selection and repaints all previously selected nodes.
3780    ///
3781    /// # Arguments
3782    ///
3783    /// - `&Self` - Mutable scene tree.
3784    pub fn clear_text_selection(&mut self) {
3785        self.set_text_selection(None);
3786    }
3787
3788    /// Extracts the active selected UTF-8 text, optionally requiring the selection to reside inside `container`.
3789    ///
3790    /// # Arguments
3791    ///
3792    /// - `&Self` - Scene tree reference.
3793    /// - `Option<NodeId>` - Optional ancestor container constraint.
3794    ///
3795    /// # Returns
3796    ///
3797    /// - `Option<String>` - Extracted selected text with `\n` inserted between distinct visual rows.
3798    #[must_use]
3799    fn extract_selected_text_filtered(&self, container: Option<NodeId>) -> Option<String> {
3800        let sel: SelectionState = self.text_selection()?;
3801        if sel.is_empty() {
3802            return None;
3803        }
3804        if let Some(root) = container
3805            && !self.is_descendant_of(sel.get_anchor_node(), root)
3806        {
3807            return None;
3808        }
3809        let spans: &[(NodeId, usize, usize)] = self.text_selection_spans_ref();
3810        if spans.is_empty() {
3811            return None;
3812        }
3813        if spans.len() == 1 {
3814            let (nid, s, e): (NodeId, usize, usize) = spans[0];
3815            if let Some(root) = container
3816                && !self.is_descendant_of(nid, root)
3817            {
3818                return None;
3819            }
3820            let node: &SceneNode = self.get_node(nid)?;
3821            let NodeKind::Text(content) = node.get_kind() else {
3822                return None;
3823            };
3824            let extracted: &str = extract_char_range(content.as_str(), s, e);
3825            return if extracted.is_empty() {
3826                None
3827            } else {
3828                Some(extracted.to_string())
3829            };
3830        }
3831        let mut out: String = String::new();
3832        let mut prev_emitted_node: Option<NodeId> = None;
3833        let last_span_idx: usize = spans.len().saturating_sub(1);
3834        for (idx, &(nid, s, e)) in spans.iter().enumerate() {
3835            if let Some(root) = container
3836                && !self.is_descendant_of(nid, root)
3837            {
3838                continue;
3839            }
3840            let Some(node) = self.get_node(nid) else {
3841                continue;
3842            };
3843            let NodeKind::Text(content) = node.get_kind() else {
3844                continue;
3845            };
3846            let part: &str = extract_char_range(content.as_str(), s, e);
3847            let is_middle_empty: bool = part.is_empty() && idx > 0 && idx < last_span_idx;
3848            if part.is_empty() && !is_middle_empty {
3849                continue;
3850            }
3851            if let Some(prev_id) = prev_emitted_node
3852                && self.is_new_visual_row(prev_id, nid)
3853            {
3854                out.push('\n');
3855            }
3856            out.push_str(part);
3857            prev_emitted_node = Some(nid);
3858        }
3859        if out.is_empty() { None } else { Some(out) }
3860    }
3861
3862    /// Returns the currently selected UTF-8 substring across one or more live text nodes.
3863    ///
3864    /// # Arguments
3865    ///
3866    /// - `&Self` - Scene tree reference.
3867    ///
3868    /// # Returns
3869    ///
3870    /// - `Option<String>` - Selected text string, or `None` when no text is selected.
3871    #[must_use]
3872    pub fn get_selected_text(&self) -> Option<String> {
3873        self.extract_selected_text_filtered(None)
3874    }
3875
3876    /// Returns the currently selected UTF-8 substring only when the active selection lies inside `container`'s subtree.
3877    ///
3878    /// # Arguments
3879    ///
3880    /// - `&Self` - Scene tree reference.
3881    /// - `NodeId` - Container root node handle.
3882    ///
3883    /// # Returns
3884    ///
3885    /// - `Option<String>` - Selected text within `container`, or `None`.
3886    #[must_use]
3887    pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
3888        self.extract_selected_text_filtered(Some(container))
3889    }
3890
3891    /// Selects all selectable text across `id`'s active selectable container scope (excluding `TextSelectMode::None` descendants).
3892    ///
3893    /// # Arguments
3894    ///
3895    /// - `&Self` - Mutable scene tree.
3896    /// - `NodeId` - Target text or selectable container node handle.
3897    ///
3898    /// # Returns
3899    ///
3900    /// - `bool` - `true` when at least one non-empty selectable text node was selected.
3901    pub fn select_all_text(&mut self, id: NodeId) -> bool {
3902        if !self.is_node_selectable(id) {
3903            return false;
3904        }
3905        let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
3906        let Some(&first_id) = nodes.first() else {
3907            return false;
3908        };
3909        let Some(&last_id) = nodes.last() else {
3910            return false;
3911        };
3912        let last_len: usize = self
3913            .get_node(last_id)
3914            .and_then(|node: &SceneNode| {
3915                if let NodeKind::Text(content) = node.get_kind() {
3916                    Some(content.chars().count())
3917                } else {
3918                    None
3919                }
3920            })
3921            .unwrap_or(0);
3922        if nodes.len() == 1 && last_len == 0 {
3923            return false;
3924        }
3925        self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
3926        true
3927    }
3928
3929    /// Selects the full visual row containing selectable text node `id` (used for triple-click across multi-span lines).
3930    ///
3931    /// # Arguments
3932    ///
3933    /// - `&Self` - Mutable scene tree.
3934    /// - `NodeId` - Clicked selectable text node handle.
3935    ///
3936    /// # Returns
3937    ///
3938    /// - `bool` - `true` when a non-empty visual line selection was applied.
3939    pub(crate) fn select_line_text(&mut self, id: NodeId) -> bool {
3940        if !self.is_node_selectable(id) {
3941            return false;
3942        }
3943        let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
3944        let Some(pos) = nodes.iter().position(|n: &NodeId| *n == id) else {
3945            return false;
3946        };
3947        let mut start_idx: usize = pos;
3948        while start_idx > 0 && !self.is_new_visual_row(nodes[start_idx - 1], id) {
3949            start_idx -= 1;
3950        }
3951        let mut end_idx: usize = pos;
3952        while end_idx + 1 < nodes.len() && !self.is_new_visual_row(id, nodes[end_idx + 1]) {
3953            end_idx += 1;
3954        }
3955        let first_id: NodeId = nodes[start_idx];
3956        let last_id: NodeId = nodes[end_idx];
3957        let last_len: usize = self
3958            .get_node(last_id)
3959            .and_then(|node: &SceneNode| {
3960                if let NodeKind::Text(content) = node.get_kind() {
3961                    Some(content.chars().count())
3962                } else {
3963                    None
3964                }
3965            })
3966            .unwrap_or(0);
3967        if first_id == last_id && last_len == 0 {
3968            return false;
3969        }
3970        self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
3971        true
3972    }
3973
3974    /// Hit-tests `pos` across all selectable `NodeKind::Text` nodes in `anchor_or_hit`'s scope, resolving exact or nearest visual row and character index.
3975    ///
3976    /// # Arguments
3977    ///
3978    /// - `&Self` - Scene tree reference.
3979    /// - `NodeId` - Anchor text node or selectable container node.
3980    /// - `Point` - Screen-space logical pointer coordinates.
3981    ///
3982    /// # Returns
3983    ///
3984    /// - `Option<(NodeId, usize)>` - Resolved `(node_id, char_index)` within the selectable scope.
3985    #[must_use]
3986    pub(crate) fn hit_test_selectable_scope(
3987        &self,
3988        anchor_or_hit: NodeId,
3989        pos: Point,
3990    ) -> Option<(NodeId, usize)> {
3991        let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_or_hit);
3992        if nodes.is_empty() {
3993            return None;
3994        }
3995        let mut rects: Vec<(NodeId, Rect, TextStyle, usize)> = Vec::with_capacity(nodes.len());
3996        let mut overall_min_y: f32 = f32::INFINITY;
3997        let mut overall_max_y: f32 = f32::NEG_INFINITY;
3998        for &nid in nodes.iter() {
3999            let Some(node) = self.get_node(nid) else {
4000                continue;
4001            };
4002            let NodeKind::Text(content) = node.get_kind() else {
4003                continue;
4004            };
4005            let Some(rect) = self.text_node_screen_content_rect(nid) else {
4006                continue;
4007            };
4008            let tstyle: TextStyle = node.get_style().get_text();
4009            if pos.get_x() >= rect.get_x()
4010                && pos.get_x() <= rect.right()
4011                && pos.get_y() >= rect.get_y()
4012                && pos.get_y() <= rect.bottom()
4013            {
4014                let ch: usize = hit_test_text_char(content.as_str(), tstyle, rect, pos);
4015                return Some((nid, ch));
4016            }
4017            if rect.get_y() < overall_min_y {
4018                overall_min_y = rect.get_y();
4019            }
4020            if rect.bottom() > overall_max_y {
4021                overall_max_y = rect.bottom();
4022            }
4023            rects.push((nid, rect, tstyle, content.chars().count()));
4024        }
4025        if rects.is_empty() {
4026            return None;
4027        }
4028        if pos.get_y() < overall_min_y - 4.0 {
4029            return Some((rects[0].0, 0));
4030        }
4031        if pos.get_y() > overall_max_y + 4.0 {
4032            let last: (NodeId, Rect, TextStyle, usize) = rects[rects.len() - 1];
4033            return Some((last.0, last.3));
4034        }
4035        let mut min_dy: f32 = f32::INFINITY;
4036        for &(_, rect, _, _) in rects.iter() {
4037            let dy: f32 = if pos.get_y() < rect.get_y() {
4038                rect.get_y() - pos.get_y()
4039            } else if pos.get_y() > rect.bottom() {
4040                pos.get_y() - rect.bottom()
4041            } else {
4042                0.0
4043            };
4044            if dy < min_dy {
4045                min_dy = dy;
4046            }
4047        }
4048        let mut best: Option<(NodeId, Rect, TextStyle, f32, f32)> = None;
4049        for &(nid, rect, tstyle, _) in rects.iter() {
4050            let dy: f32 = if pos.get_y() < rect.get_y() {
4051                rect.get_y() - pos.get_y()
4052            } else if pos.get_y() > rect.bottom() {
4053                pos.get_y() - rect.bottom()
4054            } else {
4055                0.0
4056            };
4057            if dy > min_dy + 2.0 {
4058                continue;
4059            }
4060            let dx: f32 = if pos.get_x() < rect.get_x() {
4061                rect.get_x() - pos.get_x()
4062            } else if pos.get_x() > rect.right() {
4063                pos.get_x() - rect.right()
4064            } else {
4065                0.0
4066            };
4067            let better: bool = match best {
4068                None => true,
4069                Some((_, _, _, b_dx, b_dy)) => dx < b_dx || (dx == b_dx && dy < b_dy),
4070            };
4071            if better {
4072                best = Some((nid, rect, tstyle, dx, dy));
4073            }
4074        }
4075        let (best_nid, best_rect, best_style, _, _): (NodeId, Rect, TextStyle, f32, f32) = best?;
4076        let best_node: &SceneNode = self.get_node(best_nid)?;
4077        let NodeKind::Text(content) = best_node.get_kind() else {
4078            return None;
4079        };
4080        let min_y: f32 = best_rect.get_y() + 0.5;
4081        let max_y: f32 = (best_rect.bottom() - 0.5).max(min_y);
4082        let clamped_y: f32 = pos.get_y().clamp(min_y, max_y);
4083        let ch: usize = hit_test_text_char(
4084            content.as_str(),
4085            best_style,
4086            best_rect,
4087            Point::new(pos.get_x(), clamped_y),
4088        );
4089        Some((best_nid, ch))
4090    }
4091}
4092
4093/// RAII depth-tracking methods for `SceneBorrowGuard`.
4094impl SceneBorrowGuard {
4095    /// Increments the thread-local `SceneTree` borrow depth and returns a guard that decrements it on drop.
4096    ///
4097    /// # Returns
4098    ///
4099    /// - `Self` - Active borrow depth guard.
4100    #[inline(always)]
4101    pub(crate) fn enter() -> Self {
4102        let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4103            depth.set(depth.get().saturating_add(1));
4104        });
4105        Self
4106    }
4107}
4108
4109/// Decrements the thread-local `SceneTree` borrow depth on scope exit.
4110impl Drop for SceneBorrowGuard {
4111    /// Decrements the active thread-local `SceneTree` borrow counter.
4112    ///
4113    /// # Arguments
4114    ///
4115    /// - `&Self` - Mutable guard being dropped.
4116    #[inline(always)]
4117    fn drop(&mut self) {
4118        let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4119            depth.set(depth.get().saturating_sub(1));
4120        });
4121    }
4122}
4123
4124/// Shared scene handle operations enabling surgical reactive node updates.
4125impl SceneHandle {
4126    /// Creates a new `SceneHandle` wrapping a fresh `SceneTree`.
4127    ///
4128    /// # Returns
4129    ///
4130    /// - `Self` - Shared scene handle.
4131    #[must_use]
4132    pub fn new_tree() -> Self {
4133        Self {
4134            inner: Rc::new(SceneHandleInner {
4135                tree: RefCell::new(SceneTree::default()),
4136                has_deferred: Cell::new(false),
4137                deferred_writes: RefCell::new(Vec::new()),
4138            }),
4139        }
4140    }
4141
4142    /// Returns `true` when re-entrant scene mutations are queued awaiting flush.
4143    ///
4144    /// # Arguments
4145    ///
4146    /// - `&Self` - Scene handle reference.
4147    ///
4148    /// # Returns
4149    ///
4150    /// - `bool` - Whether deferred scene mutations are pending.
4151    #[must_use]
4152    #[inline(always)]
4153    pub fn has_deferred_writes(&self) -> bool {
4154        let Self { inner } = self;
4155        inner.has_deferred.get()
4156    }
4157
4158    /// Executes all queued re-entrant scene mutations under an already-held mutable `SceneTree` borrow.
4159    ///
4160    /// # Arguments
4161    ///
4162    /// - `&SceneHandleInner` - Shared scene storage holding the deferred queue.
4163    /// - `&mut SceneTree` - Active mutable scene tree borrow.
4164    ///
4165    /// # Returns
4166    ///
4167    /// - `usize` - Number of deferred mutations executed.
4168    fn drain_deferred_locked(inner: &SceneHandleInner, tree: &mut SceneTree) -> usize {
4169        let mut executed: usize = 0;
4170        for _ in 0..MAX_FLUSH_ITERATIONS {
4171            let batch: Vec<DeferredSceneWrite> = match inner.deferred_writes.try_borrow_mut() {
4172                Ok(mut queue) => {
4173                    inner.has_deferred.set(false);
4174                    if queue.is_empty() {
4175                        break;
4176                    }
4177                    take(&mut *queue)
4178                }
4179                Err(_) => break,
4180            };
4181            for op in batch.into_iter() {
4182                op(tree);
4183                executed = executed.saturating_add(1);
4184            }
4185            if !inner.has_deferred.get() {
4186                break;
4187            }
4188        }
4189        executed
4190    }
4191
4192    /// Executes any pending re-entrant scene mutations queued while `SceneTree` was borrowed.
4193    ///
4194    /// # Arguments
4195    ///
4196    /// - `&Self` - Scene handle reference.
4197    ///
4198    /// # Returns
4199    ///
4200    /// - `usize` - Number of deferred mutations executed (`0` if queue is empty or tree is still borrowed).
4201    pub fn flush_deferred_writes(&self) -> usize {
4202        let Self { inner } = self;
4203        if !inner.has_deferred.get() {
4204            return 0;
4205        }
4206        let executed: usize = match inner.tree.try_borrow_mut() {
4207            Ok(mut guard) => {
4208                let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4209                Self::drain_deferred_locked(inner, &mut guard)
4210            }
4211            Err(_) => return 0,
4212        };
4213        if !is_scene_borrowed() && !panicking() && has_deferred_effect_flush() {
4214            self.flush_after_outer_borrow();
4215        }
4216        executed
4217    }
4218
4219    /// Checks whether deferred writes or deferred reactive effects need flushing after an outer borrow drops.
4220    ///
4221    /// # Arguments
4222    ///
4223    /// - `&Self` - Scene handle reference.
4224    #[inline(always)]
4225    fn finish_outer_borrow(&self) {
4226        if is_scene_borrowed() || panicking() {
4227            return;
4228        }
4229        let Self { inner } = self;
4230        if !inner.has_deferred.get() && !has_deferred_effect_flush() {
4231            return;
4232        }
4233        self.flush_after_outer_borrow();
4234    }
4235
4236    /// Drains interleaved deferred scene writes and deferred reactive effect flushes once no `SceneTree` borrow is active.
4237    ///
4238    /// # Arguments
4239    ///
4240    /// - `&Self` - Scene handle reference.
4241    #[cold]
4242    fn flush_after_outer_borrow(&self) {
4243        let Self { inner } = self;
4244        for _ in 0..MAX_FLUSH_ITERATIONS {
4245            let drained_writes: usize = if inner.has_deferred.get() {
4246                match inner.tree.try_borrow_mut() {
4247                    Ok(mut guard) => {
4248                        let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4249                        Self::drain_deferred_locked(inner, &mut guard)
4250                    }
4251                    Err(_) => 0,
4252                }
4253            } else {
4254                0
4255            };
4256            let flushed_effects: bool = if take_deferred_effect_flush() {
4257                flush_effects();
4258                true
4259            } else {
4260                false
4261            };
4262            if drained_writes == 0 && !flushed_effects && !inner.has_deferred.get() {
4263                break;
4264            }
4265        }
4266    }
4267
4268    /// Mutates the underlying `SceneTree` immediately when unborrowed (zero allocations) or queues `operation` re-entrantly until the outer borrow unwinds.
4269    ///
4270    /// # Arguments
4271    ///
4272    /// - `&Self` - Scene handle reference.
4273    /// - `F` - Guaranteed-delivery scene mutation closure.
4274    pub fn mutate<F>(&self, operation: F)
4275    where
4276        F: FnOnce(&mut SceneTree) + 'static,
4277    {
4278        let ran_inline: bool = {
4279            let Self { inner } = self;
4280            match inner.tree.try_borrow_mut() {
4281                Ok(mut guard) => {
4282                    let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4283                    operation(&mut guard);
4284                    if inner.has_deferred.get() {
4285                        let _: usize = Self::drain_deferred_locked(inner, &mut guard);
4286                    }
4287                    true
4288                }
4289                Err(_) => {
4290                    if let Ok(mut queue) = inner.deferred_writes.try_borrow_mut() {
4291                        queue.push(Box::new(operation));
4292                        inner.has_deferred.set(true);
4293                    }
4294                    notify_frame_needed();
4295                    false
4296                }
4297            }
4298        };
4299        if ran_inline {
4300            self.finish_outer_borrow();
4301        }
4302    }
4303
4304    /// Updates virtualized scroll metrics `(scroll_y, content_height)` on `id` for accurate scrollbar thumbs.
4305    ///
4306    /// # Arguments
4307    ///
4308    /// - `&Self` - Scene handle reference.
4309    /// - `NodeId` - Target virtualized scroll container.
4310    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
4311    /// - `f32` - Total virtualized content height in logical pixels.
4312    pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
4313        self.mutate(move |tree: &mut SceneTree| {
4314            tree.set_virtual_scroll(id, scroll_y, content_height);
4315        });
4316    }
4317
4318    /// Computes screen-space logical bounds for `id` subtracting ancestor scroll offsets.
4319    ///
4320    /// # Arguments
4321    ///
4322    /// - `&Self` - Scene handle reference.
4323    /// - `NodeId` - Target node handle.
4324    ///
4325    /// # Returns
4326    ///
4327    /// - `Option<Rect>` - Screen-space bounds if the node is alive.
4328    #[must_use]
4329    pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
4330        self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
4331    }
4332
4333    /// Starts or replaces a smooth paint/transform transition on the target node.
4334    ///
4335    /// # Arguments
4336    ///
4337    /// - `&Self` - Scene handle reference.
4338    /// - `NodeTransition` - Transition specification to run.
4339    pub fn start_transition(&self, transition: NodeTransition) {
4340        self.mutate(move |tree: &mut SceneTree| {
4341            tree.start_transition(transition);
4342        });
4343    }
4344
4345    /// Marks `id` dirty with `mask` for incremental repainting.
4346    ///
4347    /// # Arguments
4348    ///
4349    /// - `&Self` - Scene handle reference.
4350    /// - `NodeId` - Target node handle.
4351    /// - `u16` - Dirty flag bits.
4352    pub fn mark_dirty(&self, id: NodeId, mask: u16) {
4353        self.mutate(move |tree: &mut SceneTree| {
4354            tree.mark_dirty(id, mask);
4355        });
4356    }
4357
4358    /// Replaces all children of `parent` and finalizes disposed scopes and `Lifecycle` hooks outside the tree borrow.
4359    ///
4360    /// # Arguments
4361    ///
4362    /// - `&Self` - Scene handle reference.
4363    /// - `NodeId` - Parent container node.
4364    /// - `Vec<NodeId>` - Replacement ordered children.
4365    pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
4366        let (scopes, observers): DisposedSubtreePayload = self.with_write(
4367            |tree: &mut SceneTree| {
4368                if tree.get_node(parent).is_none() {
4369                    return (Vec::new(), Vec::new());
4370                }
4371                let parent_idx: usize = parent.as_usize();
4372                let old_children: Vec<NodeId> = tree.children_vec(parent);
4373                tree.unlink_all_children_at(parent_idx);
4374                let mut all_scopes: Vec<Scope> = Vec::new();
4375                let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
4376                if new_children.is_empty() {
4377                    for old_child in old_children.into_iter() {
4378                        let (sc, ob): DisposedSubtreePayload =
4379                            tree.dispose_subtree_collect(old_child);
4380                        all_scopes.extend(sc);
4381                        all_obs.extend(ob);
4382                    }
4383                } else if old_children.len() > 16 && new_children.len() > 16 {
4384                    let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
4385                    for old_child in old_children.into_iter() {
4386                        if !keep_set.contains(&old_child) {
4387                            let (sc, ob): DisposedSubtreePayload =
4388                                tree.dispose_subtree_collect(old_child);
4389                            all_scopes.extend(sc);
4390                            all_obs.extend(ob);
4391                        }
4392                    }
4393                } else {
4394                    for old_child in old_children.into_iter() {
4395                        if !new_children.contains(&old_child) {
4396                            let (sc, ob): DisposedSubtreePayload =
4397                                tree.dispose_subtree_collect(old_child);
4398                            all_scopes.extend(sc);
4399                            all_obs.extend(ob);
4400                        }
4401                    }
4402                }
4403                for child in new_children.into_iter() {
4404                    if child == parent || tree.get_node(child).is_none() {
4405                        continue;
4406                    }
4407                    let child_idx: usize = child.as_usize();
4408                    let prev_parent: u32 = tree.get_topology()[child_idx].get_parent();
4409                    if prev_parent != NODE_INDEX_NONE {
4410                        tree.unlink_child_at(prev_parent as usize, child_idx);
4411                    }
4412                    tree.link_child_tail_at(parent_idx, parent, child_idx);
4413                }
4414                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4415                (all_scopes, all_obs)
4416            },
4417            (Vec::new(), Vec::new()),
4418        );
4419        finalize_disposed_subtree(scopes, observers);
4420    }
4421
4422    /// Removes `child` from `parent`, disposes its subtree, and invokes `on_unmount`/`on_destroy` outside any scene borrow.
4423    ///
4424    /// # Arguments
4425    ///
4426    /// - `&Self` - Scene handle reference.
4427    /// - `NodeId` - Parent container handle.
4428    /// - `NodeId` - Child subtree root handle to remove and destroy.
4429    pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
4430        let (scopes, observers): DisposedSubtreePayload = self.with_write(
4431            |tree: &mut SceneTree| {
4432                if tree.get_node(parent).is_some() && tree.get_node(child).is_some() {
4433                    tree.unlink_child_at(parent.as_usize(), child.as_usize());
4434                }
4435                let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
4436                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4437                out
4438            },
4439            (Vec::new(), Vec::new()),
4440        );
4441        finalize_disposed_subtree(scopes, observers);
4442    }
4443
4444    /// Mutates a node's `Style` in place under one write lock, marking only minimal dirty flags when changed.
4445    ///
4446    /// # Arguments
4447    ///
4448    /// - `&Self` - Scene handle reference.
4449    /// - `NodeId` - Target node handle.
4450    /// - `F` - In-place style mutator closure receiving `&mut Style`.
4451    ///
4452    /// # Returns
4453    ///
4454    /// - `bool` - `true` when the node existed and its style changed.
4455    pub fn mutate_style<F>(&self, id: NodeId, mutator: F) -> bool
4456    where
4457        F: FnOnce(&mut Style),
4458    {
4459        self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
4460    }
4461
4462    /// Freezes a subtree visually (`Display::None`), cancels its transitions, and dispatches `Lifecycle::on_freeze` outside any scene borrow.
4463    ///
4464    /// # Arguments
4465    ///
4466    /// - `&Self` - Scene handle reference.
4467    /// - `NodeId` - Subtree root handle to freeze.
4468    pub fn freeze_subtree(&self, root: NodeId) {
4469        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4470            |tree: &mut SceneTree| {
4471                let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4472                tree.cancel_subtree_transitions(root);
4473                let changed: bool = if let Some(node) = tree.get_node_mut(root) {
4474                    let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4475                    if layout.get_display() == Display::None {
4476                        false
4477                    } else {
4478                        layout.set_display(Display::None);
4479                        true
4480                    }
4481                } else {
4482                    false
4483                };
4484                if changed {
4485                    tree.clear_subtree_hover(root);
4486                    tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4487                }
4488                obs
4489            },
4490            Vec::new(),
4491        );
4492        dispatch_lifecycle_freeze(&observers);
4493    }
4494
4495    /// Freezes a subtree immediately for lifecycle/effects while animating its visual exit to `Display::None`.
4496    ///
4497    /// # Arguments
4498    ///
4499    /// - `&Self` - Scene handle reference.
4500    /// - `NodeId` - Subtree root handle to freeze and animate out.
4501    /// - `NodeTransition` - Exit transition specification (`hide_on_complete` is enforced).
4502    pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
4503        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4504            |tree: &mut SceneTree| {
4505                let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4506                tree.cancel_subtree_transitions(root);
4507                let mut demoted_fixed: bool = false;
4508                let mut prev_z: i32 = 0;
4509                if let Some(node) = tree.get_node_mut(root) {
4510                    let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
4511                    let st: &mut Style = node.get_mut_style();
4512                    prev_z = st.layout_ref().get_z_index();
4513                    demoted_fixed = !is_portal && st.layout_ref().get_position() == Position::Fixed;
4514                    st.get_mut_layout()
4515                        .set_position(Position::Absolute)
4516                        .set_top(Some(0.0))
4517                        .set_right(Some(0.0))
4518                        .set_bottom(None)
4519                        .set_left(Some(0.0))
4520                        .set_z_index(0);
4521                    st.get_mut_paint().set_pointer_events(PointerEvents::None);
4522                }
4523                if prev_z != 0 {
4524                    let parent_idx: u32 = tree.get_topology()[root.as_usize()].get_parent();
4525                    if parent_idx != NODE_INDEX_NONE {
4526                        tree.sync_parent_nonzero_z(parent_idx as usize, prev_z, 0);
4527                    }
4528                }
4529                tree.clear_subtree_hover(root);
4530                if demoted_fixed {
4531                    tree.sync_portal_registration(root, false);
4532                }
4533                tree.start_transition(exit_transition.with_hide_on_complete(true));
4534                tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4535                obs
4536            },
4537            Vec::new(),
4538        );
4539        dispatch_lifecycle_freeze(&observers);
4540    }
4541
4542    /// Resumes a previously frozen subtree (`Display::Flex`) and dispatches `Lifecycle::on_resume` outside any scene borrow.
4543    ///
4544    /// # Arguments
4545    ///
4546    /// - `&Self` - Scene handle reference.
4547    /// - `NodeId` - Subtree root handle to resume.
4548    pub fn resume_subtree(&self, root: NodeId) {
4549        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4550            |tree: &mut SceneTree| {
4551                let mut unhidden: bool = false;
4552                if let Some(node) = tree.get_node_mut(root) {
4553                    let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4554                    if layout.get_display() == Display::None {
4555                        layout.set_display(Display::Flex);
4556                        unhidden = true;
4557                    }
4558                }
4559                if unhidden {
4560                    tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4561                } else {
4562                    tree.mark_dirty(root, DIRTY_PAINT);
4563                }
4564                tree.collect_subtree_lifecycles(root)
4565            },
4566            Vec::new(),
4567        );
4568        dispatch_lifecycle_resume(&observers);
4569    }
4570
4571    /// Dispatches `Lifecycle::on_activate` across all observers in the subtree rooted at `root`.
4572    ///
4573    /// # Arguments
4574    ///
4575    /// - `&Self` - Scene handle reference.
4576    /// - `NodeId` - Subtree root handle becoming active.
4577    pub fn activate_subtree(&self, root: NodeId) {
4578        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
4579            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
4580            Vec::new(),
4581        );
4582        dispatch_lifecycle_activate(&observers);
4583    }
4584
4585    /// Dispatches `Lifecycle::on_update` across all observers in the subtree rooted at `root`.
4586    ///
4587    /// # Arguments
4588    ///
4589    /// - `&Self` - Scene handle reference.
4590    /// - `NodeId` - Subtree root handle receiving updates.
4591    pub fn update_subtree(&self, root: NodeId) {
4592        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
4593            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
4594            Vec::new(),
4595        );
4596        dispatch_lifecycle_update(&observers);
4597    }
4598
4599    /// Dispatches `SystemEvent::Appear` to all `Lifecycle` observers and scoped hooks owned by `root`'s subtree.
4600    ///
4601    /// # Arguments
4602    ///
4603    /// - `&Self` - Scene handle reference.
4604    /// - `NodeId` - Page or component subtree root handle becoming visible.
4605    pub fn emit_subtree_appear(&self, root: NodeId) {
4606        let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
4607            |tree: &SceneTree| {
4608                (
4609                    tree.collect_subtree_lifecycles(root),
4610                    tree.collect_subtree_scope_ids(root),
4611                )
4612            },
4613            (Vec::new(), Vec::new()),
4614        );
4615        let ev: SystemEvent = SystemEvent::Appear;
4616        dispatch_lifecycle_system_event(&observers, &ev);
4617        dispatch_system_event_to_scopes(&scopes, &ev);
4618    }
4619
4620    /// Dispatches `SystemEvent::Disappear` to all `Lifecycle` observers and scoped hooks owned by `root`'s subtree.
4621    ///
4622    /// # Arguments
4623    ///
4624    /// - `&Self` - Scene handle reference.
4625    /// - `NodeId` - Page or component subtree root handle ceasing to be visible.
4626    pub fn emit_subtree_disappear(&self, root: NodeId) {
4627        let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
4628            |tree: &SceneTree| {
4629                (
4630                    tree.collect_subtree_lifecycles(root),
4631                    tree.collect_subtree_scope_ids(root),
4632                )
4633            },
4634            (Vec::new(), Vec::new()),
4635        );
4636        let ev: SystemEvent = SystemEvent::Disappear;
4637        dispatch_lifecycle_system_event(&observers, &ev);
4638        dispatch_system_event_to_scopes(&scopes, &ev);
4639    }
4640
4641    /// Returns `true` if any node transition is currently active.
4642    ///
4643    /// # Arguments
4644    ///
4645    /// - `&Self` - Scene handle reference.
4646    ///
4647    /// # Returns
4648    ///
4649    /// - `bool` - Whether animations are running.
4650    #[must_use]
4651    pub fn has_active_transitions(&self) -> bool {
4652        self.with_read(SceneTree::has_active_transitions, false)
4653    }
4654
4655    /// Returns the currently selected text substring across the retained scene, if any.
4656    ///
4657    /// # Arguments
4658    ///
4659    /// - `&Self` - Scene handle reference.
4660    ///
4661    /// # Returns
4662    ///
4663    /// - `Option<String>` - Active selected UTF-8 text.
4664    #[must_use]
4665    pub fn get_selected_text(&self) -> Option<String> {
4666        self.with_read(SceneTree::get_selected_text, None)
4667    }
4668
4669    /// Returns the currently selected UTF-8 text when the active selection lies inside `container`'s subtree.
4670    ///
4671    /// # Arguments
4672    ///
4673    /// - `&Self` - Scene handle reference.
4674    /// - `NodeId` - Container root node handle.
4675    ///
4676    /// # Returns
4677    ///
4678    /// - `Option<String>` - Active selected UTF-8 text inside `container`.
4679    #[must_use]
4680    pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
4681        self.with_read(
4682            |tree: &SceneTree| tree.get_selected_text_within(container),
4683            None,
4684        )
4685    }
4686
4687    /// Clears any active text selection across the retained scene.
4688    ///
4689    /// # Arguments
4690    ///
4691    /// - `&Self` - Scene handle reference.
4692    pub fn clear_text_selection(&self) {
4693        self.mutate(SceneTree::clear_text_selection);
4694    }
4695
4696    /// Executes `operation` with immutable access to the underlying `SceneTree`.
4697    ///
4698    /// # Arguments
4699    ///
4700    /// - `&Self` - Scene handle.
4701    /// - `F` - Reader closure.
4702    /// - `R` - Fallback if re-entrantly borrowed.
4703    ///
4704    /// # Returns
4705    ///
4706    /// - `R` - Closure result or fallback.
4707    pub fn with_read<F, R>(&self, operation: F, fallback: R) -> R
4708    where
4709        F: FnOnce(&SceneTree) -> R,
4710    {
4711        let result: R = {
4712            let Self { inner } = self;
4713            match inner.tree.try_borrow() {
4714                Ok(guard) => {
4715                    let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4716                    operation(&guard)
4717                }
4718                Err(_) => return fallback,
4719            }
4720        };
4721        self.finish_outer_borrow();
4722        result
4723    }
4724
4725    /// Executes `operation` with mutable access to the underlying `SceneTree`.
4726    ///
4727    /// # Arguments
4728    ///
4729    /// - `&Self` - Scene handle.
4730    /// - `F` - Mutation closure.
4731    /// - `R` - Fallback if re-entrantly borrowed.
4732    ///
4733    /// # Returns
4734    ///
4735    /// - `R` - Closure result or fallback.
4736    pub fn with_write<F, R>(&self, operation: F, fallback: R) -> R
4737    where
4738        F: FnOnce(&mut SceneTree) -> R,
4739    {
4740        let result: R = {
4741            let Self { inner } = self;
4742            match inner.tree.try_borrow_mut() {
4743                Ok(mut guard) => {
4744                    let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4745                    let out: R = operation(&mut guard);
4746                    if inner.has_deferred.get() {
4747                        let _: usize = Self::drain_deferred_locked(inner, &mut guard);
4748                    }
4749                    out
4750                }
4751                Err(_) => return fallback,
4752            }
4753        };
4754        self.finish_outer_borrow();
4755        result
4756    }
4757
4758    /// Binds a reactive text expression to `node_id` via a surgical `Effect`.
4759    ///
4760    /// # Arguments
4761    ///
4762    /// - `&Self` - Scene handle.
4763    /// - `NodeId` - Target text node.
4764    /// - `F` - Reactive text producer closure.
4765    ///
4766    /// # Returns
4767    ///
4768    /// - `Effect` - Registered reactive effect.
4769    pub fn bind_text<F>(&self, node_id: NodeId, mut producer: F) -> Effect
4770    where
4771        F: FnMut() -> String + 'static,
4772    {
4773        let handle: Self = self.clone();
4774        Effect::new(move || {
4775            let value: String = producer();
4776            handle.mutate(move |tree: &mut SceneTree| {
4777                tree.set_text(node_id, value);
4778            });
4779        })
4780    }
4781
4782    /// Binds a reactive `Style` expression to `node_id` via a surgical `Effect`.
4783    ///
4784    /// # Arguments
4785    ///
4786    /// - `&Self` - Scene handle.
4787    /// - `NodeId` - Target node.
4788    /// - `F` - Reactive style producer closure.
4789    ///
4790    /// # Returns
4791    ///
4792    /// - `Effect` - Registered reactive effect.
4793    pub fn bind_style<F>(&self, node_id: NodeId, mut producer: F) -> Effect
4794    where
4795        F: FnMut() -> Style + 'static,
4796    {
4797        let handle: Self = self.clone();
4798        Effect::new(move || {
4799            let style: Style = producer();
4800            handle.mutate(move |tree: &mut SceneTree| {
4801                tree.set_style(node_id, style);
4802            });
4803        })
4804    }
4805}
4806
4807/// Disposes all context-owned detached signals when the final `Context` clone drops.
4808impl Drop for ContextShared {
4809    /// Releases every reactive signal allocated by `Context::new` so repeated mount/exit cycles retain zero heap entries.
4810    ///
4811    /// # Arguments
4812    ///
4813    /// - `&Self` - Shared context state being dropped.
4814    fn drop(&mut self) {
4815        let Self {
4816            owned_signals,
4817            runtime_epoch,
4818            ..
4819        } = self;
4820        if *runtime_epoch != current_runtime_epoch() {
4821            return;
4822        }
4823        for sig_id in owned_signals.iter().copied() {
4824            let dropped: SignalSlot = with_runtime(
4825                |rt: &mut ReactiveRuntime| rt.dispose_signal(sig_id),
4826                SignalSlot::empty(),
4827            );
4828            drop(dropped);
4829        }
4830    }
4831}
4832
4833/// High-level declarative building helpers on `Context`.
4834impl Context {
4835    /// Creates a new `Context` with reactive viewport, theme, and safe-area signals.
4836    ///
4837    /// # Arguments
4838    ///
4839    /// - `SceneHandle` - Shared scene handle.
4840    /// - `PlatformKind` - Active platform kind.
4841    ///
4842    /// # Returns
4843    ///
4844    /// - `Self` - Constructed build context.
4845    #[must_use]
4846    pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
4847        let breakpoint: Signal<Breakpoint> = Signal::new_detached(Breakpoint::Expanded);
4848        let viewport_size: Signal<Size> = Signal::new_detached(Size::new(1200.0, 800.0));
4849        let theme_mode: Signal<ThemeMode> = Signal::new_detached(ThemeMode::Light);
4850        let safe_area: Signal<SafeAreaInsets> = Signal::new_detached(SafeAreaInsets::default());
4851        let gesture: Signal<Option<GestureEvent>> = Signal::new_detached(None);
4852        let swipe_drag_offset: Signal<f32> = Signal::new_detached(0.0);
4853        let system_back: Signal<u64> = Signal::new_detached(0);
4854        let fps_limit: Signal<Option<u32>> = Signal::new_detached(None);
4855        let live_fps: Signal<f32> = Signal::new_detached(60.0);
4856        let present_fps: Signal<f32> = Signal::new_detached(0.0);
4857        let is_idle: Signal<bool> = Signal::new_detached(true);
4858        let display_refresh_rate: Signal<f32> = Signal::new_detached(60.0);
4859        let active_touches: Signal<Vec<(u64, Point)>> = Signal::new_detached(Vec::new());
4860        let exit_requested: Signal<bool> = Signal::new_detached(false);
4861        let app_state: Signal<AppState> = Signal::new_detached(AppState::Active);
4862        let network_status: Signal<NetworkStatus> = Signal::new_detached(NetworkStatus::Online);
4863        let keyboard_visible: Signal<bool> = Signal::new_detached(false);
4864        let keyboard_height: Signal<f32> = Signal::new_detached(0.0);
4865        let orientation: Signal<ScreenOrientation> =
4866            Signal::new_detached(ScreenOrientation::Landscape);
4867        let low_power_mode: Signal<bool> = Signal::new_detached(false);
4868        let locale: Signal<String> = Signal::new_detached(DEFAULT_SYSTEM_LOCALE.to_string());
4869        let window_focused: Signal<bool> = Signal::new_detached(true);
4870        let immersive_fullscreen: Signal<bool> = Signal::new_detached(false);
4871        let device_motion: Signal<DeviceMotionSample> =
4872            Signal::new_detached(DeviceMotionSample::default());
4873        let owned_signals: [SignalId; 24] = [
4874            breakpoint.id(),
4875            viewport_size.id(),
4876            theme_mode.id(),
4877            safe_area.id(),
4878            gesture.id(),
4879            swipe_drag_offset.id(),
4880            system_back.id(),
4881            fps_limit.id(),
4882            live_fps.id(),
4883            present_fps.id(),
4884            is_idle.id(),
4885            display_refresh_rate.id(),
4886            active_touches.id(),
4887            exit_requested.id(),
4888            app_state.id(),
4889            network_status.id(),
4890            keyboard_visible.id(),
4891            keyboard_height.id(),
4892            orientation.id(),
4893            low_power_mode.id(),
4894            locale.id(),
4895            window_focused.id(),
4896            immersive_fullscreen.id(),
4897            device_motion.id(),
4898        ];
4899        Self {
4900            scene,
4901            breakpoint,
4902            viewport_size,
4903            theme_mode,
4904            platform,
4905            safe_area,
4906            gesture,
4907            swipe_drag_offset,
4908            system_back,
4909            dynamic_hub: DynamicUpdateHub::new(),
4910            fps_limit,
4911            live_fps,
4912            present_fps,
4913            is_idle,
4914            display_refresh_rate,
4915            active_touches,
4916            exit_requested,
4917            app_state,
4918            network_status,
4919            keyboard_visible,
4920            keyboard_height,
4921            orientation,
4922            low_power_mode,
4923            locale,
4924            window_focused,
4925            immersive_fullscreen,
4926            device_motion,
4927            shared: Rc::new(ContextShared {
4928                fullscreen_depth: Cell::new(0),
4929                clock_ms: Cell::new(0),
4930                owned_signals,
4931                runtime_epoch: current_runtime_epoch(),
4932            }),
4933        }
4934    }
4935
4936    /// Returns the reactive `Signal<SafeAreaInsets>` updated on cold start, orientation changes, and Dynamic/Atomic Island updates.
4937    ///
4938    /// # Arguments
4939    ///
4940    /// - `&Self` - Context reference.
4941    ///
4942    /// # Returns
4943    ///
4944    /// - `Signal<SafeAreaInsets>` - Reactive safe-area insets signal.
4945    #[must_use]
4946    pub fn safe_area_signal(&self) -> Signal<SafeAreaInsets> {
4947        self.get_safe_area()
4948    }
4949
4950    /// Reads the current `SafeAreaInsets` reactively, subscribing the enclosing `Effect` or `Memo`.
4951    ///
4952    /// # Arguments
4953    ///
4954    /// - `&Self` - Context reference.
4955    ///
4956    /// # Returns
4957    ///
4958    /// - `SafeAreaInsets` - Active safe-area insets in logical pixels.
4959    #[must_use]
4960    pub fn safe_area(&self) -> SafeAreaInsets {
4961        self.get_safe_area().get()
4962    }
4963
4964    /// Returns the reactive `Signal<bool>` indicating whether immersive fullscreen mode is active.
4965    ///
4966    /// # Arguments
4967    ///
4968    /// - `&Self` - Context reference.
4969    ///
4970    /// # Returns
4971    ///
4972    /// - `Signal<bool>` - Reactive immersive fullscreen state signal.
4973    #[must_use]
4974    pub fn immersive_fullscreen_signal(&self) -> Signal<bool> {
4975        self.get_immersive_fullscreen()
4976    }
4977
4978    /// Reads whether immersive fullscreen mode is currently active, subscribing the enclosing reactive scope.
4979    ///
4980    /// # Arguments
4981    ///
4982    /// - `&Self` - Context reference.
4983    ///
4984    /// # Returns
4985    ///
4986    /// - `bool` - `true` while immersive fullscreen is active.
4987    #[must_use]
4988    pub fn is_immersive_fullscreen(&self) -> bool {
4989        self.get_immersive_fullscreen().get()
4990    }
4991
4992    /// Explicitly sets immersive fullscreen state across both reactive UI chrome and OS system bars.
4993    ///
4994    /// # Arguments
4995    ///
4996    /// - `&Self` - Context reference.
4997    /// - `bool` - `true` to enter immersive fullscreen; `false` to exit and restore bars.
4998    pub fn set_immersive_fullscreen(&self, enabled: bool) {
4999        let Self { shared, .. } = self;
5000        if enabled {
5001            if shared.fullscreen_depth.get() == 0 {
5002                shared.fullscreen_depth.set(1);
5003            }
5004            let _: bool = self.get_immersive_fullscreen().set_if_changed(true);
5005        } else {
5006            shared.fullscreen_depth.set(0);
5007            let _: bool = self.get_immersive_fullscreen().set_if_changed(false);
5008        }
5009    }
5010
5011    /// Increments the nested immersive fullscreen entry count and activates fullscreen mode.
5012    ///
5013    /// # Arguments
5014    ///
5015    /// - `&Self` - Context reference.
5016    pub fn enter_immersive_fullscreen(&self) {
5017        let Self { shared, .. } = self;
5018        let next: u32 = shared.fullscreen_depth.get().saturating_add(1);
5019        shared.fullscreen_depth.set(next);
5020        let _: bool = self.get_immersive_fullscreen().set_if_changed(true);
5021    }
5022
5023    /// Decrements the nested immersive fullscreen entry count and restores bars when the count reaches zero.
5024    ///
5025    /// # Arguments
5026    ///
5027    /// - `&Self` - Context reference.
5028    pub fn exit_immersive_fullscreen(&self) {
5029        let Self { shared, .. } = self;
5030        let next: u32 = shared.fullscreen_depth.get().saturating_sub(1);
5031        shared.fullscreen_depth.set(next);
5032        if next == 0 {
5033            let _: bool = self.get_immersive_fullscreen().set_if_changed(false);
5034        }
5035    }
5036
5037    /// Returns the reactive `Signal<AppState>` tracking canonical cross-platform application lifecycle state.
5038    ///
5039    /// # Arguments
5040    ///
5041    /// - `&Self` - Context reference.
5042    ///
5043    /// # Returns
5044    ///
5045    /// - `Signal<AppState>` - Reactive lifecycle state signal.
5046    #[must_use]
5047    pub fn app_state_signal(&self) -> Signal<AppState> {
5048        self.get_app_state()
5049    }
5050
5051    /// Dispatches a page-level `SystemEvent::Appear` to all currently active non-frozen hooks and visible observers.
5052    ///
5053    /// # Arguments
5054    ///
5055    /// - `&Self` - Context reference.
5056    pub fn emit_page_appear(&self) {
5057        let ev: SystemEvent = SystemEvent::Appear;
5058        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5059            .get_scene()
5060            .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5061        dispatch_lifecycle_system_event(&observers, &ev);
5062        dispatch_system_event_listeners(&ev);
5063    }
5064
5065    /// Dispatches a page-level `SystemEvent::Disappear` to all currently active non-frozen hooks and visible observers.
5066    ///
5067    /// # Arguments
5068    ///
5069    /// - `&Self` - Context reference.
5070    pub fn emit_page_disappear(&self) {
5071        let ev: SystemEvent = SystemEvent::Disappear;
5072        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5073            .get_scene()
5074            .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5075        dispatch_lifecycle_system_event(&observers, &ev);
5076        dispatch_system_event_listeners(&ev);
5077    }
5078
5079    /// Dispatches `SystemEvent::Appear` strictly to `Lifecycle` components and scoped hooks within `root`'s subtree.
5080    ///
5081    /// # Arguments
5082    ///
5083    /// - `&Self` - Context reference.
5084    /// - `NodeId` - Routed page or component subtree root handle becoming active.
5085    pub fn emit_subtree_appear(&self, root: NodeId) {
5086        self.get_scene().emit_subtree_appear(root);
5087    }
5088
5089    /// Dispatches `SystemEvent::Disappear` strictly to `Lifecycle` components and scoped hooks within `root`'s subtree.
5090    ///
5091    /// # Arguments
5092    ///
5093    /// - `&Self` - Context reference.
5094    /// - `NodeId` - Routed page or component subtree root handle becoming hidden.
5095    pub fn emit_subtree_disappear(&self, root: NodeId) {
5096        self.get_scene().emit_subtree_disappear(root);
5097    }
5098
5099    /// Returns the monotonic runtime elapsed clock in milliseconds.
5100    ///
5101    /// # Arguments
5102    ///
5103    /// - `&Self` - Context reference.
5104    ///
5105    /// # Returns
5106    ///
5107    /// - `u64` - Elapsed runtime time in milliseconds.
5108    #[must_use]
5109    pub fn elapsed_ms(&self) -> u64 {
5110        let Self { shared, .. } = self;
5111        shared.clock_ms.get()
5112    }
5113
5114    /// Advances the context's monotonic runtime clock by `delta_ms` milliseconds.
5115    ///
5116    /// # Arguments
5117    ///
5118    /// - `&Self` - Context reference.
5119    /// - `u64` - Milliseconds elapsed since the previous frame.
5120    pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
5121        let Self { shared, .. } = self;
5122        shared
5123            .clock_ms
5124            .set(shared.clock_ms.get().saturating_add(delta_ms));
5125    }
5126
5127    /// Requests graceful OS-level application termination across all platforms.
5128    ///
5129    /// # Arguments
5130    ///
5131    /// - `&Self` - Context reference.
5132    pub fn request_exit(&self) {
5133        let _: bool = self.get_exit_requested().set_if_changed(true);
5134        let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
5135    }
5136
5137    /// Copies `text` to the host OS or browser clipboard via native clipboard hooks.
5138    ///
5139    /// # Arguments
5140    ///
5141    /// - `&Self` - Context reference.
5142    /// - `&str` - UTF-8 text string to copy.
5143    ///
5144    /// # Returns
5145    ///
5146    /// - `bool` - `true` when a native or host clipboard bridge accepted `text`.
5147    pub fn copy_to_clipboard(&self, text: &str) -> bool {
5148        write_system_clipboard(text)
5149    }
5150
5151    /// Creates a `View` node with the given style.
5152    ///
5153    /// # Arguments
5154    ///
5155    /// - `&Self` - Build context.
5156    /// - `Style` - Initial style.
5157    ///
5158    /// # Returns
5159    ///
5160    /// - `NodeId` - Created node handle.
5161    pub fn view(&mut self, style: Style) -> NodeId {
5162        self.get_scene().with_write(
5163            |tree: &mut SceneTree| tree.create_view(style),
5164            NodeId::default(),
5165        )
5166    }
5167
5168    /// Creates a `Text` node with static initial text.
5169    ///
5170    /// # Arguments
5171    ///
5172    /// - `&Self` - Build context.
5173    /// - `String` - Text content.
5174    /// - `Style` - Text style.
5175    ///
5176    /// # Returns
5177    ///
5178    /// - `NodeId` - Created node handle.
5179    pub fn text(&mut self, content: String, style: Style) -> NodeId {
5180        self.get_scene().with_write(
5181            |tree: &mut SceneTree| tree.create_text(content, style),
5182            NodeId::default(),
5183        )
5184    }
5185
5186    /// Creates a reactive `Text` node whose content updates surgically whenever tracked signals change.
5187    ///
5188    /// # Arguments
5189    ///
5190    /// - `&Self` - Build context.
5191    /// - `Style` - Text style.
5192    /// - `F` - Reactive text producer.
5193    ///
5194    /// # Returns
5195    ///
5196    /// - `NodeId` - Created reactive text node handle.
5197    pub fn reactive_text<F>(&mut self, style: Style, producer: F) -> NodeId
5198    where
5199        F: FnMut() -> String + 'static,
5200    {
5201        let node_id: NodeId = self.text(String::new(), style);
5202        let handle: SceneHandle = self.get_scene().clone();
5203        let (scope, _): (Scope, Effect) =
5204            Scope::run(|_: Scope| handle.bind_text(node_id, producer));
5205        self.get_scene().with_write(
5206            |tree: &mut SceneTree| {
5207                tree.attach_scope(node_id, scope);
5208            },
5209            (),
5210        );
5211        node_id
5212    }
5213
5214    /// Creates a `ScrollView` node with the given style.
5215    ///
5216    /// # Arguments
5217    ///
5218    /// - `&Self` - Build context.
5219    /// - `Style` - Scroll container style.
5220    ///
5221    /// # Returns
5222    ///
5223    /// - `NodeId` - Created scroll view handle.
5224    pub fn scroll_view(&mut self, style: Style) -> NodeId {
5225        self.get_scene().with_write(
5226            |tree: &mut SceneTree| tree.create_scroll_view(style),
5227            NodeId::default(),
5228        )
5229    }
5230
5231    /// Creates an `Input` node with initial state and style.
5232    ///
5233    /// # Arguments
5234    ///
5235    /// - `&Self` - Build context.
5236    /// - `InputNodeState` - Initial input state.
5237    /// - `Style` - Input style.
5238    ///
5239    /// # Returns
5240    ///
5241    /// - `NodeId` - Created input handle.
5242    pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
5243        self.get_scene().with_write(
5244            |tree: &mut SceneTree| tree.create_input(state, style),
5245            NodeId::default(),
5246        )
5247    }
5248
5249    /// Creates an `Image` node with decoded RGBA8 pixel data.
5250    ///
5251    /// # Arguments
5252    ///
5253    /// - `&Self` - Build context.
5254    /// - `ImageBuffer` - Image buffer.
5255    /// - `Style` - Image style.
5256    ///
5257    /// # Returns
5258    ///
5259    /// - `NodeId` - Created image handle.
5260    pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
5261        self.get_scene().with_write(
5262            |tree: &mut SceneTree| tree.create_image(buffer, style),
5263            NodeId::default(),
5264        )
5265    }
5266
5267    /// Creates a `Canvas` node bound to a custom draw callback.
5268    ///
5269    /// # Arguments
5270    ///
5271    /// - `&Self` - Build context.
5272    /// - `Style` - Canvas style.
5273    /// - `F` - Draw callback receiving node bounds and mutable `DisplayList`.
5274    ///
5275    /// # Returns
5276    ///
5277    /// - `NodeId` - Created canvas handle.
5278    pub fn canvas<F>(&mut self, style: Style, painter: F) -> NodeId
5279    where
5280        F: FnMut(Rect, &mut DisplayList) + 'static,
5281    {
5282        self.canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
5283    }
5284
5285    /// Creates a `Canvas` node bound to a custom draw callback with an explicit `CanvasCaching` strategy.
5286    ///
5287    /// # Arguments
5288    ///
5289    /// - `&Self` - Build context.
5290    /// - `Style` - Canvas style.
5291    /// - `CanvasCaching` - Fragment caching strategy (`DynamicPerFrame` or `RetainedStatic`).
5292    /// - `F` - Draw callback receiving node bounds and mutable `DisplayList`.
5293    ///
5294    /// # Returns
5295    ///
5296    /// - `NodeId` - Created canvas handle.
5297    pub fn canvas_with_caching<F>(
5298        &mut self,
5299        style: Style,
5300        caching: CanvasCaching,
5301        painter: F,
5302    ) -> NodeId
5303    where
5304        F: FnMut(Rect, &mut DisplayList) + 'static,
5305    {
5306        let cb: CanvasDrawCallback = Rc::new(RefCell::new(painter));
5307        self.get_scene().with_write(
5308            |tree: &mut SceneTree| tree.create_canvas_with_caching(style, caching, cb),
5309            NodeId::default(),
5310        )
5311    }
5312
5313    /// Creates an overlay `Portal` node.
5314    ///
5315    /// # Arguments
5316    ///
5317    /// - `&Self` - Build context.
5318    /// - `Style` - Portal style.
5319    ///
5320    /// # Returns
5321    ///
5322    /// - `NodeId` - Created portal handle.
5323    pub fn portal(&mut self, style: Style) -> NodeId {
5324        self.get_scene().with_write(
5325            |tree: &mut SceneTree| tree.create_portal(style),
5326            NodeId::default(),
5327        )
5328    }
5329
5330    /// Creates a transparent logical `Fragment` grouping container for sibling nodes.
5331    ///
5332    /// # Arguments
5333    ///
5334    /// - `&Self` - Build context.
5335    ///
5336    /// # Returns
5337    ///
5338    /// - `NodeId` - Created fragment handle.
5339    pub fn fragment(&mut self) -> NodeId {
5340        self.get_scene().with_write(
5341            |tree: &mut SceneTree| tree.create_fragment(),
5342            NodeId::default(),
5343        )
5344    }
5345
5346    /// Appends `child` to `parent`.
5347    ///
5348    /// # Arguments
5349    ///
5350    /// - `&Self` - Build context.
5351    /// - `NodeId` - Parent container.
5352    /// - `NodeId` - Child node.
5353    pub fn append(&mut self, parent: NodeId, child: NodeId) {
5354        self.get_scene().with_write(
5355            |tree: &mut SceneTree| {
5356                tree.append_child(parent, child);
5357            },
5358            (),
5359        );
5360    }
5361
5362    /// Appends a slice of `children` to `parent` under a single scene write lock and dirty pass.
5363    ///
5364    /// # Arguments
5365    ///
5366    /// - `&Self` - Build context.
5367    /// - `NodeId` - Parent container.
5368    /// - `&[NodeId]` - Ordered child node slice.
5369    pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
5370        if children.is_empty() {
5371            return;
5372        }
5373        self.get_scene().with_write(
5374            |tree: &mut SceneTree| {
5375                tree.append_children(parent, children);
5376            },
5377            (),
5378        );
5379    }
5380
5381    /// Binds a reactive `Style` closure to `node_id` and attaches its disposal `Scope` automatically.
5382    ///
5383    /// # Arguments
5384    ///
5385    /// - `&Self` - Build context.
5386    /// - `NodeId` - Target scene node.
5387    /// - `F` - Reactive `Style` producer closure.
5388    pub fn bind_style<F>(&mut self, node_id: NodeId, producer: F)
5389    where
5390        F: FnMut() -> Style + 'static,
5391    {
5392        let handle: SceneHandle = self.get_scene().clone();
5393        let (scope, _): (Scope, Effect) =
5394            Scope::run(|_: Scope| handle.bind_style(node_id, producer));
5395        self.get_scene().with_write(
5396            |tree: &mut SceneTree| {
5397                tree.attach_scope(node_id, scope);
5398            },
5399            (),
5400        );
5401    }
5402
5403    /// Registers a pointer-enter handler on `node_id`.
5404    ///
5405    /// # Arguments
5406    ///
5407    /// - `&Self` - Build context.
5408    /// - `NodeId` - Target node handle.
5409    /// - `F` - Pointer-enter callback closure.
5410    pub fn on_pointer_enter<F>(&mut self, node_id: NodeId, callback: F)
5411    where
5412        F: FnMut(&UiEvent) + 'static,
5413    {
5414        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5415        self.get_scene().with_write(
5416            |tree: &mut SceneTree| {
5417                if let Some(node) = tree.get_node_mut(node_id) {
5418                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
5419                }
5420            },
5421            (),
5422        );
5423    }
5424
5425    /// Registers a pointer-leave handler on `node_id`.
5426    ///
5427    /// # Arguments
5428    ///
5429    /// - `&Self` - Build context.
5430    /// - `NodeId` - Target node handle.
5431    /// - `F` - Pointer-leave callback closure.
5432    pub fn on_pointer_leave<F>(&mut self, node_id: NodeId, callback: F)
5433    where
5434        F: FnMut(&UiEvent) + 'static,
5435    {
5436        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5437        self.get_scene().with_write(
5438            |tree: &mut SceneTree| {
5439                if let Some(node) = tree.get_node_mut(node_id) {
5440                    node.get_mut_handlers().set_on_pointer_leave(Some(handler));
5441                }
5442            },
5443            (),
5444        );
5445    }
5446
5447    /// Registers a focus-gained handler on `node_id` and marks it focusable.
5448    ///
5449    /// # Arguments
5450    ///
5451    /// - `&Self` - Build context.
5452    /// - `NodeId` - Target node handle.
5453    /// - `F` - Focus callback closure receiving `UiEventKind::Focus`.
5454    pub fn on_focus<F>(&mut self, node_id: NodeId, callback: F)
5455    where
5456        F: FnMut(&UiEvent) + 'static,
5457    {
5458        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5459        self.get_scene().with_write(
5460            |tree: &mut SceneTree| {
5461                if let Some(node) = tree.get_node_mut(node_id) {
5462                    node.get_mut_handlers().set_on_focus(Some(handler));
5463                    node.get_mut_interaction().set_focusable(true);
5464                }
5465            },
5466            (),
5467        );
5468    }
5469
5470    /// Registers a focus-lost handler on `node_id`.
5471    ///
5472    /// # Arguments
5473    ///
5474    /// - `&Self` - Build context.
5475    /// - `NodeId` - Target node handle.
5476    /// - `F` - Blur callback closure receiving `UiEventKind::Blur`.
5477    pub fn on_blur<F>(&mut self, node_id: NodeId, callback: F)
5478    where
5479        F: FnMut(&UiEvent) + 'static,
5480    {
5481        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5482        self.get_scene().with_write(
5483            |tree: &mut SceneTree| {
5484                if let Some(node) = tree.get_node_mut(node_id) {
5485                    node.get_mut_handlers().set_on_blur(Some(handler));
5486                }
5487            },
5488            (),
5489        );
5490    }
5491
5492    /// Configures whether `node_id` participates in keyboard focus navigation.
5493    ///
5494    /// # Arguments
5495    ///
5496    /// - `&Self` - Build context.
5497    /// - `NodeId` - Target node handle.
5498    /// - `bool` - Whether keyboard focus is enabled.
5499    pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
5500        self.get_scene().with_write(
5501            |tree: &mut SceneTree| {
5502                if let Some(node) = tree.get_node_mut(node_id) {
5503                    node.get_mut_interaction().set_focusable(focusable);
5504                }
5505            },
5506            (),
5507        );
5508    }
5509
5510    /// Registers a click handler on `node_id` and sets pointer cursor automatically.
5511    ///
5512    /// # Arguments
5513    ///
5514    /// - `&Self` - Build context.
5515    /// - `NodeId` - Target node.
5516    /// - `F` - Click callback closure.
5517    pub fn on_click<F>(&mut self, node_id: NodeId, callback: F)
5518    where
5519        F: FnMut(&UiEvent) + 'static,
5520    {
5521        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5522        self.get_scene().with_write(
5523            |tree: &mut SceneTree| {
5524                if let Some(node) = tree.get_node_mut(node_id) {
5525                    node.get_mut_handlers().set_on_click(Some(handler));
5526                    node.get_mut_interaction().set_focusable(true);
5527                    let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
5528                    if paint.get_cursor() == CursorIcon::Default {
5529                        paint.set_cursor(CursorIcon::Pointer);
5530                    }
5531                }
5532            },
5533            (),
5534        );
5535    }
5536
5537    /// Registers a change handler on an `Input` node.
5538    ///
5539    /// # Arguments
5540    ///
5541    /// - `&Self` - Build context.
5542    /// - `NodeId` - Target input node.
5543    /// - `F` - Change callback closure.
5544    pub fn on_change<F>(&mut self, node_id: NodeId, callback: F)
5545    where
5546        F: FnMut(&UiEvent) + 'static,
5547    {
5548        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5549        self.get_scene().with_write(
5550            |tree: &mut SceneTree| {
5551                if let Some(node) = tree.get_node_mut(node_id) {
5552                    node.get_mut_handlers().set_on_change(Some(handler));
5553                }
5554            },
5555            (),
5556        );
5557    }
5558
5559    /// Attaches semantic accessibility properties to `node_id`.
5560    ///
5561    /// # Arguments
5562    ///
5563    /// - `&Self` - Build context.
5564    /// - `NodeId` - Target scene node.
5565    /// - `A11yProps` - Semantic role, label, hint, and state metadata.
5566    pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
5567        self.get_scene().with_write(
5568            |tree: &mut SceneTree| {
5569                if let Some(node) = tree.get_node_mut(node_id) {
5570                    node.set_a11y(Some(props));
5571                }
5572            },
5573            (),
5574        );
5575    }
5576
5577    /// Registers a scroll handler on a scrollable container node.
5578    ///
5579    /// # Arguments
5580    ///
5581    /// - `&Self` - Build context.
5582    /// - `NodeId` - Target scroll container node.
5583    /// - `F` - Scroll callback closure receiving `UiEventKind::Scroll(delta)`.
5584    pub fn on_scroll<F>(&mut self, node_id: NodeId, callback: F)
5585    where
5586        F: FnMut(&UiEvent) + 'static,
5587    {
5588        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5589        self.get_scene().with_write(
5590            |tree: &mut SceneTree| {
5591                if let Some(node) = tree.get_node_mut(node_id) {
5592                    node.get_mut_handlers().set_on_scroll(Some(handler));
5593                }
5594            },
5595            (),
5596        );
5597    }
5598
5599    /// Registers a pointer-down handler on `node_id` for draggable interactive controls.
5600    ///
5601    /// # Arguments
5602    ///
5603    /// - `&Self` - Build context.
5604    /// - `NodeId` - Target node handle.
5605    /// - `F` - Pointer-down callback closure.
5606    pub fn on_pointer_down<F>(&mut self, node_id: NodeId, callback: F)
5607    where
5608        F: FnMut(&UiEvent) + 'static,
5609    {
5610        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5611        self.get_scene().with_write(
5612            |tree: &mut SceneTree| {
5613                if let Some(node) = tree.get_node_mut(node_id) {
5614                    node.get_mut_handlers().set_on_pointer_down(Some(handler));
5615                    let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
5616                    if paint.get_cursor() == CursorIcon::Default {
5617                        paint.set_cursor(CursorIcon::Pointer);
5618                    }
5619                }
5620            },
5621            (),
5622        );
5623    }
5624
5625    /// Registers a pointer-move handler on `node_id` receiving captured drag coordinates while pressed.
5626    ///
5627    /// # Arguments
5628    ///
5629    /// - `&Self` - Build context.
5630    /// - `NodeId` - Target node handle.
5631    /// - `F` - Pointer-move callback closure.
5632    pub fn on_pointer_move<F>(&mut self, node_id: NodeId, callback: F)
5633    where
5634        F: FnMut(&UiEvent) + 'static,
5635    {
5636        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5637        self.get_scene().with_write(
5638            |tree: &mut SceneTree| {
5639                if let Some(node) = tree.get_node_mut(node_id) {
5640                    node.get_mut_handlers().set_on_pointer_move(Some(handler));
5641                }
5642            },
5643            (),
5644        );
5645    }
5646
5647    /// Registers a pointer-up handler on `node_id` invoked when drag capture releases.
5648    ///
5649    /// # Arguments
5650    ///
5651    /// - `&Self` - Build context.
5652    /// - `NodeId` - Target node handle.
5653    /// - `F` - Pointer-up callback closure.
5654    pub fn on_pointer_up<F>(&mut self, node_id: NodeId, callback: F)
5655    where
5656        F: FnMut(&UiEvent) + 'static,
5657    {
5658        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5659        self.get_scene().with_write(
5660            |tree: &mut SceneTree| {
5661                if let Some(node) = tree.get_node_mut(node_id) {
5662                    node.get_mut_handlers().set_on_pointer_up(Some(handler));
5663                }
5664            },
5665            (),
5666        );
5667    }
5668
5669    /// Registers a pointer-cancel handler on `node_id` invoked when OS or gesture arbitration cancels a press.
5670    ///
5671    /// # Arguments
5672    ///
5673    /// - `&Self` - Build context.
5674    /// - `NodeId` - Target node handle.
5675    /// - `F` - Pointer-cancel callback closure receiving `UiEventKind::PointerCancel`.
5676    pub fn on_pointer_cancel<F>(&mut self, node_id: NodeId, callback: F)
5677    where
5678        F: FnMut(&UiEvent) + 'static,
5679    {
5680        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5681        self.get_scene().with_write(
5682            |tree: &mut SceneTree| {
5683                if let Some(node) = tree.get_node_mut(node_id) {
5684                    node.get_mut_handlers().set_on_pointer_cancel(Some(handler));
5685                }
5686            },
5687            (),
5688        );
5689    }
5690
5691    /// Registers a hover handler on `node_id` invoked on both `PointerEnter` and `PointerLeave`.
5692    ///
5693    /// # Arguments
5694    ///
5695    /// - `&Self` - Build context.
5696    /// - `NodeId` - Target node handle.
5697    /// - `F` - Hover callback closure receiving `UiEventKind::PointerEnter` or `PointerLeave`.
5698    pub fn on_hover<F>(&mut self, node_id: NodeId, callback: F)
5699    where
5700        F: FnMut(&UiEvent) + 'static,
5701    {
5702        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5703        let leave_handler: UiEventHandler = handler.clone();
5704        self.get_scene().with_write(
5705            |tree: &mut SceneTree| {
5706                if let Some(node) = tree.get_node_mut(node_id) {
5707                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
5708                    node.get_mut_handlers()
5709                        .set_on_pointer_leave(Some(leave_handler));
5710                }
5711            },
5712            (),
5713        );
5714    }
5715
5716    /// Registers a keyboard key-down handler on `node_id` and marks it focusable.
5717    ///
5718    /// # Arguments
5719    ///
5720    /// - `&Self` - Build context.
5721    /// - `NodeId` - Target node handle.
5722    /// - `F` - Key-down callback closure receiving `UiEventKind::KeyDown`.
5723    pub fn on_key<F>(&mut self, node_id: NodeId, callback: F)
5724    where
5725        F: FnMut(&UiEvent) + 'static,
5726    {
5727        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5728        self.get_scene().with_write(
5729            |tree: &mut SceneTree| {
5730                if let Some(node) = tree.get_node_mut(node_id) {
5731                    node.get_mut_handlers().set_on_key_down(Some(handler));
5732                    node.get_mut_interaction().set_focusable(true);
5733                }
5734            },
5735            (),
5736        );
5737    }
5738
5739    /// Records virtualized scroll progress on `node_id` so the overlay scrollbar tracks accurately.
5740    ///
5741    /// # Arguments
5742    ///
5743    /// - `&Self` - Build context.
5744    /// - `NodeId` - Target virtualized scroll container.
5745    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
5746    /// - `f32` - Full virtualized content height in logical pixels.
5747    pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
5748        self.get_scene()
5749            .set_virtual_scroll(node_id, scroll_y, content_height);
5750    }
5751
5752    /// Sets the concrete inner pixel scroll offset on `node_id` (used by virtualized lists for sub-pixel alignment).
5753    ///
5754    /// # Arguments
5755    ///
5756    /// - `&Self` - Build context.
5757    /// - `NodeId` - Target scroll container.
5758    /// - `Point` - Scroll offset `(x, y)` in logical pixels.
5759    pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
5760        self.get_scene().with_write(
5761            |tree: &mut SceneTree| {
5762                tree.set_scroll_offset(node_id, offset);
5763            },
5764            (),
5765        );
5766    }
5767
5768    /// Starts a smooth paint/transform transition on `transition.get_node()`.
5769    ///
5770    /// # Arguments
5771    ///
5772    /// - `&Self` - Build context.
5773    /// - `NodeTransition` - Transition specification.
5774    pub fn start_transition(&mut self, transition: NodeTransition) {
5775        self.get_scene().start_transition(transition);
5776    }
5777
5778    /// Mounts a reactive dynamic subtree whose children rebuild cleanly inside an isolated `Scope`.
5779    ///
5780    /// # Arguments
5781    ///
5782    /// - `&Self` - Build context.
5783    /// - `NodeId` - Host container node.
5784    /// - `F` - Reactive zero-`ctx` builder returning child `NodeId` values.
5785    pub fn bind_children<F>(&mut self, host: NodeId, mut builder: F)
5786    where
5787        F: FnMut() -> Vec<NodeId> + 'static,
5788    {
5789        let ctx_clone: Self = self.clone();
5790        let handle: SceneHandle = self.get_scene().clone();
5791        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
5792            Effect::new(move || {
5793                let (child_scope, children): (Scope, Vec<NodeId>) =
5794                    Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
5795                let first_opt: Option<NodeId> = children.first().copied();
5796                handle.replace_children_safe(host, children);
5797                if let Some(first) = first_opt {
5798                    handle.mutate(move |tree: &mut SceneTree| {
5799                        tree.attach_scope(first, child_scope);
5800                    });
5801                } else {
5802                    child_scope.dispose();
5803                }
5804            })
5805        });
5806        self.get_scene().mutate(move |tree: &mut SceneTree| {
5807            tree.attach_scope(host, scope);
5808        });
5809    }
5810
5811    /// Mounts a keyed reactive child list reconciling items in O(N) by key `K` so unchanged items retain their mounted `NodeId` and `Scope`.
5812    ///
5813    /// # Arguments
5814    ///
5815    /// - `&Self` - Build context.
5816    /// - `NodeId` - Host container node.
5817    /// - `Items` - Reactive producer returning the ordered list of item data `Vec<T>`.
5818    /// - `KeyFn` - Pure key extractor mapping `&T` to a stable key `K`.
5819    /// - `RenderFn` - Item builder mounting one child `NodeId` for a newly inserted item `T`.
5820    pub fn bind_children_keyed<T, K, Items, KeyFn, RenderFn>(
5821        &mut self,
5822        host: NodeId,
5823        mut items_fn: Items,
5824        mut key_fn: KeyFn,
5825        mut render_fn: RenderFn,
5826    ) where
5827        T: 'static,
5828        K: Eq + Hash + 'static,
5829        Items: FnMut() -> Vec<T> + 'static,
5830        KeyFn: FnMut(&T) -> K + 'static,
5831        RenderFn: FnMut(T) -> NodeId + 'static,
5832    {
5833        let ctx_clone: Self = self.clone();
5834        let handle: SceneHandle = self.get_scene().clone();
5835        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
5836            let mut live_nodes: HashMap<K, NodeId> = HashMap::new();
5837            Effect::new(move || {
5838                let next_items: Vec<T> = items_fn();
5839                let mut next_map: HashMap<K, NodeId> = HashMap::with_capacity(next_items.len());
5840                let mut next_children: Vec<NodeId> = Vec::with_capacity(next_items.len());
5841                let mut new_scopes: Vec<(NodeId, Scope)> = Vec::new();
5842                for item in next_items.into_iter() {
5843                    let key: K = key_fn(&item);
5844                    if let Some(existing_id) = live_nodes.remove(&key) {
5845                        next_children.push(existing_id);
5846                        let _: Option<NodeId> = next_map.insert(key, existing_id);
5847                    } else {
5848                        let (item_scope, mounted_id): (Scope, NodeId) = Scope::run(|_: Scope| {
5849                            with_context(ctx_clone.clone(), || render_fn(item))
5850                        });
5851                        new_scopes.push((mounted_id, item_scope));
5852                        next_children.push(mounted_id);
5853                        let _: &mut NodeId = next_map.entry(key).or_insert(mounted_id);
5854                    }
5855                }
5856                live_nodes = next_map;
5857                handle.replace_children_safe(host, next_children);
5858                if !new_scopes.is_empty() {
5859                    handle.mutate(move |tree: &mut SceneTree| {
5860                        for (nid, item_scope) in new_scopes.into_iter() {
5861                            tree.attach_scope(nid, item_scope);
5862                        }
5863                    });
5864                }
5865            })
5866        });
5867        self.get_scene().mutate(move |tree: &mut SceneTree| {
5868            tree.attach_scope(host, scope);
5869        });
5870    }
5871}
5872
5873/// Restores the previously bound ambient `Context` when leaving scope.
5874impl Drop for ContextGuard {
5875    /// Restores the saved thread-local `Context`.
5876    ///
5877    /// # Arguments
5878    ///
5879    /// - `&Self` - Mutable scope guard being dropped.
5880    fn drop(&mut self) {
5881        let Self { previous } = self;
5882        let restored: Option<Context> = previous.take();
5883        ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
5884            *slot.borrow_mut() = restored;
5885        });
5886    }
5887}
5888
5889/// `NodeRefTarget` implementation storing a `NodeId` directly into a mutable local binding.
5890impl NodeRefTarget for NodeId {
5891    /// Assigns `id` to `self`.
5892    ///
5893    /// # Arguments
5894    ///
5895    /// - `&Self` - Target `NodeId` slot.
5896    /// - `NodeId` - Mounted node handle.
5897    fn bind_node_ref(&mut self, id: NodeId) {
5898        *self = id;
5899    }
5900}
5901
5902/// `NodeRefTarget` implementation storing a `NodeId` into an `Option<NodeId>`.
5903impl NodeRefTarget for Option<NodeId> {
5904    /// Assigns `Some(id)` to `self`.
5905    ///
5906    /// # Arguments
5907    ///
5908    /// - `&Self` - Target optional `NodeId` slot.
5909    /// - `NodeId` - Mounted node handle.
5910    fn bind_node_ref(&mut self, id: NodeId) {
5911        *self = Some(id);
5912    }
5913}
5914
5915/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<NodeId>`.
5916impl NodeRefTarget for Cell<NodeId> {
5917    /// Sets `self` to `id`.
5918    ///
5919    /// # Arguments
5920    ///
5921    /// - `&Self` - Target `Cell<NodeId>`.
5922    /// - `NodeId` - Mounted node handle.
5923    fn bind_node_ref(&mut self, id: NodeId) {
5924        self.set(id);
5925    }
5926}
5927
5928/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<NodeId>>`.
5929impl NodeRefTarget for Rc<Cell<NodeId>> {
5930    /// Sets the shared cell value to `id`.
5931    ///
5932    /// # Arguments
5933    ///
5934    /// - `&Self` - Target shared `Cell<NodeId>`.
5935    /// - `NodeId` - Mounted node handle.
5936    fn bind_node_ref(&mut self, id: NodeId) {
5937        self.set(id);
5938    }
5939}
5940
5941/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<Option<NodeId>>`.
5942impl NodeRefTarget for Cell<Option<NodeId>> {
5943    /// Sets `self` to `Some(id)`.
5944    ///
5945    /// # Arguments
5946    ///
5947    /// - `&Self` - Target `Cell<Option<NodeId>>`.
5948    /// - `NodeId` - Mounted node handle.
5949    fn bind_node_ref(&mut self, id: NodeId) {
5950        self.set(Some(id));
5951    }
5952}
5953
5954/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<Option<NodeId>>>`.
5955impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
5956    /// Sets the shared cell value to `Some(id)`.
5957    ///
5958    /// # Arguments
5959    ///
5960    /// - `&Self` - Target shared `Cell<Option<NodeId>>`.
5961    /// - `NodeId` - Mounted node handle.
5962    fn bind_node_ref(&mut self, id: NodeId) {
5963        self.set(Some(id));
5964    }
5965}
5966
5967/// `TextNodeContent` implementation mounting an owned `String` as a static text node.
5968impl TextNodeContent for String {
5969    /// Mounts a static text scene node from this `String`.
5970    ///
5971    /// # Arguments
5972    ///
5973    /// - `Self` - Owned text string.
5974    /// - `&mut Context` - Active scene build context.
5975    /// - `Style` - Resolved text style.
5976    ///
5977    /// # Returns
5978    ///
5979    /// - `NodeId` - Mounted text node handle.
5980    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
5981        ctx.text(self, style)
5982    }
5983
5984    /// Mounts a static text scene node from this `String` using the ambient `Context` without cloning it.
5985    ///
5986    /// # Arguments
5987    ///
5988    /// - `Self` - Owned text string.
5989    /// - `Style` - Resolved text style.
5990    ///
5991    /// # Returns
5992    ///
5993    /// - `NodeId` - Mounted text node handle.
5994    fn mount_text_current(self, style: Style) -> NodeId {
5995        with_current_context(|ctx: &Context| {
5996            ctx.get_scene().with_write(
5997                |tree: &mut SceneTree| tree.create_text(self, style),
5998                NodeId::default(),
5999            )
6000        })
6001    }
6002}
6003
6004/// `TextNodeContent` implementation mounting a string slice as a static text node.
6005impl TextNodeContent for &str {
6006    /// Mounts a static text scene node from this `&str`.
6007    ///
6008    /// # Arguments
6009    ///
6010    /// - `Self` - Borrowed text slice.
6011    /// - `&mut Context` - Active scene build context.
6012    /// - `Style` - Resolved text style.
6013    ///
6014    /// # Returns
6015    ///
6016    /// - `NodeId` - Mounted text node handle.
6017    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6018        ctx.text(self.to_string(), style)
6019    }
6020
6021    /// Mounts a static text scene node from this `&str` using the ambient `Context` without cloning it.
6022    ///
6023    /// # Arguments
6024    ///
6025    /// - `Self` - Borrowed text slice.
6026    /// - `Style` - Resolved text style.
6027    ///
6028    /// # Returns
6029    ///
6030    /// - `NodeId` - Mounted text node handle.
6031    fn mount_text_current(self, style: Style) -> NodeId {
6032        let owned: String = self.to_string();
6033        with_current_context(|ctx: &Context| {
6034            ctx.get_scene().with_write(
6035                |tree: &mut SceneTree| tree.create_text(owned, style),
6036                NodeId::default(),
6037            )
6038        })
6039    }
6040}
6041
6042/// `TextNodeContent` implementation mounting a borrowed `&String` as a static text node.
6043impl TextNodeContent for &String {
6044    /// Mounts a static text scene node from this `&String`.
6045    ///
6046    /// # Arguments
6047    ///
6048    /// - `Self` - Borrowed string reference.
6049    /// - `&mut Context` - Active scene build context.
6050    /// - `Style` - Resolved text style.
6051    ///
6052    /// # Returns
6053    ///
6054    /// - `NodeId` - Mounted text node handle.
6055    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6056        ctx.text(self.clone(), style)
6057    }
6058
6059    /// Mounts a static text scene node from this `&String` using the ambient `Context` without cloning it.
6060    ///
6061    /// # Arguments
6062    ///
6063    /// - `Self` - Borrowed string reference.
6064    /// - `Style` - Resolved text style.
6065    ///
6066    /// # Returns
6067    ///
6068    /// - `NodeId` - Mounted text node handle.
6069    fn mount_text_current(self, style: Style) -> NodeId {
6070        let owned: String = self.clone();
6071        with_current_context(|ctx: &Context| {
6072            ctx.get_scene().with_write(
6073                |tree: &mut SceneTree| tree.create_text(owned, style),
6074                NodeId::default(),
6075            )
6076        })
6077    }
6078}
6079
6080/// `TextNodeContent` implementation mounting a `Cow<str>` as a static text node.
6081impl TextNodeContent for Cow<'_, str> {
6082    /// Mounts a static text scene node from this `Cow<str>`.
6083    ///
6084    /// # Arguments
6085    ///
6086    /// - `Self` - Copy-on-write string value.
6087    /// - `&mut Context` - Active scene build context.
6088    /// - `Style` - Resolved text style.
6089    ///
6090    /// # Returns
6091    ///
6092    /// - `NodeId` - Mounted text node handle.
6093    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6094        ctx.text(self.into_owned(), style)
6095    }
6096
6097    /// Mounts a static text scene node from this `Cow<str>` using the ambient `Context` without cloning it.
6098    ///
6099    /// # Arguments
6100    ///
6101    /// - `Self` - Copy-on-write string value.
6102    /// - `Style` - Resolved text style.
6103    ///
6104    /// # Returns
6105    ///
6106    /// - `NodeId` - Mounted text node handle.
6107    fn mount_text_current(self, style: Style) -> NodeId {
6108        let owned: String = self.into_owned();
6109        with_current_context(|ctx: &Context| {
6110            ctx.get_scene().with_write(
6111                |tree: &mut SceneTree| tree.create_text(owned, style),
6112                NodeId::default(),
6113            )
6114        })
6115    }
6116}
6117
6118/// `TextNodeContent` implementation mounting any `FnMut() -> S` closure or function item as a reactive text node.
6119impl<F, S> TextNodeContent for F
6120where
6121    F: FnMut() -> S + 'static,
6122    S: Into<String>,
6123{
6124    /// Mounts a reactive text scene node bound to this closure or function item.
6125    ///
6126    /// # Arguments
6127    ///
6128    /// - `Self` - Reactive text producer closure.
6129    /// - `&mut Context` - Active scene build context.
6130    /// - `Style` - Resolved text style.
6131    ///
6132    /// # Returns
6133    ///
6134    /// - `NodeId` - Mounted reactive text node handle.
6135    fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
6136        ctx.reactive_text(style, move || self().into())
6137    }
6138
6139    /// Mounts a reactive text scene node bound to this closure or function item using the ambient `Context` without cloning it.
6140    ///
6141    /// # Arguments
6142    ///
6143    /// - `Self` - Reactive text producer closure.
6144    /// - `Style` - Resolved text style.
6145    ///
6146    /// # Returns
6147    ///
6148    /// - `NodeId` - Mounted reactive text node handle.
6149    fn mount_text_current(mut self, style: Style) -> NodeId {
6150        mount_reactive_text(style, move || self().into())
6151    }
6152}