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