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        if let Some(sel) = self.extract_selected_text_filtered(None) {
3981            return Some(sel);
3982        }
3983        let focused: NodeId = self.get_focus().focused_node()?;
3984        let node: &SceneNode = self.get_node(focused)?;
3985        if let NodeKind::Input(state) = node.get_kind() {
3986            return state.selected_text().map(str::to_string);
3987        }
3988        None
3989    }
3990
3991    /// Returns the currently selected UTF-8 substring only when the active selection lies inside `container`'s subtree.
3992    ///
3993    /// # Arguments
3994    ///
3995    /// - `&Self` - Scene tree reference.
3996    /// - `NodeId` - Container root node handle.
3997    ///
3998    /// # Returns
3999    ///
4000    /// - `Option<String>` - Selected text within `container`, or `None`.
4001    #[must_use]
4002    pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
4003        self.extract_selected_text_filtered(Some(container))
4004    }
4005
4006    /// Selects all selectable text across `id`'s active selectable container scope (excluding `TextSelectMode::None` descendants).
4007    ///
4008    /// # Arguments
4009    ///
4010    /// - `&Self` - Mutable scene tree.
4011    /// - `NodeId` - Target text or selectable container node handle.
4012    ///
4013    /// # Returns
4014    ///
4015    /// - `bool` - `true` when at least one non-empty selectable text node was selected.
4016    pub fn select_all_text(&mut self, id: NodeId) -> bool {
4017        if !self.is_node_selectable(id) {
4018            return false;
4019        }
4020        let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
4021        let Some(&first_id) = nodes.first() else {
4022            return false;
4023        };
4024        let Some(&last_id) = nodes.last() else {
4025            return false;
4026        };
4027        let last_len: usize = self
4028            .get_node(last_id)
4029            .and_then(|node: &SceneNode| {
4030                if let NodeKind::Text(content) = node.get_kind() {
4031                    Some(content.chars().count())
4032                } else {
4033                    None
4034                }
4035            })
4036            .unwrap_or(0);
4037        if nodes.len() == 1 && last_len == 0 {
4038            return false;
4039        }
4040        self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
4041        true
4042    }
4043
4044    /// Selects the full visual row containing selectable text node `id` (used for triple-click across multi-span lines).
4045    ///
4046    /// # Arguments
4047    ///
4048    /// - `&Self` - Mutable scene tree.
4049    /// - `NodeId` - Clicked selectable text node handle.
4050    ///
4051    /// # Returns
4052    ///
4053    /// - `bool` - `true` when a non-empty visual line selection was applied.
4054    pub(crate) fn select_line_text(&mut self, id: NodeId) -> bool {
4055        if !self.is_node_selectable(id) {
4056            return false;
4057        }
4058        let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(id);
4059        let Some(pos) = nodes.iter().position(|n: &NodeId| *n == id) else {
4060            return false;
4061        };
4062        let mut start_idx: usize = pos;
4063        while start_idx > 0 && !self.is_new_visual_row(nodes[start_idx - 1], id) {
4064            start_idx -= 1;
4065        }
4066        let mut end_idx: usize = pos;
4067        while end_idx + 1 < nodes.len() && !self.is_new_visual_row(id, nodes[end_idx + 1]) {
4068            end_idx += 1;
4069        }
4070        let first_id: NodeId = nodes[start_idx];
4071        let last_id: NodeId = nodes[end_idx];
4072        let last_len: usize = self
4073            .get_node(last_id)
4074            .and_then(|node: &SceneNode| {
4075                if let NodeKind::Text(content) = node.get_kind() {
4076                    Some(content.chars().count())
4077                } else {
4078                    None
4079                }
4080            })
4081            .unwrap_or(0);
4082        if first_id == last_id && last_len == 0 {
4083            return false;
4084        }
4085        self.set_text_selection(Some(SelectionState::new(first_id, 0, last_id, last_len)));
4086        true
4087    }
4088
4089    /// Hit-tests `pos` across all selectable `NodeKind::Text` nodes in `anchor_or_hit`'s scope, resolving exact or nearest visual row and character index.
4090    ///
4091    /// # Arguments
4092    ///
4093    /// - `&Self` - Scene tree reference.
4094    /// - `NodeId` - Anchor text node or selectable container node.
4095    /// - `Point` - Screen-space logical pointer coordinates.
4096    ///
4097    /// # Returns
4098    ///
4099    /// - `Option<(NodeId, usize)>` - Resolved `(node_id, char_index)` within the selectable scope.
4100    #[must_use]
4101    pub(crate) fn hit_test_selectable_scope(
4102        &self,
4103        anchor_or_hit: NodeId,
4104        pos: Point,
4105    ) -> Option<(NodeId, usize)> {
4106        let nodes: Vec<NodeId> = self.selectable_scope_text_nodes(anchor_or_hit);
4107        if nodes.is_empty() {
4108            return None;
4109        }
4110        let mut rects: Vec<(NodeId, Rect, TextStyle, usize)> = Vec::with_capacity(nodes.len());
4111        let mut overall_min_y: f32 = f32::INFINITY;
4112        let mut overall_max_y: f32 = f32::NEG_INFINITY;
4113        for &nid in nodes.iter() {
4114            let Some(node) = self.get_node(nid) else {
4115                continue;
4116            };
4117            let NodeKind::Text(content) = node.get_kind() else {
4118                continue;
4119            };
4120            let Some(rect) = self.text_node_screen_content_rect(nid) else {
4121                continue;
4122            };
4123            let tstyle: TextStyle = node.get_style().get_text();
4124            if pos.get_x() >= rect.get_x()
4125                && pos.get_x() <= rect.right()
4126                && pos.get_y() >= rect.get_y()
4127                && pos.get_y() <= rect.bottom()
4128            {
4129                let ch: usize = hit_test_text_char(content.as_str(), tstyle, rect, pos);
4130                return Some((nid, ch));
4131            }
4132            if rect.get_y() < overall_min_y {
4133                overall_min_y = rect.get_y();
4134            }
4135            if rect.bottom() > overall_max_y {
4136                overall_max_y = rect.bottom();
4137            }
4138            rects.push((nid, rect, tstyle, content.chars().count()));
4139        }
4140        if rects.is_empty() {
4141            return None;
4142        }
4143        if pos.get_y() < overall_min_y - 4.0 {
4144            return Some((rects[0].0, 0));
4145        }
4146        if pos.get_y() > overall_max_y + 4.0 {
4147            let last: (NodeId, Rect, TextStyle, usize) = rects[rects.len() - 1];
4148            return Some((last.0, last.3));
4149        }
4150        let mut min_dy: f32 = f32::INFINITY;
4151        for &(_, rect, _, _) in rects.iter() {
4152            let dy: f32 = if pos.get_y() < rect.get_y() {
4153                rect.get_y() - pos.get_y()
4154            } else if pos.get_y() > rect.bottom() {
4155                pos.get_y() - rect.bottom()
4156            } else {
4157                0.0
4158            };
4159            if dy < min_dy {
4160                min_dy = dy;
4161            }
4162        }
4163        let mut best: Option<(NodeId, Rect, TextStyle, f32, f32)> = None;
4164        for &(nid, rect, tstyle, _) in rects.iter() {
4165            let dy: f32 = if pos.get_y() < rect.get_y() {
4166                rect.get_y() - pos.get_y()
4167            } else if pos.get_y() > rect.bottom() {
4168                pos.get_y() - rect.bottom()
4169            } else {
4170                0.0
4171            };
4172            if dy > min_dy + 2.0 {
4173                continue;
4174            }
4175            let dx: f32 = if pos.get_x() < rect.get_x() {
4176                rect.get_x() - pos.get_x()
4177            } else if pos.get_x() > rect.right() {
4178                pos.get_x() - rect.right()
4179            } else {
4180                0.0
4181            };
4182            let better: bool = match best {
4183                None => true,
4184                Some((_, _, _, b_dx, b_dy)) => dx < b_dx || (dx == b_dx && dy < b_dy),
4185            };
4186            if better {
4187                best = Some((nid, rect, tstyle, dx, dy));
4188            }
4189        }
4190        let (best_nid, best_rect, best_style, _, _): (NodeId, Rect, TextStyle, f32, f32) = best?;
4191        let best_node: &SceneNode = self.get_node(best_nid)?;
4192        let NodeKind::Text(content) = best_node.get_kind() else {
4193            return None;
4194        };
4195        let min_y: f32 = best_rect.get_y() + 0.5;
4196        let max_y: f32 = (best_rect.bottom() - 0.5).max(min_y);
4197        let clamped_y: f32 = pos.get_y().clamp(min_y, max_y);
4198        let ch: usize = hit_test_text_char(
4199            content.as_str(),
4200            best_style,
4201            best_rect,
4202            Point::new(pos.get_x(), clamped_y),
4203        );
4204        Some((best_nid, ch))
4205    }
4206}
4207
4208/// RAII depth-tracking methods for `SceneBorrowGuard`.
4209impl SceneBorrowGuard {
4210    /// Increments the thread-local `SceneTree` borrow depth and returns a guard that decrements it on drop.
4211    ///
4212    /// # Returns
4213    ///
4214    /// - `Self` - Active borrow depth guard.
4215    #[inline(always)]
4216    pub(crate) fn enter() -> Self {
4217        let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4218            depth.set(depth.get().saturating_add(1));
4219        });
4220        Self
4221    }
4222}
4223
4224/// Decrements the thread-local `SceneTree` borrow depth on scope exit.
4225impl Drop for SceneBorrowGuard {
4226    /// Decrements the active thread-local `SceneTree` borrow counter.
4227    ///
4228    /// # Arguments
4229    ///
4230    /// - `&Self` - Mutable guard being dropped.
4231    #[inline(always)]
4232    fn drop(&mut self) {
4233        let _: Result<(), _> = SCENE_BORROW_DEPTH.try_with(|depth: &Cell<u32>| {
4234            depth.set(depth.get().saturating_sub(1));
4235        });
4236    }
4237}
4238
4239/// Shared scene handle operations enabling surgical reactive node updates.
4240impl SceneHandle {
4241    /// Creates a new `SceneHandle` wrapping a fresh `SceneTree`.
4242    ///
4243    /// # Returns
4244    ///
4245    /// - `Self` - Shared scene handle.
4246    #[must_use]
4247    pub fn new_tree() -> Self {
4248        Self {
4249            inner: Rc::new(SceneHandleInner {
4250                tree: RefCell::new(SceneTree::default()),
4251                has_deferred: Cell::new(false),
4252                deferred_writes: RefCell::new(Vec::new()),
4253            }),
4254        }
4255    }
4256
4257    /// Returns `true` when re-entrant scene mutations are queued awaiting flush.
4258    ///
4259    /// # Arguments
4260    ///
4261    /// - `&Self` - Scene handle reference.
4262    ///
4263    /// # Returns
4264    ///
4265    /// - `bool` - Whether deferred scene mutations are pending.
4266    #[must_use]
4267    #[inline(always)]
4268    pub fn has_deferred_writes(&self) -> bool {
4269        let Self { inner } = self;
4270        inner.has_deferred.get()
4271    }
4272
4273    /// Executes all queued re-entrant scene mutations under an already-held mutable `SceneTree` borrow.
4274    ///
4275    /// # Arguments
4276    ///
4277    /// - `&SceneHandleInner` - Shared scene storage holding the deferred queue.
4278    /// - `&mut SceneTree` - Active mutable scene tree borrow.
4279    ///
4280    /// # Returns
4281    ///
4282    /// - `usize` - Number of deferred mutations executed.
4283    fn drain_deferred_locked(inner: &SceneHandleInner, tree: &mut SceneTree) -> usize {
4284        let mut executed: usize = 0;
4285        for _ in 0..MAX_FLUSH_ITERATIONS {
4286            let batch: Vec<DeferredSceneWrite> = match inner.deferred_writes.try_borrow_mut() {
4287                Ok(mut queue) => {
4288                    inner.has_deferred.set(false);
4289                    if queue.is_empty() {
4290                        break;
4291                    }
4292                    take(&mut *queue)
4293                }
4294                Err(_) => break,
4295            };
4296            for op in batch.into_iter() {
4297                op(tree);
4298                executed = executed.saturating_add(1);
4299            }
4300            if !inner.has_deferred.get() {
4301                break;
4302            }
4303        }
4304        executed
4305    }
4306
4307    /// Executes any pending re-entrant scene mutations queued while `SceneTree` was borrowed.
4308    ///
4309    /// # Arguments
4310    ///
4311    /// - `&Self` - Scene handle reference.
4312    ///
4313    /// # Returns
4314    ///
4315    /// - `usize` - Number of deferred mutations executed (`0` if queue is empty or tree is still borrowed).
4316    pub fn flush_deferred_writes(&self) -> usize {
4317        let Self { inner } = self;
4318        if !inner.has_deferred.get() {
4319            return 0;
4320        }
4321        let executed: usize = match inner.tree.try_borrow_mut() {
4322            Ok(mut guard) => {
4323                let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4324                Self::drain_deferred_locked(inner, &mut guard)
4325            }
4326            Err(_) => return 0,
4327        };
4328        if !is_scene_borrowed() && !panicking() && has_deferred_effect_flush() {
4329            self.flush_after_outer_borrow();
4330        }
4331        executed
4332    }
4333
4334    /// Checks whether deferred writes or deferred reactive effects need flushing after an outer borrow drops.
4335    ///
4336    /// # Arguments
4337    ///
4338    /// - `&Self` - Scene handle reference.
4339    #[inline(always)]
4340    fn finish_outer_borrow(&self) {
4341        if is_scene_borrowed() || panicking() {
4342            return;
4343        }
4344        let Self { inner } = self;
4345        if !inner.has_deferred.get() && !has_deferred_effect_flush() {
4346            return;
4347        }
4348        self.flush_after_outer_borrow();
4349    }
4350
4351    /// Drains interleaved deferred scene writes and deferred reactive effect flushes once no `SceneTree` borrow is active.
4352    ///
4353    /// # Arguments
4354    ///
4355    /// - `&Self` - Scene handle reference.
4356    #[cold]
4357    fn flush_after_outer_borrow(&self) {
4358        let Self { inner } = self;
4359        for _ in 0..MAX_FLUSH_ITERATIONS {
4360            let drained_writes: usize = if inner.has_deferred.get() {
4361                match inner.tree.try_borrow_mut() {
4362                    Ok(mut guard) => {
4363                        let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4364                        Self::drain_deferred_locked(inner, &mut guard)
4365                    }
4366                    Err(_) => 0,
4367                }
4368            } else {
4369                0
4370            };
4371            let flushed_effects: bool = if take_deferred_effect_flush() {
4372                flush_effects();
4373                true
4374            } else {
4375                false
4376            };
4377            if drained_writes == 0 && !flushed_effects && !inner.has_deferred.get() {
4378                break;
4379            }
4380        }
4381    }
4382
4383    /// Mutates the underlying `SceneTree` immediately when unborrowed (zero allocations) or queues `operation` re-entrantly until the outer borrow unwinds.
4384    ///
4385    /// # Arguments
4386    ///
4387    /// - `&Self` - Scene handle reference.
4388    /// - `F` - Guaranteed-delivery scene mutation closure.
4389    pub fn mutate<F>(&self, operation: F)
4390    where
4391        F: FnOnce(&mut SceneTree) + 'static,
4392    {
4393        let ran_inline: bool = {
4394            let Self { inner } = self;
4395            match inner.tree.try_borrow_mut() {
4396                Ok(mut guard) => {
4397                    let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4398                    operation(&mut guard);
4399                    if inner.has_deferred.get() {
4400                        let _: usize = Self::drain_deferred_locked(inner, &mut guard);
4401                    }
4402                    true
4403                }
4404                Err(_) => {
4405                    if let Ok(mut queue) = inner.deferred_writes.try_borrow_mut() {
4406                        queue.push(Box::new(operation));
4407                        inner.has_deferred.set(true);
4408                    }
4409                    notify_frame_needed();
4410                    false
4411                }
4412            }
4413        };
4414        if ran_inline {
4415            self.finish_outer_borrow();
4416        }
4417    }
4418
4419    /// Updates virtualized scroll metrics `(scroll_y, content_height)` on `id` for accurate scrollbar thumbs.
4420    ///
4421    /// # Arguments
4422    ///
4423    /// - `&Self` - Scene handle reference.
4424    /// - `NodeId` - Target virtualized scroll container.
4425    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
4426    /// - `f32` - Total virtualized content height in logical pixels.
4427    pub fn set_virtual_scroll(&self, id: NodeId, scroll_y: f32, content_height: f32) {
4428        self.mutate(move |tree: &mut SceneTree| {
4429            tree.set_virtual_scroll(id, scroll_y, content_height);
4430        });
4431    }
4432
4433    /// Computes screen-space logical bounds for `id` subtracting ancestor scroll offsets.
4434    ///
4435    /// # Arguments
4436    ///
4437    /// - `&Self` - Scene handle reference.
4438    /// - `NodeId` - Target node handle.
4439    ///
4440    /// # Returns
4441    ///
4442    /// - `Option<Rect>` - Screen-space bounds if the node is alive.
4443    #[must_use]
4444    pub fn node_screen_bounds(&self, id: NodeId) -> Option<Rect> {
4445        self.with_read(|tree: &SceneTree| tree.node_screen_bounds(id), None)
4446    }
4447
4448    /// Starts or replaces a smooth paint/transform transition on the target node.
4449    ///
4450    /// # Arguments
4451    ///
4452    /// - `&Self` - Scene handle reference.
4453    /// - `NodeTransition` - Transition specification to run.
4454    pub fn start_transition(&self, transition: NodeTransition) {
4455        self.mutate(move |tree: &mut SceneTree| {
4456            tree.start_transition(transition);
4457        });
4458    }
4459
4460    /// Marks `id` dirty with `mask` for incremental repainting.
4461    ///
4462    /// # Arguments
4463    ///
4464    /// - `&Self` - Scene handle reference.
4465    /// - `NodeId` - Target node handle.
4466    /// - `u16` - Dirty flag bits.
4467    pub fn mark_dirty(&self, id: NodeId, mask: u16) {
4468        self.mutate(move |tree: &mut SceneTree| {
4469            tree.mark_dirty(id, mask);
4470        });
4471    }
4472
4473    /// Replaces all children of `parent` and finalizes disposed scopes and `Lifecycle` hooks outside the tree borrow.
4474    ///
4475    /// # Arguments
4476    ///
4477    /// - `&Self` - Scene handle reference.
4478    /// - `NodeId` - Parent container node.
4479    /// - `Vec<NodeId>` - Replacement ordered children.
4480    pub fn replace_children_safe(&self, parent: NodeId, new_children: Vec<NodeId>) {
4481        let (scopes, observers): DisposedSubtreePayload = self.with_write(
4482            |tree: &mut SceneTree| {
4483                if tree.get_node(parent).is_none() {
4484                    return (Vec::new(), Vec::new());
4485                }
4486                let parent_idx: usize = parent.as_usize();
4487                let old_children: Vec<NodeId> = tree.children_vec(parent);
4488                tree.unlink_all_children_at(parent_idx);
4489                let mut all_scopes: Vec<Scope> = Vec::new();
4490                let mut all_obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = Vec::new();
4491                if new_children.is_empty() {
4492                    for old_child in old_children.into_iter() {
4493                        let (sc, ob): DisposedSubtreePayload =
4494                            tree.dispose_subtree_collect(old_child);
4495                        all_scopes.extend(sc);
4496                        all_obs.extend(ob);
4497                    }
4498                } else if old_children.len() > 16 && new_children.len() > 16 {
4499                    let keep_set: HashSet<NodeId> = new_children.iter().copied().collect();
4500                    for old_child in old_children.into_iter() {
4501                        if !keep_set.contains(&old_child) {
4502                            let (sc, ob): DisposedSubtreePayload =
4503                                tree.dispose_subtree_collect(old_child);
4504                            all_scopes.extend(sc);
4505                            all_obs.extend(ob);
4506                        }
4507                    }
4508                } else {
4509                    for old_child in old_children.into_iter() {
4510                        if !new_children.contains(&old_child) {
4511                            let (sc, ob): DisposedSubtreePayload =
4512                                tree.dispose_subtree_collect(old_child);
4513                            all_scopes.extend(sc);
4514                            all_obs.extend(ob);
4515                        }
4516                    }
4517                }
4518                for child in new_children.into_iter() {
4519                    if child == parent || tree.get_node(child).is_none() {
4520                        continue;
4521                    }
4522                    let child_idx: usize = child.as_usize();
4523                    let prev_parent: u32 = tree.get_topology()[child_idx].get_parent();
4524                    if prev_parent != NODE_INDEX_NONE {
4525                        tree.unlink_child_at(prev_parent as usize, child_idx);
4526                    }
4527                    tree.link_child_tail_at(parent_idx, parent, child_idx);
4528                }
4529                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4530                (all_scopes, all_obs)
4531            },
4532            (Vec::new(), Vec::new()),
4533        );
4534        finalize_disposed_subtree(scopes, observers);
4535    }
4536
4537    /// Removes `child` from `parent`, disposes its subtree, and invokes `on_unmount`/`on_destroy` outside any scene borrow.
4538    ///
4539    /// # Arguments
4540    ///
4541    /// - `&Self` - Scene handle reference.
4542    /// - `NodeId` - Parent container handle.
4543    /// - `NodeId` - Child subtree root handle to remove and destroy.
4544    pub fn remove_and_dispose_child(&self, parent: NodeId, child: NodeId) {
4545        let (scopes, observers): DisposedSubtreePayload = self.with_write(
4546            |tree: &mut SceneTree| {
4547                if tree.get_node(parent).is_some() && tree.get_node(child).is_some() {
4548                    tree.unlink_child_at(parent.as_usize(), child.as_usize());
4549                }
4550                let out: DisposedSubtreePayload = tree.dispose_subtree_collect(child);
4551                tree.mark_dirty(parent, DIRTY_CHILDREN_CHANGE_MASK);
4552                out
4553            },
4554            (Vec::new(), Vec::new()),
4555        );
4556        finalize_disposed_subtree(scopes, observers);
4557    }
4558
4559    /// Mutates a node's `Style` in place under one write lock, marking only minimal dirty flags when changed.
4560    ///
4561    /// # Arguments
4562    ///
4563    /// - `&Self` - Scene handle reference.
4564    /// - `NodeId` - Target node handle.
4565    /// - `F` - In-place style mutator closure receiving `&mut Style`.
4566    ///
4567    /// # Returns
4568    ///
4569    /// - `bool` - `true` when the node existed and its style changed.
4570    pub fn mutate_style<F>(&self, id: NodeId, mutator: F) -> bool
4571    where
4572        F: FnOnce(&mut Style),
4573    {
4574        self.with_write(|tree: &mut SceneTree| tree.mutate_style(id, mutator), false)
4575    }
4576
4577    /// Freezes a subtree visually (`Display::None`), cancels its transitions, and dispatches `Lifecycle::on_freeze` outside any scene borrow.
4578    ///
4579    /// # Arguments
4580    ///
4581    /// - `&Self` - Scene handle reference.
4582    /// - `NodeId` - Subtree root handle to freeze.
4583    pub fn freeze_subtree(&self, root: NodeId) {
4584        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4585            |tree: &mut SceneTree| {
4586                let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4587                tree.cancel_subtree_transitions(root);
4588                let changed: bool = if let Some(node) = tree.get_node_mut(root) {
4589                    let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4590                    if layout.get_display() == Display::None {
4591                        false
4592                    } else {
4593                        layout.set_display(Display::None);
4594                        true
4595                    }
4596                } else {
4597                    false
4598                };
4599                if changed {
4600                    tree.clear_subtree_hover(root);
4601                    tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4602                }
4603                obs
4604            },
4605            Vec::new(),
4606        );
4607        dispatch_lifecycle_freeze(&observers);
4608    }
4609
4610    /// Freezes a subtree immediately for lifecycle/effects while animating its visual exit to `Display::None`.
4611    ///
4612    /// # Arguments
4613    ///
4614    /// - `&Self` - Scene handle reference.
4615    /// - `NodeId` - Subtree root handle to freeze and animate out.
4616    /// - `NodeTransition` - Exit transition specification (`hide_on_complete` is enforced).
4617    pub fn freeze_subtree_animated(&self, root: NodeId, exit_transition: NodeTransition) {
4618        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4619            |tree: &mut SceneTree| {
4620                let obs: Vec<(NodeId, Rc<dyn Lifecycle>)> = tree.collect_subtree_lifecycles(root);
4621                tree.cancel_subtree_transitions(root);
4622                let mut demoted_fixed: bool = false;
4623                let mut prev_z: i32 = 0;
4624                if let Some(node) = tree.get_node_mut(root) {
4625                    let is_portal: bool = matches!(node.get_kind(), NodeKind::Portal);
4626                    let st: &mut Style = node.get_mut_style();
4627                    prev_z = st.layout_ref().get_z_index();
4628                    demoted_fixed = !is_portal && st.layout_ref().get_position() == Position::Fixed;
4629                    st.get_mut_layout()
4630                        .set_position(Position::Absolute)
4631                        .set_top(Some(0.0))
4632                        .set_right(Some(0.0))
4633                        .set_bottom(None)
4634                        .set_left(Some(0.0))
4635                        .set_z_index(0);
4636                    st.get_mut_paint().set_pointer_events(PointerEvents::None);
4637                }
4638                if prev_z != 0 {
4639                    let parent_idx: u32 = tree.get_topology()[root.as_usize()].get_parent();
4640                    if parent_idx != NODE_INDEX_NONE {
4641                        tree.sync_parent_nonzero_z(parent_idx as usize, prev_z, 0);
4642                    }
4643                }
4644                tree.clear_subtree_hover(root);
4645                if demoted_fixed {
4646                    tree.sync_portal_registration(root, false);
4647                }
4648                tree.start_transition(exit_transition.with_hide_on_complete(true));
4649                tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4650                obs
4651            },
4652            Vec::new(),
4653        );
4654        dispatch_lifecycle_freeze(&observers);
4655    }
4656
4657    /// Resumes a previously frozen subtree (`Display::Flex`) and dispatches `Lifecycle::on_resume` outside any scene borrow.
4658    ///
4659    /// # Arguments
4660    ///
4661    /// - `&Self` - Scene handle reference.
4662    /// - `NodeId` - Subtree root handle to resume.
4663    pub fn resume_subtree(&self, root: NodeId) {
4664        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_write(
4665            |tree: &mut SceneTree| {
4666                let mut unhidden: bool = false;
4667                if let Some(node) = tree.get_node_mut(root) {
4668                    let layout: &mut LayoutStyle = node.get_mut_style().get_mut_layout();
4669                    if layout.get_display() == Display::None {
4670                        layout.set_display(Display::Flex);
4671                        unhidden = true;
4672                    }
4673                }
4674                if unhidden {
4675                    tree.mark_dirty(root, DIRTY_LAYOUT | DIRTY_PAINT);
4676                } else {
4677                    tree.mark_dirty(root, DIRTY_PAINT);
4678                }
4679                tree.collect_subtree_lifecycles(root)
4680            },
4681            Vec::new(),
4682        );
4683        dispatch_lifecycle_resume(&observers);
4684    }
4685
4686    /// Dispatches `Lifecycle::on_activate` across all observers in the subtree rooted at `root`.
4687    ///
4688    /// # Arguments
4689    ///
4690    /// - `&Self` - Scene handle reference.
4691    /// - `NodeId` - Subtree root handle becoming active.
4692    pub fn activate_subtree(&self, root: NodeId) {
4693        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
4694            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
4695            Vec::new(),
4696        );
4697        dispatch_lifecycle_activate(&observers);
4698    }
4699
4700    /// Dispatches `Lifecycle::on_update` across all observers in the subtree rooted at `root`.
4701    ///
4702    /// # Arguments
4703    ///
4704    /// - `&Self` - Scene handle reference.
4705    /// - `NodeId` - Subtree root handle receiving updates.
4706    pub fn update_subtree(&self, root: NodeId) {
4707        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self.with_read(
4708            |tree: &SceneTree| tree.collect_subtree_lifecycles(root),
4709            Vec::new(),
4710        );
4711        dispatch_lifecycle_update(&observers);
4712    }
4713
4714    /// Dispatches `SystemEvent::Appear` to all `Lifecycle` observers and scoped hooks owned by `root`'s subtree.
4715    ///
4716    /// # Arguments
4717    ///
4718    /// - `&Self` - Scene handle reference.
4719    /// - `NodeId` - Page or component subtree root handle becoming visible.
4720    pub fn emit_subtree_appear(&self, root: NodeId) {
4721        let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
4722            |tree: &SceneTree| {
4723                (
4724                    tree.collect_subtree_lifecycles(root),
4725                    tree.collect_subtree_scope_ids(root),
4726                )
4727            },
4728            (Vec::new(), Vec::new()),
4729        );
4730        let ev: SystemEvent = SystemEvent::Appear;
4731        dispatch_lifecycle_system_event(&observers, &ev);
4732        dispatch_system_event_to_scopes(&scopes, &ev);
4733    }
4734
4735    /// Dispatches `SystemEvent::Disappear` to all `Lifecycle` observers and scoped hooks owned by `root`'s subtree.
4736    ///
4737    /// # Arguments
4738    ///
4739    /// - `&Self` - Scene handle reference.
4740    /// - `NodeId` - Page or component subtree root handle ceasing to be visible.
4741    pub fn emit_subtree_disappear(&self, root: NodeId) {
4742        let (observers, scopes): SubtreeLifecycleTargets = self.with_read(
4743            |tree: &SceneTree| {
4744                (
4745                    tree.collect_subtree_lifecycles(root),
4746                    tree.collect_subtree_scope_ids(root),
4747                )
4748            },
4749            (Vec::new(), Vec::new()),
4750        );
4751        let ev: SystemEvent = SystemEvent::Disappear;
4752        dispatch_lifecycle_system_event(&observers, &ev);
4753        dispatch_system_event_to_scopes(&scopes, &ev);
4754    }
4755
4756    /// Returns `true` if any node transition is currently active.
4757    ///
4758    /// # Arguments
4759    ///
4760    /// - `&Self` - Scene handle reference.
4761    ///
4762    /// # Returns
4763    ///
4764    /// - `bool` - Whether animations are running.
4765    #[must_use]
4766    pub fn has_active_transitions(&self) -> bool {
4767        self.with_read(SceneTree::has_active_transitions, false)
4768    }
4769
4770    /// Returns the currently selected text substring across the retained scene, if any.
4771    ///
4772    /// # Arguments
4773    ///
4774    /// - `&Self` - Scene handle reference.
4775    ///
4776    /// # Returns
4777    ///
4778    /// - `Option<String>` - Active selected UTF-8 text.
4779    #[must_use]
4780    pub fn get_selected_text(&self) -> Option<String> {
4781        self.with_read(SceneTree::get_selected_text, None)
4782    }
4783
4784    /// Returns the currently selected UTF-8 text when the active selection lies inside `container`'s subtree.
4785    ///
4786    /// # Arguments
4787    ///
4788    /// - `&Self` - Scene handle reference.
4789    /// - `NodeId` - Container root node handle.
4790    ///
4791    /// # Returns
4792    ///
4793    /// - `Option<String>` - Active selected UTF-8 text inside `container`.
4794    #[must_use]
4795    pub fn get_selected_text_within(&self, container: NodeId) -> Option<String> {
4796        self.with_read(
4797            |tree: &SceneTree| tree.get_selected_text_within(container),
4798            None,
4799        )
4800    }
4801
4802    /// Clears any active text selection across the retained scene.
4803    ///
4804    /// # Arguments
4805    ///
4806    /// - `&Self` - Scene handle reference.
4807    pub fn clear_text_selection(&self) {
4808        self.mutate(SceneTree::clear_text_selection);
4809    }
4810
4811    /// Executes `operation` with immutable access to the underlying `SceneTree`.
4812    ///
4813    /// # Arguments
4814    ///
4815    /// - `&Self` - Scene handle.
4816    /// - `F` - Reader closure.
4817    /// - `R` - Fallback if re-entrantly borrowed.
4818    ///
4819    /// # Returns
4820    ///
4821    /// - `R` - Closure result or fallback.
4822    pub fn with_read<F, R>(&self, operation: F, fallback: R) -> R
4823    where
4824        F: FnOnce(&SceneTree) -> R,
4825    {
4826        let result: R = {
4827            let Self { inner } = self;
4828            match inner.tree.try_borrow() {
4829                Ok(guard) => {
4830                    let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4831                    operation(&guard)
4832                }
4833                Err(_) => return fallback,
4834            }
4835        };
4836        self.finish_outer_borrow();
4837        result
4838    }
4839
4840    /// Executes `operation` with mutable access to the underlying `SceneTree`.
4841    ///
4842    /// # Arguments
4843    ///
4844    /// - `&Self` - Scene handle.
4845    /// - `F` - Mutation closure.
4846    /// - `R` - Fallback if re-entrantly borrowed.
4847    ///
4848    /// # Returns
4849    ///
4850    /// - `R` - Closure result or fallback.
4851    pub fn with_write<F, R>(&self, operation: F, fallback: R) -> R
4852    where
4853        F: FnOnce(&mut SceneTree) -> R,
4854    {
4855        let result: R = {
4856            let Self { inner } = self;
4857            match inner.tree.try_borrow_mut() {
4858                Ok(mut guard) => {
4859                    let _depth: SceneBorrowGuard = SceneBorrowGuard::enter();
4860                    let out: R = operation(&mut guard);
4861                    if inner.has_deferred.get() {
4862                        let _: usize = Self::drain_deferred_locked(inner, &mut guard);
4863                    }
4864                    out
4865                }
4866                Err(_) => return fallback,
4867            }
4868        };
4869        self.finish_outer_borrow();
4870        result
4871    }
4872
4873    /// Binds a reactive text expression to `node_id` via a surgical `Effect`.
4874    ///
4875    /// # Arguments
4876    ///
4877    /// - `&Self` - Scene handle.
4878    /// - `NodeId` - Target text node.
4879    /// - `F` - Reactive text producer closure.
4880    ///
4881    /// # Returns
4882    ///
4883    /// - `Effect` - Registered reactive effect.
4884    pub fn bind_text<F>(&self, node_id: NodeId, mut producer: F) -> Effect
4885    where
4886        F: FnMut() -> String + 'static,
4887    {
4888        let handle: Self = self.clone();
4889        Effect::new(move || {
4890            let value: String = producer();
4891            handle.mutate(move |tree: &mut SceneTree| {
4892                tree.set_text(node_id, value);
4893            });
4894        })
4895    }
4896
4897    /// Binds a reactive `Style` expression to `node_id` via a surgical `Effect`.
4898    ///
4899    /// # Arguments
4900    ///
4901    /// - `&Self` - Scene handle.
4902    /// - `NodeId` - Target node.
4903    /// - `F` - Reactive style producer closure.
4904    ///
4905    /// # Returns
4906    ///
4907    /// - `Effect` - Registered reactive effect.
4908    pub fn bind_style<F>(&self, node_id: NodeId, mut producer: F) -> Effect
4909    where
4910        F: FnMut() -> Style + 'static,
4911    {
4912        let handle: Self = self.clone();
4913        Effect::new(move || {
4914            let style: Style = producer();
4915            handle.mutate(move |tree: &mut SceneTree| {
4916                tree.set_style(node_id, style);
4917            });
4918        })
4919    }
4920}
4921
4922/// Disposes all context-owned detached signals when the final `Context` clone drops.
4923impl Drop for ContextShared {
4924    /// Releases every reactive signal allocated by `Context::new` so repeated mount/exit cycles retain zero heap entries.
4925    ///
4926    /// # Arguments
4927    ///
4928    /// - `&Self` - Shared context state being dropped.
4929    fn drop(&mut self) {
4930        let Self {
4931            owned_signals,
4932            runtime_epoch,
4933            ..
4934        } = self;
4935        if *runtime_epoch != current_runtime_epoch() {
4936            return;
4937        }
4938        for sig_id in owned_signals.iter().copied() {
4939            let dropped: SignalSlot = with_runtime(
4940                |rt: &mut ReactiveRuntime| rt.dispose_signal(sig_id),
4941                SignalSlot::empty(),
4942            );
4943            drop(dropped);
4944        }
4945    }
4946}
4947
4948/// High-level declarative building helpers on `Context`.
4949impl Context {
4950    /// Creates a new `Context` with reactive viewport, theme, and safe-area signals.
4951    ///
4952    /// # Arguments
4953    ///
4954    /// - `SceneHandle` - Shared scene handle.
4955    /// - `PlatformKind` - Active platform kind.
4956    ///
4957    /// # Returns
4958    ///
4959    /// - `Self` - Constructed build context.
4960    #[must_use]
4961    pub fn new(scene: SceneHandle, platform: PlatformKind) -> Self {
4962        let breakpoint: Signal<Breakpoint> = Signal::new_detached(Breakpoint::Expanded);
4963        let viewport_size: Signal<Size> = Signal::new_detached(Size::new(1200.0, 800.0));
4964        let theme_mode: Signal<ThemeMode> = Signal::new_detached(ThemeMode::Light);
4965        let safe_area: Signal<SafeAreaInsets> = Signal::new_detached(SafeAreaInsets::default());
4966        let gesture: Signal<Option<GestureEvent>> = Signal::new_detached(None);
4967        let swipe_drag_offset: Signal<f32> = Signal::new_detached(0.0);
4968        let system_back: Signal<u64> = Signal::new_detached(0);
4969        let fps_limit: Signal<Option<u32>> = Signal::new_detached(None);
4970        let live_fps: Signal<f32> = Signal::new_detached(60.0);
4971        let present_fps: Signal<f32> = Signal::new_detached(0.0);
4972        let is_idle: Signal<bool> = Signal::new_detached(true);
4973        let display_refresh_rate: Signal<f32> = Signal::new_detached(60.0);
4974        let active_touches: Signal<Vec<(u64, Point)>> = Signal::new_detached(Vec::new());
4975        let exit_requested: Signal<bool> = Signal::new_detached(false);
4976        let app_state: Signal<AppState> = Signal::new_detached(AppState::Active);
4977        let network_status: Signal<NetworkStatus> = Signal::new_detached(NetworkStatus::Online);
4978        let keyboard_visible: Signal<bool> = Signal::new_detached(false);
4979        let keyboard_height: Signal<f32> = Signal::new_detached(0.0);
4980        let orientation: Signal<ScreenOrientation> =
4981            Signal::new_detached(ScreenOrientation::Landscape);
4982        let low_power_mode: Signal<bool> = Signal::new_detached(false);
4983        let locale: Signal<String> = Signal::new_detached(DEFAULT_SYSTEM_LOCALE.to_string());
4984        let window_focused: Signal<bool> = Signal::new_detached(true);
4985        let immersive_fullscreen: Signal<bool> = Signal::new_detached(false);
4986        let device_motion: Signal<DeviceMotionSample> =
4987            Signal::new_detached(DeviceMotionSample::default());
4988        let owned_signals: [SignalId; 24] = [
4989            breakpoint.id(),
4990            viewport_size.id(),
4991            theme_mode.id(),
4992            safe_area.id(),
4993            gesture.id(),
4994            swipe_drag_offset.id(),
4995            system_back.id(),
4996            fps_limit.id(),
4997            live_fps.id(),
4998            present_fps.id(),
4999            is_idle.id(),
5000            display_refresh_rate.id(),
5001            active_touches.id(),
5002            exit_requested.id(),
5003            app_state.id(),
5004            network_status.id(),
5005            keyboard_visible.id(),
5006            keyboard_height.id(),
5007            orientation.id(),
5008            low_power_mode.id(),
5009            locale.id(),
5010            window_focused.id(),
5011            immersive_fullscreen.id(),
5012            device_motion.id(),
5013        ];
5014        Self {
5015            scene,
5016            breakpoint,
5017            viewport_size,
5018            theme_mode,
5019            platform,
5020            safe_area,
5021            gesture,
5022            swipe_drag_offset,
5023            system_back,
5024            dynamic_hub: DynamicUpdateHub::new(),
5025            fps_limit,
5026            live_fps,
5027            present_fps,
5028            is_idle,
5029            display_refresh_rate,
5030            active_touches,
5031            exit_requested,
5032            app_state,
5033            network_status,
5034            keyboard_visible,
5035            keyboard_height,
5036            orientation,
5037            low_power_mode,
5038            locale,
5039            window_focused,
5040            immersive_fullscreen,
5041            device_motion,
5042            shared: Rc::new(ContextShared {
5043                fullscreen_depth: Cell::new(0),
5044                clock_ms: Cell::new(0),
5045                owned_signals,
5046                runtime_epoch: current_runtime_epoch(),
5047            }),
5048        }
5049    }
5050
5051    /// Returns the reactive `Signal<SafeAreaInsets>` updated on cold start, orientation changes, and Dynamic/Atomic Island updates.
5052    ///
5053    /// # Arguments
5054    ///
5055    /// - `&Self` - Context reference.
5056    ///
5057    /// # Returns
5058    ///
5059    /// - `Signal<SafeAreaInsets>` - Reactive safe-area insets signal.
5060    #[must_use]
5061    pub fn safe_area_signal(&self) -> Signal<SafeAreaInsets> {
5062        self.get_safe_area()
5063    }
5064
5065    /// Reads the current `SafeAreaInsets` reactively, subscribing the enclosing `Effect` or `Memo`.
5066    ///
5067    /// # Arguments
5068    ///
5069    /// - `&Self` - Context reference.
5070    ///
5071    /// # Returns
5072    ///
5073    /// - `SafeAreaInsets` - Active safe-area insets in logical pixels.
5074    #[must_use]
5075    pub fn safe_area(&self) -> SafeAreaInsets {
5076        self.get_safe_area().get()
5077    }
5078
5079    /// Returns the reactive `Signal<bool>` indicating whether immersive fullscreen mode is active.
5080    ///
5081    /// # Arguments
5082    ///
5083    /// - `&Self` - Context reference.
5084    ///
5085    /// # Returns
5086    ///
5087    /// - `Signal<bool>` - Reactive immersive fullscreen state signal.
5088    #[must_use]
5089    pub fn immersive_fullscreen_signal(&self) -> Signal<bool> {
5090        self.get_immersive_fullscreen()
5091    }
5092
5093    /// Reads whether immersive fullscreen mode is currently active, subscribing the enclosing reactive scope.
5094    ///
5095    /// # Arguments
5096    ///
5097    /// - `&Self` - Context reference.
5098    ///
5099    /// # Returns
5100    ///
5101    /// - `bool` - `true` while immersive fullscreen is active.
5102    #[must_use]
5103    pub fn is_immersive_fullscreen(&self) -> bool {
5104        self.get_immersive_fullscreen().get()
5105    }
5106
5107    /// Explicitly sets immersive fullscreen state across both reactive UI chrome and OS system bars.
5108    ///
5109    /// # Arguments
5110    ///
5111    /// - `&Self` - Context reference.
5112    /// - `bool` - `true` to enter immersive fullscreen; `false` to exit and restore bars.
5113    pub fn set_immersive_fullscreen(&self, enabled: bool) {
5114        let Self { shared, .. } = self;
5115        if enabled {
5116            if shared.fullscreen_depth.get() == 0 {
5117                shared.fullscreen_depth.set(1);
5118            }
5119            let _: bool = self.get_immersive_fullscreen().set_if_changed(true);
5120        } else {
5121            shared.fullscreen_depth.set(0);
5122            let _: bool = self.get_immersive_fullscreen().set_if_changed(false);
5123        }
5124    }
5125
5126    /// Increments the nested immersive fullscreen entry count and activates fullscreen mode.
5127    ///
5128    /// # Arguments
5129    ///
5130    /// - `&Self` - Context reference.
5131    pub fn enter_immersive_fullscreen(&self) {
5132        let Self { shared, .. } = self;
5133        let next: u32 = shared.fullscreen_depth.get().saturating_add(1);
5134        shared.fullscreen_depth.set(next);
5135        let _: bool = self.get_immersive_fullscreen().set_if_changed(true);
5136    }
5137
5138    /// Decrements the nested immersive fullscreen entry count and restores bars when the count reaches zero.
5139    ///
5140    /// # Arguments
5141    ///
5142    /// - `&Self` - Context reference.
5143    pub fn exit_immersive_fullscreen(&self) {
5144        let Self { shared, .. } = self;
5145        let next: u32 = shared.fullscreen_depth.get().saturating_sub(1);
5146        shared.fullscreen_depth.set(next);
5147        if next == 0 {
5148            let _: bool = self.get_immersive_fullscreen().set_if_changed(false);
5149        }
5150    }
5151
5152    /// Returns the reactive `Signal<AppState>` tracking canonical cross-platform application lifecycle state.
5153    ///
5154    /// # Arguments
5155    ///
5156    /// - `&Self` - Context reference.
5157    ///
5158    /// # Returns
5159    ///
5160    /// - `Signal<AppState>` - Reactive lifecycle state signal.
5161    #[must_use]
5162    pub fn app_state_signal(&self) -> Signal<AppState> {
5163        self.get_app_state()
5164    }
5165
5166    /// Dispatches a page-level `SystemEvent::Appear` to all currently active non-frozen hooks and visible observers.
5167    ///
5168    /// # Arguments
5169    ///
5170    /// - `&Self` - Context reference.
5171    pub fn emit_page_appear(&self) {
5172        let ev: SystemEvent = SystemEvent::Appear;
5173        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5174            .get_scene()
5175            .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5176        dispatch_lifecycle_system_event(&observers, &ev);
5177        dispatch_system_event_listeners(&ev);
5178    }
5179
5180    /// Dispatches a page-level `SystemEvent::Disappear` to all currently active non-frozen hooks and visible observers.
5181    ///
5182    /// # Arguments
5183    ///
5184    /// - `&Self` - Context reference.
5185    pub fn emit_page_disappear(&self) {
5186        let ev: SystemEvent = SystemEvent::Disappear;
5187        let observers: Vec<(NodeId, Rc<dyn Lifecycle>)> = self
5188            .get_scene()
5189            .with_read(SceneTree::collect_visible_lifecycles, Vec::new());
5190        dispatch_lifecycle_system_event(&observers, &ev);
5191        dispatch_system_event_listeners(&ev);
5192    }
5193
5194    /// Dispatches `SystemEvent::Appear` strictly to `Lifecycle` components and scoped hooks within `root`'s subtree.
5195    ///
5196    /// # Arguments
5197    ///
5198    /// - `&Self` - Context reference.
5199    /// - `NodeId` - Routed page or component subtree root handle becoming active.
5200    pub fn emit_subtree_appear(&self, root: NodeId) {
5201        self.get_scene().emit_subtree_appear(root);
5202    }
5203
5204    /// Dispatches `SystemEvent::Disappear` strictly to `Lifecycle` components and scoped hooks within `root`'s subtree.
5205    ///
5206    /// # Arguments
5207    ///
5208    /// - `&Self` - Context reference.
5209    /// - `NodeId` - Routed page or component subtree root handle becoming hidden.
5210    pub fn emit_subtree_disappear(&self, root: NodeId) {
5211        self.get_scene().emit_subtree_disappear(root);
5212    }
5213
5214    /// Returns the monotonic runtime elapsed clock in milliseconds.
5215    ///
5216    /// # Arguments
5217    ///
5218    /// - `&Self` - Context reference.
5219    ///
5220    /// # Returns
5221    ///
5222    /// - `u64` - Elapsed runtime time in milliseconds.
5223    #[must_use]
5224    pub fn elapsed_ms(&self) -> u64 {
5225        let Self { shared, .. } = self;
5226        shared.clock_ms.get()
5227    }
5228
5229    /// Advances the context's monotonic runtime clock by `delta_ms` milliseconds.
5230    ///
5231    /// # Arguments
5232    ///
5233    /// - `&Self` - Context reference.
5234    /// - `u64` - Milliseconds elapsed since the previous frame.
5235    pub(crate) fn advance_clock_ms(&self, delta_ms: u64) {
5236        let Self { shared, .. } = self;
5237        shared
5238            .clock_ms
5239            .set(shared.clock_ms.get().saturating_add(delta_ms));
5240    }
5241
5242    /// Requests graceful OS-level application termination across all platforms.
5243    ///
5244    /// # Arguments
5245    ///
5246    /// - `&Self` - Context reference.
5247    pub fn request_exit(&self) {
5248        let _: bool = self.get_exit_requested().set_if_changed(true);
5249        let _: bool = dispatch_native_action(NATIVE_ACTION_EXIT, "", "");
5250    }
5251
5252    /// Copies `text` to the host OS or browser clipboard via native clipboard hooks.
5253    ///
5254    /// # Arguments
5255    ///
5256    /// - `&Self` - Context reference.
5257    /// - `&str` - UTF-8 text string to copy.
5258    ///
5259    /// # Returns
5260    ///
5261    /// - `bool` - `true` when a native or host clipboard bridge accepted `text`.
5262    pub fn copy_to_clipboard(&self, text: &str) -> bool {
5263        write_system_clipboard(text)
5264    }
5265
5266    /// Creates a `View` node with the given style.
5267    ///
5268    /// # Arguments
5269    ///
5270    /// - `&Self` - Build context.
5271    /// - `Style` - Initial style.
5272    ///
5273    /// # Returns
5274    ///
5275    /// - `NodeId` - Created node handle.
5276    pub fn view(&mut self, style: Style) -> NodeId {
5277        self.get_scene().with_write(
5278            |tree: &mut SceneTree| tree.create_view(style),
5279            NodeId::default(),
5280        )
5281    }
5282
5283    /// Creates a `Text` node with static initial text.
5284    ///
5285    /// # Arguments
5286    ///
5287    /// - `&Self` - Build context.
5288    /// - `String` - Text content.
5289    /// - `Style` - Text style.
5290    ///
5291    /// # Returns
5292    ///
5293    /// - `NodeId` - Created node handle.
5294    pub fn text(&mut self, content: String, style: Style) -> NodeId {
5295        self.get_scene().with_write(
5296            |tree: &mut SceneTree| tree.create_text(content, style),
5297            NodeId::default(),
5298        )
5299    }
5300
5301    /// Creates a reactive `Text` node whose content updates surgically whenever tracked signals change.
5302    ///
5303    /// # Arguments
5304    ///
5305    /// - `&Self` - Build context.
5306    /// - `Style` - Text style.
5307    /// - `F` - Reactive text producer.
5308    ///
5309    /// # Returns
5310    ///
5311    /// - `NodeId` - Created reactive text node handle.
5312    pub fn reactive_text<F>(&mut self, style: Style, producer: F) -> NodeId
5313    where
5314        F: FnMut() -> String + 'static,
5315    {
5316        let node_id: NodeId = self.text(String::new(), style);
5317        let handle: SceneHandle = self.get_scene().clone();
5318        let (scope, _): (Scope, Effect) =
5319            Scope::run(|_: Scope| handle.bind_text(node_id, producer));
5320        self.get_scene().with_write(
5321            |tree: &mut SceneTree| {
5322                tree.attach_scope(node_id, scope);
5323            },
5324            (),
5325        );
5326        node_id
5327    }
5328
5329    /// Creates a `ScrollView` node with the given style.
5330    ///
5331    /// # Arguments
5332    ///
5333    /// - `&Self` - Build context.
5334    /// - `Style` - Scroll container style.
5335    ///
5336    /// # Returns
5337    ///
5338    /// - `NodeId` - Created scroll view handle.
5339    pub fn scroll_view(&mut self, style: Style) -> NodeId {
5340        self.get_scene().with_write(
5341            |tree: &mut SceneTree| tree.create_scroll_view(style),
5342            NodeId::default(),
5343        )
5344    }
5345
5346    /// Creates an `Input` node with initial state and style.
5347    ///
5348    /// # Arguments
5349    ///
5350    /// - `&Self` - Build context.
5351    /// - `InputNodeState` - Initial input state.
5352    /// - `Style` - Input style.
5353    ///
5354    /// # Returns
5355    ///
5356    /// - `NodeId` - Created input handle.
5357    pub fn input(&mut self, state: InputNodeState, style: Style) -> NodeId {
5358        self.get_scene().with_write(
5359            |tree: &mut SceneTree| tree.create_input(state, style),
5360            NodeId::default(),
5361        )
5362    }
5363
5364    /// Creates an `Image` node with decoded RGBA8 pixel data.
5365    ///
5366    /// # Arguments
5367    ///
5368    /// - `&Self` - Build context.
5369    /// - `ImageBuffer` - Image buffer.
5370    /// - `Style` - Image style.
5371    ///
5372    /// # Returns
5373    ///
5374    /// - `NodeId` - Created image handle.
5375    pub fn image(&mut self, buffer: ImageBuffer, style: Style) -> NodeId {
5376        self.get_scene().with_write(
5377            |tree: &mut SceneTree| tree.create_image(buffer, style),
5378            NodeId::default(),
5379        )
5380    }
5381
5382    /// Creates a `Canvas` node bound to a custom draw callback.
5383    ///
5384    /// # Arguments
5385    ///
5386    /// - `&Self` - Build context.
5387    /// - `Style` - Canvas style.
5388    /// - `F` - Draw callback receiving node bounds and mutable `DisplayList`.
5389    ///
5390    /// # Returns
5391    ///
5392    /// - `NodeId` - Created canvas handle.
5393    pub fn canvas<F>(&mut self, style: Style, painter: F) -> NodeId
5394    where
5395        F: FnMut(Rect, &mut DisplayList) + 'static,
5396    {
5397        self.canvas_with_caching(style, CanvasCaching::DynamicPerFrame, painter)
5398    }
5399
5400    /// Creates a `Canvas` node bound to a custom draw callback with an explicit `CanvasCaching` strategy.
5401    ///
5402    /// # Arguments
5403    ///
5404    /// - `&Self` - Build context.
5405    /// - `Style` - Canvas style.
5406    /// - `CanvasCaching` - Fragment caching strategy (`DynamicPerFrame` or `RetainedStatic`).
5407    /// - `F` - Draw callback receiving node bounds and mutable `DisplayList`.
5408    ///
5409    /// # Returns
5410    ///
5411    /// - `NodeId` - Created canvas handle.
5412    pub fn canvas_with_caching<F>(
5413        &mut self,
5414        style: Style,
5415        caching: CanvasCaching,
5416        painter: F,
5417    ) -> NodeId
5418    where
5419        F: FnMut(Rect, &mut DisplayList) + 'static,
5420    {
5421        let cb: CanvasDrawCallback = Rc::new(RefCell::new(painter));
5422        self.get_scene().with_write(
5423            |tree: &mut SceneTree| tree.create_canvas_with_caching(style, caching, cb),
5424            NodeId::default(),
5425        )
5426    }
5427
5428    /// Creates an overlay `Portal` node.
5429    ///
5430    /// # Arguments
5431    ///
5432    /// - `&Self` - Build context.
5433    /// - `Style` - Portal style.
5434    ///
5435    /// # Returns
5436    ///
5437    /// - `NodeId` - Created portal handle.
5438    pub fn portal(&mut self, style: Style) -> NodeId {
5439        self.get_scene().with_write(
5440            |tree: &mut SceneTree| tree.create_portal(style),
5441            NodeId::default(),
5442        )
5443    }
5444
5445    /// Creates a transparent logical `Fragment` grouping container for sibling nodes.
5446    ///
5447    /// # Arguments
5448    ///
5449    /// - `&Self` - Build context.
5450    ///
5451    /// # Returns
5452    ///
5453    /// - `NodeId` - Created fragment handle.
5454    pub fn fragment(&mut self) -> NodeId {
5455        self.get_scene().with_write(
5456            |tree: &mut SceneTree| tree.create_fragment(),
5457            NodeId::default(),
5458        )
5459    }
5460
5461    /// Appends `child` to `parent`.
5462    ///
5463    /// # Arguments
5464    ///
5465    /// - `&Self` - Build context.
5466    /// - `NodeId` - Parent container.
5467    /// - `NodeId` - Child node.
5468    pub fn append(&mut self, parent: NodeId, child: NodeId) {
5469        self.get_scene().with_write(
5470            |tree: &mut SceneTree| {
5471                tree.append_child(parent, child);
5472            },
5473            (),
5474        );
5475    }
5476
5477    /// Appends a slice of `children` to `parent` under a single scene write lock and dirty pass.
5478    ///
5479    /// # Arguments
5480    ///
5481    /// - `&Self` - Build context.
5482    /// - `NodeId` - Parent container.
5483    /// - `&[NodeId]` - Ordered child node slice.
5484    pub fn append_many(&mut self, parent: NodeId, children: &[NodeId]) {
5485        if children.is_empty() {
5486            return;
5487        }
5488        self.get_scene().with_write(
5489            |tree: &mut SceneTree| {
5490                tree.append_children(parent, children);
5491            },
5492            (),
5493        );
5494    }
5495
5496    /// Binds a reactive `Style` closure to `node_id` and attaches its disposal `Scope` automatically.
5497    ///
5498    /// # Arguments
5499    ///
5500    /// - `&Self` - Build context.
5501    /// - `NodeId` - Target scene node.
5502    /// - `F` - Reactive `Style` producer closure.
5503    pub fn bind_style<F>(&mut self, node_id: NodeId, producer: F)
5504    where
5505        F: FnMut() -> Style + 'static,
5506    {
5507        let handle: SceneHandle = self.get_scene().clone();
5508        let (scope, _): (Scope, Effect) =
5509            Scope::run(|_: Scope| handle.bind_style(node_id, producer));
5510        self.get_scene().with_write(
5511            |tree: &mut SceneTree| {
5512                tree.attach_scope(node_id, scope);
5513            },
5514            (),
5515        );
5516    }
5517
5518    /// Registers a pointer-enter handler on `node_id`.
5519    ///
5520    /// # Arguments
5521    ///
5522    /// - `&Self` - Build context.
5523    /// - `NodeId` - Target node handle.
5524    /// - `F` - Pointer-enter callback closure.
5525    pub fn on_pointer_enter<F>(&mut self, node_id: NodeId, callback: F)
5526    where
5527        F: FnMut(&UiEvent) + 'static,
5528    {
5529        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5530        self.get_scene().with_write(
5531            |tree: &mut SceneTree| {
5532                if let Some(node) = tree.get_node_mut(node_id) {
5533                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
5534                }
5535            },
5536            (),
5537        );
5538    }
5539
5540    /// Registers a pointer-leave handler on `node_id`.
5541    ///
5542    /// # Arguments
5543    ///
5544    /// - `&Self` - Build context.
5545    /// - `NodeId` - Target node handle.
5546    /// - `F` - Pointer-leave callback closure.
5547    pub fn on_pointer_leave<F>(&mut self, node_id: NodeId, callback: F)
5548    where
5549        F: FnMut(&UiEvent) + 'static,
5550    {
5551        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5552        self.get_scene().with_write(
5553            |tree: &mut SceneTree| {
5554                if let Some(node) = tree.get_node_mut(node_id) {
5555                    node.get_mut_handlers().set_on_pointer_leave(Some(handler));
5556                }
5557            },
5558            (),
5559        );
5560    }
5561
5562    /// Registers a focus-gained handler on `node_id` and marks it focusable.
5563    ///
5564    /// # Arguments
5565    ///
5566    /// - `&Self` - Build context.
5567    /// - `NodeId` - Target node handle.
5568    /// - `F` - Focus callback closure receiving `UiEventKind::Focus`.
5569    pub fn on_focus<F>(&mut self, node_id: NodeId, callback: F)
5570    where
5571        F: FnMut(&UiEvent) + 'static,
5572    {
5573        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5574        self.get_scene().with_write(
5575            |tree: &mut SceneTree| {
5576                if let Some(node) = tree.get_node_mut(node_id) {
5577                    node.get_mut_handlers().set_on_focus(Some(handler));
5578                    node.get_mut_interaction().set_focusable(true);
5579                }
5580            },
5581            (),
5582        );
5583    }
5584
5585    /// Registers a focus-lost handler on `node_id`.
5586    ///
5587    /// # Arguments
5588    ///
5589    /// - `&Self` - Build context.
5590    /// - `NodeId` - Target node handle.
5591    /// - `F` - Blur callback closure receiving `UiEventKind::Blur`.
5592    pub fn on_blur<F>(&mut self, node_id: NodeId, callback: F)
5593    where
5594        F: FnMut(&UiEvent) + 'static,
5595    {
5596        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5597        self.get_scene().with_write(
5598            |tree: &mut SceneTree| {
5599                if let Some(node) = tree.get_node_mut(node_id) {
5600                    node.get_mut_handlers().set_on_blur(Some(handler));
5601                }
5602            },
5603            (),
5604        );
5605    }
5606
5607    /// Configures whether `node_id` participates in keyboard focus navigation.
5608    ///
5609    /// # Arguments
5610    ///
5611    /// - `&Self` - Build context.
5612    /// - `NodeId` - Target node handle.
5613    /// - `bool` - Whether keyboard focus is enabled.
5614    pub fn set_focusable(&mut self, node_id: NodeId, focusable: bool) {
5615        self.get_scene().with_write(
5616            |tree: &mut SceneTree| {
5617                if let Some(node) = tree.get_node_mut(node_id) {
5618                    node.get_mut_interaction().set_focusable(focusable);
5619                }
5620            },
5621            (),
5622        );
5623    }
5624
5625    /// Registers a click handler on `node_id` and sets pointer cursor automatically.
5626    ///
5627    /// # Arguments
5628    ///
5629    /// - `&Self` - Build context.
5630    /// - `NodeId` - Target node.
5631    /// - `F` - Click callback closure.
5632    pub fn on_click<F>(&mut self, node_id: NodeId, callback: F)
5633    where
5634        F: FnMut(&UiEvent) + 'static,
5635    {
5636        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5637        self.get_scene().with_write(
5638            |tree: &mut SceneTree| {
5639                if let Some(node) = tree.get_node_mut(node_id) {
5640                    node.get_mut_handlers().set_on_click(Some(handler));
5641                    node.get_mut_interaction().set_focusable(true);
5642                    let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
5643                    if paint.get_cursor() == CursorIcon::Default {
5644                        paint.set_cursor(CursorIcon::Pointer);
5645                    }
5646                }
5647            },
5648            (),
5649        );
5650    }
5651
5652    /// Registers a change handler on an `Input` node.
5653    ///
5654    /// # Arguments
5655    ///
5656    /// - `&Self` - Build context.
5657    /// - `NodeId` - Target input node.
5658    /// - `F` - Change callback closure.
5659    pub fn on_change<F>(&mut self, node_id: NodeId, callback: F)
5660    where
5661        F: FnMut(&UiEvent) + 'static,
5662    {
5663        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5664        self.get_scene().with_write(
5665            |tree: &mut SceneTree| {
5666                if let Some(node) = tree.get_node_mut(node_id) {
5667                    node.get_mut_handlers().set_on_change(Some(handler));
5668                }
5669            },
5670            (),
5671        );
5672    }
5673
5674    /// Attaches semantic accessibility properties to `node_id`.
5675    ///
5676    /// # Arguments
5677    ///
5678    /// - `&Self` - Build context.
5679    /// - `NodeId` - Target scene node.
5680    /// - `A11yProps` - Semantic role, label, hint, and state metadata.
5681    pub fn set_a11y(&mut self, node_id: NodeId, props: A11yProps) {
5682        self.get_scene().with_write(
5683            |tree: &mut SceneTree| {
5684                if let Some(node) = tree.get_node_mut(node_id) {
5685                    node.set_a11y(Some(props));
5686                }
5687            },
5688            (),
5689        );
5690    }
5691
5692    /// Registers a scroll handler on a scrollable container node.
5693    ///
5694    /// # Arguments
5695    ///
5696    /// - `&Self` - Build context.
5697    /// - `NodeId` - Target scroll container node.
5698    /// - `F` - Scroll callback closure receiving `UiEventKind::Scroll(delta)`.
5699    pub fn on_scroll<F>(&mut self, node_id: NodeId, callback: F)
5700    where
5701        F: FnMut(&UiEvent) + 'static,
5702    {
5703        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5704        self.get_scene().with_write(
5705            |tree: &mut SceneTree| {
5706                if let Some(node) = tree.get_node_mut(node_id) {
5707                    node.get_mut_handlers().set_on_scroll(Some(handler));
5708                }
5709            },
5710            (),
5711        );
5712    }
5713
5714    /// Registers a pointer-down handler on `node_id` for draggable interactive controls.
5715    ///
5716    /// # Arguments
5717    ///
5718    /// - `&Self` - Build context.
5719    /// - `NodeId` - Target node handle.
5720    /// - `F` - Pointer-down callback closure.
5721    pub fn on_pointer_down<F>(&mut self, node_id: NodeId, callback: F)
5722    where
5723        F: FnMut(&UiEvent) + 'static,
5724    {
5725        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5726        self.get_scene().with_write(
5727            |tree: &mut SceneTree| {
5728                if let Some(node) = tree.get_node_mut(node_id) {
5729                    node.get_mut_handlers().set_on_pointer_down(Some(handler));
5730                    let paint: &mut PaintStyle = node.get_mut_style().get_mut_paint();
5731                    if paint.get_cursor() == CursorIcon::Default {
5732                        paint.set_cursor(CursorIcon::Pointer);
5733                    }
5734                }
5735            },
5736            (),
5737        );
5738    }
5739
5740    /// Registers a pointer-move handler on `node_id` receiving captured drag coordinates while pressed.
5741    ///
5742    /// # Arguments
5743    ///
5744    /// - `&Self` - Build context.
5745    /// - `NodeId` - Target node handle.
5746    /// - `F` - Pointer-move callback closure.
5747    pub fn on_pointer_move<F>(&mut self, node_id: NodeId, callback: F)
5748    where
5749        F: FnMut(&UiEvent) + 'static,
5750    {
5751        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5752        self.get_scene().with_write(
5753            |tree: &mut SceneTree| {
5754                if let Some(node) = tree.get_node_mut(node_id) {
5755                    node.get_mut_handlers().set_on_pointer_move(Some(handler));
5756                }
5757            },
5758            (),
5759        );
5760    }
5761
5762    /// Registers a pointer-up handler on `node_id` invoked when drag capture releases.
5763    ///
5764    /// # Arguments
5765    ///
5766    /// - `&Self` - Build context.
5767    /// - `NodeId` - Target node handle.
5768    /// - `F` - Pointer-up callback closure.
5769    pub fn on_pointer_up<F>(&mut self, node_id: NodeId, callback: F)
5770    where
5771        F: FnMut(&UiEvent) + 'static,
5772    {
5773        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5774        self.get_scene().with_write(
5775            |tree: &mut SceneTree| {
5776                if let Some(node) = tree.get_node_mut(node_id) {
5777                    node.get_mut_handlers().set_on_pointer_up(Some(handler));
5778                }
5779            },
5780            (),
5781        );
5782    }
5783
5784    /// Registers a pointer-cancel handler on `node_id` invoked when OS or gesture arbitration cancels a press.
5785    ///
5786    /// # Arguments
5787    ///
5788    /// - `&Self` - Build context.
5789    /// - `NodeId` - Target node handle.
5790    /// - `F` - Pointer-cancel callback closure receiving `UiEventKind::PointerCancel`.
5791    pub fn on_pointer_cancel<F>(&mut self, node_id: NodeId, callback: F)
5792    where
5793        F: FnMut(&UiEvent) + 'static,
5794    {
5795        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5796        self.get_scene().with_write(
5797            |tree: &mut SceneTree| {
5798                if let Some(node) = tree.get_node_mut(node_id) {
5799                    node.get_mut_handlers().set_on_pointer_cancel(Some(handler));
5800                }
5801            },
5802            (),
5803        );
5804    }
5805
5806    /// Registers a hover handler on `node_id` invoked on both `PointerEnter` and `PointerLeave`.
5807    ///
5808    /// # Arguments
5809    ///
5810    /// - `&Self` - Build context.
5811    /// - `NodeId` - Target node handle.
5812    /// - `F` - Hover callback closure receiving `UiEventKind::PointerEnter` or `PointerLeave`.
5813    pub fn on_hover<F>(&mut self, node_id: NodeId, callback: F)
5814    where
5815        F: FnMut(&UiEvent) + 'static,
5816    {
5817        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5818        let leave_handler: UiEventHandler = handler.clone();
5819        self.get_scene().with_write(
5820            |tree: &mut SceneTree| {
5821                if let Some(node) = tree.get_node_mut(node_id) {
5822                    node.get_mut_handlers().set_on_pointer_enter(Some(handler));
5823                    node.get_mut_handlers()
5824                        .set_on_pointer_leave(Some(leave_handler));
5825                }
5826            },
5827            (),
5828        );
5829    }
5830
5831    /// Registers a keyboard key-down handler on `node_id` and marks it focusable.
5832    ///
5833    /// # Arguments
5834    ///
5835    /// - `&Self` - Build context.
5836    /// - `NodeId` - Target node handle.
5837    /// - `F` - Key-down callback closure receiving `UiEventKind::KeyDown`.
5838    pub fn on_key<F>(&mut self, node_id: NodeId, callback: F)
5839    where
5840        F: FnMut(&UiEvent) + 'static,
5841    {
5842        let handler: UiEventHandler = Rc::new(RefCell::new(callback));
5843        self.get_scene().with_write(
5844            |tree: &mut SceneTree| {
5845                if let Some(node) = tree.get_node_mut(node_id) {
5846                    node.get_mut_handlers().set_on_key_down(Some(handler));
5847                    node.get_mut_interaction().set_focusable(true);
5848                }
5849            },
5850            (),
5851        );
5852    }
5853
5854    /// Records virtualized scroll progress on `node_id` so the overlay scrollbar tracks accurately.
5855    ///
5856    /// # Arguments
5857    ///
5858    /// - `&Self` - Build context.
5859    /// - `NodeId` - Target virtualized scroll container.
5860    /// - `f32` - Active virtual vertical scroll offset in logical pixels.
5861    /// - `f32` - Full virtualized content height in logical pixels.
5862    pub fn set_virtual_scroll(&mut self, node_id: NodeId, scroll_y: f32, content_height: f32) {
5863        self.get_scene()
5864            .set_virtual_scroll(node_id, scroll_y, content_height);
5865    }
5866
5867    /// Sets the concrete inner pixel scroll offset on `node_id` (used by virtualized lists for sub-pixel alignment).
5868    ///
5869    /// # Arguments
5870    ///
5871    /// - `&Self` - Build context.
5872    /// - `NodeId` - Target scroll container.
5873    /// - `Point` - Scroll offset `(x, y)` in logical pixels.
5874    pub fn set_scroll_offset(&mut self, node_id: NodeId, offset: Point) {
5875        self.get_scene().with_write(
5876            |tree: &mut SceneTree| {
5877                tree.set_scroll_offset(node_id, offset);
5878            },
5879            (),
5880        );
5881    }
5882
5883    /// Starts a smooth paint/transform transition on `transition.get_node()`.
5884    ///
5885    /// # Arguments
5886    ///
5887    /// - `&Self` - Build context.
5888    /// - `NodeTransition` - Transition specification.
5889    pub fn start_transition(&mut self, transition: NodeTransition) {
5890        self.get_scene().start_transition(transition);
5891    }
5892
5893    /// Mounts a reactive dynamic subtree whose children rebuild cleanly inside an isolated `Scope`.
5894    ///
5895    /// # Arguments
5896    ///
5897    /// - `&Self` - Build context.
5898    /// - `NodeId` - Host container node.
5899    /// - `F` - Reactive zero-`ctx` builder returning child `NodeId` values.
5900    pub fn bind_children<F>(&mut self, host: NodeId, mut builder: F)
5901    where
5902        F: FnMut() -> Vec<NodeId> + 'static,
5903    {
5904        let ctx_clone: Self = self.clone();
5905        let handle: SceneHandle = self.get_scene().clone();
5906        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
5907            Effect::new(move || {
5908                let (child_scope, children): (Scope, Vec<NodeId>) =
5909                    Scope::run(|_: Scope| with_context(ctx_clone.clone(), &mut builder));
5910                let first_opt: Option<NodeId> = children.first().copied();
5911                handle.replace_children_safe(host, children);
5912                if let Some(first) = first_opt {
5913                    handle.mutate(move |tree: &mut SceneTree| {
5914                        tree.attach_scope(first, child_scope);
5915                    });
5916                } else {
5917                    child_scope.dispose();
5918                }
5919            })
5920        });
5921        self.get_scene().mutate(move |tree: &mut SceneTree| {
5922            tree.attach_scope(host, scope);
5923        });
5924    }
5925
5926    /// Mounts a keyed reactive child list reconciling items in O(N) by key `K` so unchanged items retain their mounted `NodeId` and `Scope`.
5927    ///
5928    /// # Arguments
5929    ///
5930    /// - `&Self` - Build context.
5931    /// - `NodeId` - Host container node.
5932    /// - `Items` - Reactive producer returning the ordered list of item data `Vec<T>`.
5933    /// - `KeyFn` - Pure key extractor mapping `&T` to a stable key `K`.
5934    /// - `RenderFn` - Item builder mounting one child `NodeId` for a newly inserted item `T`.
5935    pub fn bind_children_keyed<T, K, Items, KeyFn, RenderFn>(
5936        &mut self,
5937        host: NodeId,
5938        mut items_fn: Items,
5939        mut key_fn: KeyFn,
5940        mut render_fn: RenderFn,
5941    ) where
5942        T: 'static,
5943        K: Eq + Hash + 'static,
5944        Items: FnMut() -> Vec<T> + 'static,
5945        KeyFn: FnMut(&T) -> K + 'static,
5946        RenderFn: FnMut(T) -> NodeId + 'static,
5947    {
5948        let ctx_clone: Self = self.clone();
5949        let handle: SceneHandle = self.get_scene().clone();
5950        let (scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
5951            let mut live_nodes: HashMap<K, NodeId> = HashMap::new();
5952            Effect::new(move || {
5953                let next_items: Vec<T> = items_fn();
5954                let mut next_map: HashMap<K, NodeId> = HashMap::with_capacity(next_items.len());
5955                let mut next_children: Vec<NodeId> = Vec::with_capacity(next_items.len());
5956                let mut new_scopes: Vec<(NodeId, Scope)> = Vec::new();
5957                for item in next_items.into_iter() {
5958                    let key: K = key_fn(&item);
5959                    if let Some(existing_id) = live_nodes.remove(&key) {
5960                        next_children.push(existing_id);
5961                        let _: Option<NodeId> = next_map.insert(key, existing_id);
5962                    } else {
5963                        let (item_scope, mounted_id): (Scope, NodeId) = Scope::run(|_: Scope| {
5964                            with_context(ctx_clone.clone(), || render_fn(item))
5965                        });
5966                        new_scopes.push((mounted_id, item_scope));
5967                        next_children.push(mounted_id);
5968                        let _: &mut NodeId = next_map.entry(key).or_insert(mounted_id);
5969                    }
5970                }
5971                live_nodes = next_map;
5972                handle.replace_children_safe(host, next_children);
5973                if !new_scopes.is_empty() {
5974                    handle.mutate(move |tree: &mut SceneTree| {
5975                        for (nid, item_scope) in new_scopes.into_iter() {
5976                            tree.attach_scope(nid, item_scope);
5977                        }
5978                    });
5979                }
5980            })
5981        });
5982        self.get_scene().mutate(move |tree: &mut SceneTree| {
5983            tree.attach_scope(host, scope);
5984        });
5985    }
5986}
5987
5988/// Restores the previously bound ambient `Context` when leaving scope.
5989impl Drop for ContextGuard {
5990    /// Restores the saved thread-local `Context`.
5991    ///
5992    /// # Arguments
5993    ///
5994    /// - `&Self` - Mutable scope guard being dropped.
5995    fn drop(&mut self) {
5996        let Self { previous } = self;
5997        let restored: Option<Context> = previous.take();
5998        ACTIVE_CONTEXT.with(|slot: &RefCell<Option<Context>>| {
5999            *slot.borrow_mut() = restored;
6000        });
6001    }
6002}
6003
6004/// `NodeRefTarget` implementation storing a `NodeId` directly into a mutable local binding.
6005impl NodeRefTarget for NodeId {
6006    /// Assigns `id` to `self`.
6007    ///
6008    /// # Arguments
6009    ///
6010    /// - `&Self` - Target `NodeId` slot.
6011    /// - `NodeId` - Mounted node handle.
6012    fn bind_node_ref(&mut self, id: NodeId) {
6013        *self = id;
6014    }
6015}
6016
6017/// `NodeRefTarget` implementation storing a `NodeId` into an `Option<NodeId>`.
6018impl NodeRefTarget for Option<NodeId> {
6019    /// Assigns `Some(id)` to `self`.
6020    ///
6021    /// # Arguments
6022    ///
6023    /// - `&Self` - Target optional `NodeId` slot.
6024    /// - `NodeId` - Mounted node handle.
6025    fn bind_node_ref(&mut self, id: NodeId) {
6026        *self = Some(id);
6027    }
6028}
6029
6030/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<NodeId>`.
6031impl NodeRefTarget for Cell<NodeId> {
6032    /// Sets `self` to `id`.
6033    ///
6034    /// # Arguments
6035    ///
6036    /// - `&Self` - Target `Cell<NodeId>`.
6037    /// - `NodeId` - Mounted node handle.
6038    fn bind_node_ref(&mut self, id: NodeId) {
6039        self.set(id);
6040    }
6041}
6042
6043/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<NodeId>>`.
6044impl NodeRefTarget for Rc<Cell<NodeId>> {
6045    /// Sets the shared cell value to `id`.
6046    ///
6047    /// # Arguments
6048    ///
6049    /// - `&Self` - Target shared `Cell<NodeId>`.
6050    /// - `NodeId` - Mounted node handle.
6051    fn bind_node_ref(&mut self, id: NodeId) {
6052        self.set(id);
6053    }
6054}
6055
6056/// `NodeRefTarget` implementation storing a `NodeId` into a `Cell<Option<NodeId>>`.
6057impl NodeRefTarget for Cell<Option<NodeId>> {
6058    /// Sets `self` to `Some(id)`.
6059    ///
6060    /// # Arguments
6061    ///
6062    /// - `&Self` - Target `Cell<Option<NodeId>>`.
6063    /// - `NodeId` - Mounted node handle.
6064    fn bind_node_ref(&mut self, id: NodeId) {
6065        self.set(Some(id));
6066    }
6067}
6068
6069/// `NodeRefTarget` implementation storing a `NodeId` into a shared `Rc<Cell<Option<NodeId>>>`.
6070impl NodeRefTarget for Rc<Cell<Option<NodeId>>> {
6071    /// Sets the shared cell value to `Some(id)`.
6072    ///
6073    /// # Arguments
6074    ///
6075    /// - `&Self` - Target shared `Cell<Option<NodeId>>`.
6076    /// - `NodeId` - Mounted node handle.
6077    fn bind_node_ref(&mut self, id: NodeId) {
6078        self.set(Some(id));
6079    }
6080}
6081
6082/// `TextNodeContent` implementation mounting an owned `String` as a static text node.
6083impl TextNodeContent for String {
6084    /// Mounts a static text scene node from this `String`.
6085    ///
6086    /// # Arguments
6087    ///
6088    /// - `Self` - Owned text string.
6089    /// - `&mut Context` - Active scene build context.
6090    /// - `Style` - Resolved text style.
6091    ///
6092    /// # Returns
6093    ///
6094    /// - `NodeId` - Mounted text node handle.
6095    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6096        ctx.text(self, style)
6097    }
6098
6099    /// Mounts a static text scene node from this `String` using the ambient `Context` without cloning it.
6100    ///
6101    /// # Arguments
6102    ///
6103    /// - `Self` - Owned text string.
6104    /// - `Style` - Resolved text style.
6105    ///
6106    /// # Returns
6107    ///
6108    /// - `NodeId` - Mounted text node handle.
6109    fn mount_text_current(self, style: Style) -> NodeId {
6110        with_current_context(|ctx: &Context| {
6111            ctx.get_scene().with_write(
6112                |tree: &mut SceneTree| tree.create_text(self, style),
6113                NodeId::default(),
6114            )
6115        })
6116    }
6117}
6118
6119/// `TextNodeContent` implementation mounting a string slice as a static text node.
6120impl TextNodeContent for &str {
6121    /// Mounts a static text scene node from this `&str`.
6122    ///
6123    /// # Arguments
6124    ///
6125    /// - `Self` - Borrowed text slice.
6126    /// - `&mut Context` - Active scene build context.
6127    /// - `Style` - Resolved text style.
6128    ///
6129    /// # Returns
6130    ///
6131    /// - `NodeId` - Mounted text node handle.
6132    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6133        ctx.text(self.to_string(), style)
6134    }
6135
6136    /// Mounts a static text scene node from this `&str` using the ambient `Context` without cloning it.
6137    ///
6138    /// # Arguments
6139    ///
6140    /// - `Self` - Borrowed text slice.
6141    /// - `Style` - Resolved text style.
6142    ///
6143    /// # Returns
6144    ///
6145    /// - `NodeId` - Mounted text node handle.
6146    fn mount_text_current(self, style: Style) -> NodeId {
6147        let owned: String = self.to_string();
6148        with_current_context(|ctx: &Context| {
6149            ctx.get_scene().with_write(
6150                |tree: &mut SceneTree| tree.create_text(owned, style),
6151                NodeId::default(),
6152            )
6153        })
6154    }
6155}
6156
6157/// `TextNodeContent` implementation mounting a borrowed `&String` as a static text node.
6158impl TextNodeContent for &String {
6159    /// Mounts a static text scene node from this `&String`.
6160    ///
6161    /// # Arguments
6162    ///
6163    /// - `Self` - Borrowed string reference.
6164    /// - `&mut Context` - Active scene build context.
6165    /// - `Style` - Resolved text style.
6166    ///
6167    /// # Returns
6168    ///
6169    /// - `NodeId` - Mounted text node handle.
6170    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6171        ctx.text(self.clone(), style)
6172    }
6173
6174    /// Mounts a static text scene node from this `&String` using the ambient `Context` without cloning it.
6175    ///
6176    /// # Arguments
6177    ///
6178    /// - `Self` - Borrowed string reference.
6179    /// - `Style` - Resolved text style.
6180    ///
6181    /// # Returns
6182    ///
6183    /// - `NodeId` - Mounted text node handle.
6184    fn mount_text_current(self, style: Style) -> NodeId {
6185        let owned: String = self.clone();
6186        with_current_context(|ctx: &Context| {
6187            ctx.get_scene().with_write(
6188                |tree: &mut SceneTree| tree.create_text(owned, style),
6189                NodeId::default(),
6190            )
6191        })
6192    }
6193}
6194
6195/// `TextNodeContent` implementation mounting a `Cow<str>` as a static text node.
6196impl TextNodeContent for Cow<'_, str> {
6197    /// Mounts a static text scene node from this `Cow<str>`.
6198    ///
6199    /// # Arguments
6200    ///
6201    /// - `Self` - Copy-on-write string value.
6202    /// - `&mut Context` - Active scene build context.
6203    /// - `Style` - Resolved text style.
6204    ///
6205    /// # Returns
6206    ///
6207    /// - `NodeId` - Mounted text node handle.
6208    fn mount_text_content(self, ctx: &mut Context, style: Style) -> NodeId {
6209        ctx.text(self.into_owned(), style)
6210    }
6211
6212    /// Mounts a static text scene node from this `Cow<str>` using the ambient `Context` without cloning it.
6213    ///
6214    /// # Arguments
6215    ///
6216    /// - `Self` - Copy-on-write string value.
6217    /// - `Style` - Resolved text style.
6218    ///
6219    /// # Returns
6220    ///
6221    /// - `NodeId` - Mounted text node handle.
6222    fn mount_text_current(self, style: Style) -> NodeId {
6223        let owned: String = self.into_owned();
6224        with_current_context(|ctx: &Context| {
6225            ctx.get_scene().with_write(
6226                |tree: &mut SceneTree| tree.create_text(owned, style),
6227                NodeId::default(),
6228            )
6229        })
6230    }
6231}
6232
6233/// `TextNodeContent` implementation mounting any `FnMut() -> S` closure or function item as a reactive text node.
6234impl<F, S> TextNodeContent for F
6235where
6236    F: FnMut() -> S + 'static,
6237    S: Into<String>,
6238{
6239    /// Mounts a reactive text scene node bound to this closure or function item.
6240    ///
6241    /// # Arguments
6242    ///
6243    /// - `Self` - Reactive text producer closure.
6244    /// - `&mut Context` - Active scene build context.
6245    /// - `Style` - Resolved text style.
6246    ///
6247    /// # Returns
6248    ///
6249    /// - `NodeId` - Mounted reactive text node handle.
6250    fn mount_text_content(mut self, ctx: &mut Context, style: Style) -> NodeId {
6251        ctx.reactive_text(style, move || self().into())
6252    }
6253
6254    /// Mounts a reactive text scene node bound to this closure or function item using the ambient `Context` without cloning it.
6255    ///
6256    /// # Arguments
6257    ///
6258    /// - `Self` - Reactive text producer closure.
6259    /// - `Style` - Resolved text style.
6260    ///
6261    /// # Returns
6262    ///
6263    /// - `NodeId` - Mounted reactive text node handle.
6264    fn mount_text_current(mut self, style: Style) -> NodeId {
6265        mount_reactive_text(style, move || self().into())
6266    }
6267}