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