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