Skip to main content

euv_core/scene/tree/
impl.rs

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