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