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