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