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