Skip to main content

repose_tree/
tree.rs

1//! The main ViewTree structure.
2
3use crate::{
4    hash::{SubtreeHashBuilder, SubtreeHashes, ViewHashes, hash_view_facets},
5    node::{LayoutCache, LayoutConstraints, NodeId, TreeNode, TreeStats},
6    reconcile::ReconcileContext,
7};
8use repose_core::{Modifier, Rect, SubcomposeScope, View, ViewId, ViewKind};
9use rustc_hash::{FxHashMap, FxHashSet};
10use slotmap::Key;
11use slotmap::SlotMap;
12use smallvec::SmallVec;
13use std::rc::Rc;
14use std::sync::Arc;
15
16/// A persistent view tree that supports incremental updates.
17pub struct ViewTree {
18    /// All nodes in the tree.
19    nodes: SlotMap<NodeId, TreeNode>,
20
21    /// The root node.
22    root: Option<NodeId>,
23
24    /// Nodes that need re-layout.
25    dirty: FxHashSet<NodeId>,
26    dirty_propagated: FxHashSet<NodeId>,
27
28    paint_dirty: FxHashSet<NodeId>,
29    paint_dirty_propagated: FxHashSet<NodeId>,
30
31    /// Current generation (frame counter).
32    generation: u64,
33
34    /// Map from user-facing ViewId to internal NodeId.
35    view_id_map: FxHashMap<ViewId, NodeId>,
36
37    /// Every live node claiming each `ViewId`, in claim order. The first
38    /// entry is the lookup owner.
39    view_id_members: FxHashMap<ViewId, SmallVec<[NodeId; 2]>>,
40
41    duplicate_view_ids: FxHashSet<ViewId>,
42
43    /// Statistics from the last reconcile operation.
44    pub stats: TreeStats,
45
46    /// Nodes removed during the last update (needed to sync external systems like Taffy).
47    pub removed_ids: Vec<NodeId>,
48
49    pending_removals: Vec<NodeId>,
50    removal_seen: FxHashSet<NodeId>,
51
52    /// Root constraints to use when calling a `SubcomposeLayout`'s content
53    /// closure during this frame. Set via [`ViewTree::set_subcompose_scope`]
54    /// before calling [`ViewTree::update`].
55    subcompose_scope: SubcomposeScope,
56
57    /// Cache of (scope, subcomposed slots) for each `SubcomposeLayout` node.
58    /// The closure is re-invoked only when the ancestor-derived scope
59    /// changes or the node's content changes. Each cached slot view has its
60    /// `Modifier::key` overwritten with its slot id.
61    subcompose_cache: FxHashMap<NodeId, (SubcomposeScope, Arc<Vec<View>>)>,
62
63    scope_invalidation_seen: FxHashSet<NodeId>,
64}
65
66impl Default for ViewTree {
67    fn default() -> Self {
68        Self::new()
69    }
70}
71
72fn rc_identity_changed<T: ?Sized>(old: &Option<Rc<T>>, new: &Option<Rc<T>>) -> bool {
73    match (old, new) {
74        (Some(old), Some(new)) => !Rc::ptr_eq(old, new),
75        (None, None) => false,
76        _ => true,
77    }
78}
79
80fn arc_identity_changed<T: ?Sized>(old: &Option<Arc<T>>, new: &Option<Arc<T>>) -> bool {
81    match (old, new) {
82        (Some(old), Some(new)) => !Arc::ptr_eq(old, new),
83        (None, None) => false,
84        _ => true,
85    }
86}
87
88#[derive(Clone, Copy, Default)]
89struct IdentityChange {
90    paint: bool,
91    layout: bool,
92    subcompose: bool,
93}
94
95impl IdentityChange {
96    fn merge(&mut self, other: Self) {
97        self.paint |= other.paint;
98        self.layout |= other.layout;
99        self.subcompose |= other.subcompose;
100    }
101}
102
103fn focus_requester_changed(
104    old: &Option<repose_core::FocusRequester>,
105    new: &Option<repose_core::FocusRequester>,
106) -> bool {
107    match (old, new) {
108        (Some(old), Some(new)) => !Rc::ptr_eq(&old.target, &new.target),
109        (None, None) => false,
110        _ => true,
111    }
112}
113
114fn interaction_source_changed(
115    old: &Option<repose_core::InteractionSource>,
116    new: &Option<repose_core::InteractionSource>,
117) -> bool {
118    match (old, new) {
119        (Some(old), Some(new)) => old.stable_id() != new.stable_id(),
120        (None, None) => false,
121        _ => true,
122    }
123}
124
125fn text_selection_changed(
126    old: &Option<repose_core::text::TextSelection>,
127    new: &Option<repose_core::text::TextSelection>,
128) -> bool {
129    match (old, new) {
130        (Some(old), Some(new)) => old.stable_id() != new.stable_id(),
131        (None, None) => false,
132        _ => true,
133    }
134}
135
136fn scroll_axis_identity_changed(
137    old: &repose_core::scroll::ScrollAxisBinding,
138    new: &repose_core::scroll::ScrollAxisBinding,
139) -> bool {
140    rc_identity_changed(&old.on_scroll, &new.on_scroll)
141        || rc_identity_changed(&old.on_scroll_with_source, &new.on_scroll_with_source)
142        || rc_identity_changed(&old.set_viewport_main, &new.set_viewport_main)
143        || rc_identity_changed(&old.set_content_main, &new.set_content_main)
144        || rc_identity_changed(&old.get_offset_main, &new.get_offset_main)
145        || rc_identity_changed(&old.set_offset_main, &new.set_offset_main)
146        || rc_identity_changed(&old.tick, &new.tick)
147        || rc_identity_changed(&old.set_nested_scroll_parent, &new.set_nested_scroll_parent)
148}
149
150fn scroll_identity_changed(
151    old: &Option<repose_core::ScrollBinding>,
152    new: &Option<repose_core::ScrollBinding>,
153) -> bool {
154    match (old, new) {
155        (
156            Some(repose_core::ScrollBinding::Vertical(old)),
157            Some(repose_core::ScrollBinding::Vertical(new)),
158        ) => scroll_axis_identity_changed(old, new),
159        (
160            Some(repose_core::ScrollBinding::Horizontal(old)),
161            Some(repose_core::ScrollBinding::Horizontal(new)),
162        ) => scroll_axis_identity_changed(old, new),
163        (
164            Some(repose_core::ScrollBinding::Both(old)),
165            Some(repose_core::ScrollBinding::Both(new)),
166        ) => {
167            rc_identity_changed(&old.on_scroll, &new.on_scroll)
168                || rc_identity_changed(&old.on_scroll_with_source, &new.on_scroll_with_source)
169                || rc_identity_changed(&old.set_viewport_width, &new.set_viewport_width)
170                || rc_identity_changed(&old.set_viewport_height, &new.set_viewport_height)
171                || rc_identity_changed(&old.set_content_width, &new.set_content_width)
172                || rc_identity_changed(&old.set_content_height, &new.set_content_height)
173                || rc_identity_changed(&old.get_offset_xy, &new.get_offset_xy)
174                || rc_identity_changed(&old.set_offset_xy, &new.set_offset_xy)
175                || rc_identity_changed(&old.tick, &new.tick)
176                || rc_identity_changed(&old.set_nested_scroll_parent, &new.set_nested_scroll_parent)
177        }
178        (None, None) => false,
179        _ => true,
180    }
181}
182
183fn cursor_identity_changed(
184    old: &Option<repose_core::CursorIcon>,
185    new: &Option<repose_core::CursorIcon>,
186) -> bool {
187    match (old, new) {
188        (
189            Some(repose_core::CursorIcon::Custom(old)),
190            Some(repose_core::CursorIcon::Custom(new)),
191        ) => !std::sync::Arc::ptr_eq(old, new) || old != new,
192        (None, None) => false,
193        _ => true,
194    }
195}
196
197fn text_input_identity_change(
198    old: Option<&repose_core::TextInputConfig>,
199    new: Option<&repose_core::TextInputConfig>,
200) -> IdentityChange {
201    let (Some(old), Some(new)) = (old, new) else {
202        return IdentityChange {
203            paint: old.is_some() != new.is_some(),
204            layout: old.is_some() != new.is_some(),
205            subcompose: false,
206        };
207    };
208    let mut change = IdentityChange::default();
209    if rc_identity_changed(&old.on_change, &new.on_change)
210        || rc_identity_changed(&old.on_submit, &new.on_submit)
211        || rc_identity_changed(&old.on_text_layout, &new.on_text_layout)
212        || rc_identity_changed(&old.focus_tracker, &new.focus_tracker)
213        || interaction_source_changed(&old.interaction_source, &new.interaction_source)
214    {
215        change.paint = true;
216    }
217    if rc_identity_changed(&old.visual_transformation, &new.visual_transformation) {
218        change.paint = true;
219        change.layout = true;
220    }
221    match (&old.keyboard_actions, &new.keyboard_actions) {
222        (Some(old), Some(new)) => {
223            if rc_identity_changed(&old.on_done, &new.on_done)
224                || rc_identity_changed(&old.on_go, &new.on_go)
225                || rc_identity_changed(&old.on_next, &new.on_next)
226                || rc_identity_changed(&old.on_previous, &new.on_previous)
227                || rc_identity_changed(&old.on_search, &new.on_search)
228                || rc_identity_changed(&old.on_send, &new.on_send)
229            {
230                change.paint = true;
231            }
232        }
233        (None, None) => {}
234        _ => change.paint = true,
235    }
236    change
237}
238
239fn modifier_identity_change(old: &Modifier, new: &Modifier) -> IdentityChange {
240    let mut change = IdentityChange::default();
241    macro_rules! paint_changed {
242        ($($field:ident),+ $(,)?) => {
243            if false $(|| rc_identity_changed(&old.$field, &new.$field))+ {
244                change.paint = true;
245            }
246        };
247    }
248    macro_rules! layout_changed {
249        ($($field:ident),+ $(,)?) => {
250            if false $(|| rc_identity_changed(&old.$field, &new.$field))+ {
251                change.layout = true;
252            }
253        };
254    }
255    if !old.nodes_identity_matches(new) {
256        change.paint = true;
257    }
258    paint_changed!(
259        on_scroll,
260        on_pointer_down,
261        on_pointer_move,
262        on_pointer_up,
263        on_pointer_cancel,
264        on_pointer_enter,
265        on_pointer_leave,
266        on_click,
267        on_double_click,
268        on_long_click,
269        on_globally_positioned,
270        on_size_changed,
271        on_key_event,
272        on_preview_key_event,
273        on_ime,
274        on_drag_start,
275        on_drag_end,
276        on_drag_enter,
277        on_drag_over,
278        on_drag_leave,
279        on_drop,
280        on_action,
281        painter,
282        graphics_layer_scope,
283        indication,
284        drag_preview,
285        on_focus_changed,
286    );
287    layout_changed!(layout);
288    if arc_identity_changed(&old.paint_callback, &new.paint_callback) {
289        change.paint = true;
290    }
291    if focus_requester_changed(&old.focus_requester, &new.focus_requester)
292        || old.bring_into_view.is_some() != new.bring_into_view.is_some()
293        || interaction_source_changed(&old.interaction_source, &new.interaction_source)
294        || text_selection_changed(&old.text_selection, &new.text_selection)
295    {
296        change.paint = true;
297    }
298    change.merge(text_input_identity_change(
299        old.text_input.as_ref(),
300        new.text_input.as_ref(),
301    ));
302    match (&old.nested_scroll_connection, &new.nested_scroll_connection) {
303        (Some(old), Some(new)) => {
304            if rc_identity_changed(&old.on_pre_scroll, &new.on_pre_scroll)
305                || rc_identity_changed(&old.on_post_scroll, &new.on_post_scroll)
306                || rc_identity_changed(&old.on_pre_fling, &new.on_pre_fling)
307                || rc_identity_changed(&old.on_post_fling, &new.on_post_fling)
308            {
309                change.paint = true;
310            }
311        }
312        (None, None) => {}
313        _ => change.paint = true,
314    }
315    if scroll_identity_changed(&old.scroll, &new.scroll)
316        || cursor_identity_changed(&old.cursor, &new.cursor)
317        || old.scrollbar_style != new.scrollbar_style
318    {
319        change.paint = true;
320    }
321    if old.layout_offset != new.layout_offset
322        || old.absolute_layout_offset != new.absolute_layout_offset
323        || old.wrap_content != new.wrap_content
324    {
325        change.layout = true;
326    }
327    if old.visible != new.visible {
328        change.layout = true;
329        change.paint = true;
330    }
331    if old.background_alpha != new.background_alpha {
332        change.paint = true;
333    }
334    if old.paint_order != new.paint_order {
335        change.paint = true;
336    }
337    change
338}
339
340fn view_identity_change(node: &TreeNode, view: &View) -> IdentityChange {
341    let mut change = modifier_identity_change(&node.modifier, &view.modifier);
342    if let (
343        ViewKind::SubcomposeLayout { content: old },
344        ViewKind::SubcomposeLayout { content: new },
345    ) = (&node.kind, &view.kind)
346        && !Arc::ptr_eq(old, new)
347    {
348        change.paint = true;
349        change.layout = true;
350        change.subcompose = true;
351    }
352    change
353}
354
355fn semantics_equal(
356    old: Option<&repose_core::Semantics>,
357    new: Option<&repose_core::Semantics>,
358) -> bool {
359    match (old, new) {
360        (Some(old), Some(new)) => {
361            old.role == new.role
362                && old.label == new.label
363                && old.focused == new.focused
364                && old.enabled == new.enabled
365                && old.selectable_group == new.selectable_group
366                && old.checked == new.checked
367                && old.selected == new.selected
368                && old.value == new.value
369        }
370        (None, None) => true,
371        _ => false,
372    }
373}
374
375fn view_kind_equal(old: &ViewKind, new: &ViewKind) -> bool {
376    match (old, new) {
377        (
378            ViewKind::SubcomposeLayout { content: old },
379            ViewKind::SubcomposeLayout { content: new },
380        ) => Arc::ptr_eq(old, new),
381        (
382            ViewKind::Text {
383                text: old_text,
384                color: old_color,
385                font_size: old_font_size,
386                soft_wrap: old_soft_wrap,
387                max_lines: old_max_lines,
388                overflow: old_overflow,
389                font_family: old_font_family,
390                annotations: old_annotations,
391                text_align: old_text_align,
392                font_weight: old_font_weight,
393                font_style: old_font_style,
394                text_decoration: old_text_decoration,
395                letter_spacing: old_letter_spacing,
396                line_height: old_line_height,
397                url: old_url,
398                font_variation_settings: old_font_variation_settings,
399                draw_style: old_draw_style,
400            },
401            ViewKind::Text {
402                text: new_text,
403                color: new_color,
404                font_size: new_font_size,
405                soft_wrap: new_soft_wrap,
406                max_lines: new_max_lines,
407                overflow: new_overflow,
408                font_family: new_font_family,
409                annotations: new_annotations,
410                text_align: new_text_align,
411                font_weight: new_font_weight,
412                font_style: new_font_style,
413                text_decoration: new_text_decoration,
414                letter_spacing: new_letter_spacing,
415                line_height: new_line_height,
416                url: new_url,
417                font_variation_settings: new_font_variation_settings,
418                draw_style: new_draw_style,
419            },
420        ) => {
421            old_text == new_text
422                && old_color == new_color
423                && old_font_size == new_font_size
424                && old_soft_wrap == new_soft_wrap
425                && old_max_lines == new_max_lines
426                && old_overflow == new_overflow
427                && old_font_family == new_font_family
428                && old_annotations == new_annotations
429                && old_text_align == new_text_align
430                && old_font_weight == new_font_weight
431                && old_font_style == new_font_style
432                && old_text_decoration == new_text_decoration
433                && old_letter_spacing == new_letter_spacing
434                && old_line_height == new_line_height
435                && old_url == new_url
436                && old_font_variation_settings == new_font_variation_settings
437                && old_draw_style == new_draw_style
438        }
439        (
440            ViewKind::Image {
441                handle: old_handle,
442                tint: old_tint,
443                fit: old_fit,
444                filter: old_filter,
445                source_rect: old_source_rect,
446                alignment: old_alignment,
447            },
448            ViewKind::Image {
449                handle: new_handle,
450                tint: new_tint,
451                fit: new_fit,
452                filter: new_filter,
453                source_rect: new_source_rect,
454                alignment: new_alignment,
455            },
456        ) => {
457            old_handle == new_handle
458                && old_tint == new_tint
459                && old_fit == new_fit
460                && old_filter == new_filter
461                && old_source_rect == new_source_rect
462                && old_alignment == new_alignment
463        }
464        _ => std::mem::discriminant(old) == std::mem::discriminant(new),
465    }
466}
467
468fn next_dedup_key(
469    original: u64,
470    index: usize,
471    parent_id: NodeId,
472    new_seen_keys: &mut FxHashSet<u64>,
473    keyed_children: &FxHashMap<u64, NodeId>,
474) -> u64 {
475    let mut candidate = (original.wrapping_mul(0x9E3779B97F4A7C15)
476        ^ (index as u64).wrapping_add(0xBF58476D1CE4E5B9))
477    .wrapping_add(parent_id.data().as_ffi());
478    loop {
479        if candidate != original
480            && !new_seen_keys.contains(&candidate)
481            && !keyed_children.contains_key(&candidate)
482        {
483            new_seen_keys.insert(candidate);
484            return candidate;
485        }
486        candidate = candidate.wrapping_add(1);
487        if candidate == 0 {
488            candidate = 1;
489        }
490    }
491}
492
493impl ViewTree {
494    /// Create a new empty tree.
495    pub fn new() -> Self {
496        Self {
497            nodes: SlotMap::with_key(),
498            root: None,
499            dirty: FxHashSet::default(),
500            dirty_propagated: FxHashSet::default(),
501            paint_dirty: FxHashSet::default(),
502            paint_dirty_propagated: FxHashSet::default(),
503            generation: 0,
504            view_id_map: FxHashMap::default(),
505            view_id_members: FxHashMap::default(),
506            duplicate_view_ids: FxHashSet::default(),
507            stats: TreeStats::default(),
508            removed_ids: Vec::new(),
509            pending_removals: Vec::new(),
510            removal_seen: FxHashSet::default(),
511            subcompose_scope: SubcomposeScope::UNBOUNDED,
512            subcompose_cache: FxHashMap::default(),
513            scope_invalidation_seen: FxHashSet::default(),
514        }
515    }
516
517    /// Set the constraints that will be passed to any `SubcomposeLayout`
518    /// content closures during the next [`update`](Self::update) call.
519    /// The scope is read once per reconcile of a `SubcomposeLayout` node. If
520    /// you need different scopes at different depths, the closure itself is
521    /// responsible for narrowing the values it receives.
522    pub fn set_subcompose_scope(&mut self, scope: SubcomposeScope) {
523        self.subcompose_scope = SubcomposeScope::new(
524            scope.min_width,
525            scope.max_width,
526            scope.min_height,
527            scope.max_height,
528        );
529    }
530
531    /// Get the currently-set subcompose scope.
532    pub fn subcompose_scope(&self) -> SubcomposeScope {
533        self.subcompose_scope
534    }
535
536    /// Run a `SubcomposeLayout`'s content closure, returning the cached views
537    /// when the scope is unchanged for this node.
538    /// The caller is responsible for ensuring the cache is invalidated (e.g.
539    /// on content change) via [`ViewTree::invalidate_subcompose_cache`].
540    ///
541    /// The closure must run whenever the scope differs from the scope the
542    /// cached views were built for: the scope is derived from the previous
543    /// frame's layout, so holding a stale result would keep feeding the tree a
544    /// scope that no longer exists.
545    ///
546    /// The scope is computed by walking the node's ancestor chain and
547    /// intersecting the root scope with each ancestor's `Modifier` width /
548    /// height / min / max fields, plus the SubcomposeLayout's own modifier.
549    /// Ancestors additionally narrow the scope by their own cached
550    /// Taffy-computed size from the previous frame's layout pass.
551    fn run_subcompose(
552        &mut self,
553        node_id: NodeId,
554        content: &Arc<dyn Fn(&SubcomposeScope) -> Vec<(u64, View)>>,
555    ) -> Arc<Vec<View>> {
556        let raw_scope = self.compute_scope_for_node(node_id);
557        let scope = SubcomposeScope::new(
558            raw_scope.min_width,
559            raw_scope.max_width,
560            raw_scope.min_height,
561            raw_scope.max_height,
562        );
563        if let Some((cached_scope, cached_slots)) = self.subcompose_cache.get(&node_id)
564            && *cached_scope == scope
565        {
566            return Arc::clone(cached_slots);
567        }
568        let slots = content(&scope);
569        let scope_key = format!("subcompose_{:?}", node_id);
570        let mut views = Vec::with_capacity(slots.len());
571        for (slot_id, mut view) in slots {
572            view.modifier.key = Some(slot_id);
573            view.scope_key = Some(scope_key.clone());
574            view.modifier.repaint_boundary = true;
575            views.push(view);
576        }
577        let views = Arc::new(views);
578        let old_cache = self
579            .subcompose_cache
580            .insert(node_id, (scope, Arc::clone(&views)));
581        drop(old_cache);
582        views
583    }
584
585    /// Compute the `SubcomposeScope` visible to a `SubcomposeLayout` at
586    /// `node_id`. Starts with the user-set root scope and intersects each
587    /// ancestor's `Modifier` width / height / min / max / padding fields in
588    /// root-to-leaf order. Each ancestor also narrows the scope by its cached
589    /// Taffy-computed size from the previous frame's layout pass, so
590    /// parent-dependent sizes are reflected in the scope after the first frame.
591    ///
592    /// The SubcomposeLayout's own measured size is deliberately excluded: a
593    /// node's size is an outcome of its content, so feeding it back would let
594    /// subcomposed content ratchet its own scope inward every frame.
595    fn compute_scope_for_node(&self, node_id: NodeId) -> SubcomposeScope {
596        let mut scope = self.subcompose_scope;
597        let mut chain: SmallVec<[NodeId; 16]> = SmallVec::new();
598        let mut current = Some(node_id);
599        while let Some(id) = current {
600            chain.push(id);
601            match self.nodes.get(id) {
602                Some(node) => current = node.parent,
603                None => break,
604            }
605        }
606        chain.reverse();
607        for &ancestor_id in &chain {
608            if let Some(node) = self.nodes.get(ancestor_id) {
609                scope = intersect_scope_with_modifier(scope, &node.modifier);
610                if ancestor_id == node_id {
611                    continue;
612                }
613                if let Some(cache) = &node.layout_cache {
614                    let w = cache.rect.w;
615                    if w >= 0.0 && w.is_finite() {
616                        scope.max_width = scope.max_width.min(repose_core::Dp(w));
617                    }
618                    let h = cache.rect.h;
619                    if h >= 0.0 && h.is_finite() {
620                        scope.max_height = scope.max_height.min(repose_core::Dp(h));
621                    }
622                }
623            }
624        }
625        scope
626    }
627
628    /// Drop the cached subcomposed view for a single node. Call this when the
629    /// `SubcomposeLayout`'s modifier or identity changes so the next
630    /// reconciliation re-invokes the closure.
631    pub fn invalidate_subcompose_cache(&mut self, node_id: NodeId) {
632        let removed = self.subcompose_cache.remove(&node_id);
633        drop(removed);
634    }
635
636    /// Get the current generation.
637    pub fn generation(&self) -> u64 {
638        self.generation
639    }
640
641    /// Get the root node ID.
642    pub fn root(&self) -> Option<NodeId> {
643        self.root
644    }
645
646    /// Get a node by ID.
647    pub fn get(&self, id: NodeId) -> Option<&TreeNode> {
648        self.nodes.get(id)
649    }
650
651    /// Get a mutable node by ID.
652    pub fn get_mut(&mut self, id: NodeId) -> Option<&mut TreeNode> {
653        self.nodes.get_mut(id)
654    }
655
656    /// Get a node by ViewId.
657    pub fn get_by_view_id(&self, view_id: ViewId) -> Option<&TreeNode> {
658        self.view_id_map
659            .get(&view_id)
660            .and_then(|id| self.nodes.get(*id))
661    }
662
663    /// Get the number of nodes in the tree.
664    pub fn len(&self) -> usize {
665        self.nodes.len()
666    }
667
668    /// Check if the tree is empty.
669    pub fn is_empty(&self) -> bool {
670        self.nodes.is_empty()
671    }
672
673    /// Check if a node is marked dirty.
674    pub fn is_dirty(&self, id: NodeId) -> bool {
675        self.dirty.contains(&id)
676    }
677
678    /// Get the set of dirty nodes.
679    pub fn dirty_nodes(&self) -> &FxHashSet<NodeId> {
680        &self.dirty
681    }
682
683    /// Clear the dirty set (after layout).
684    pub fn clear_dirty(&mut self) {
685        self.dirty.clear();
686        self.dirty_propagated.clear();
687    }
688
689    pub fn paint_dirty_nodes(&self) -> &FxHashSet<NodeId> {
690        &self.paint_dirty
691    }
692
693    pub fn clear_paint_dirty(&mut self) {
694        self.paint_dirty.clear();
695        self.paint_dirty_propagated.clear();
696    }
697
698    fn mark_paint_dirty(&mut self, node_id: NodeId) {
699        let mut current = Some(node_id);
700        while let Some(id) = current {
701            if !self.paint_dirty_propagated.insert(id) {
702                break;
703            }
704            self.paint_dirty.insert(id);
705            current = self.nodes.get(id).and_then(|node| node.parent);
706        }
707    }
708
709    fn mark_scope_descendants_dirty(&mut self, id: NodeId) {
710        if !self.scope_invalidation_seen.insert(id) {
711            return;
712        }
713        let mut stack: SmallVec<[NodeId; 16]> = SmallVec::new();
714        stack.push(id);
715        while let Some(current) = stack.pop() {
716            let Some(node) = self.nodes.get(current) else {
717                continue;
718            };
719            for &child in &node.children {
720                if self
721                    .nodes
722                    .get(child)
723                    .is_some_and(|child| child.scope_key.is_some())
724                {
725                    self.dirty.insert(child);
726                }
727                stack.push(child);
728            }
729        }
730    }
731
732    /// Mark a node as needing re-layout.
733    pub fn mark_dirty(&mut self, id: NodeId) {
734        let mut current = Some(id);
735        while let Some(current_id) = current {
736            if !self.dirty_propagated.insert(current_id) {
737                break;
738            }
739            self.dirty.insert(current_id);
740            current = self.nodes.get(current_id).and_then(|node| node.parent);
741        }
742
743        let needs_scope_invalidate = self.nodes.get(id).is_some_and(|node| {
744            node.modifier.transform.is_some()
745                || node.modifier.alpha.is_some()
746                || node.modifier.graphics_layer.is_some()
747                || node.modifier.graphics_layer_scope.is_some()
748        });
749        if needs_scope_invalidate {
750            self.mark_scope_descendants_dirty(id);
751        }
752    }
753
754    /// Update the tree from a new View, performing incremental reconciliation.
755    /// Returns the root NodeId.
756    pub fn update(&mut self, new_root: &View) -> NodeId {
757        self.removed_ids.clear();
758        self.pending_removals.clear();
759        self.removal_seen.clear();
760        self.paint_dirty.clear();
761        self.paint_dirty_propagated.clear();
762        self.dirty_propagated.clear();
763        self.scope_invalidation_seen.clear();
764
765        self.generation += 1;
766        self.stats = TreeStats::default();
767
768        let mut ctx = ReconcileContext::new(self.generation);
769
770        let root_id = if let Some(existing_root) = self.root {
771            self.reconcile_node(existing_root, new_root, None, 0, 0, &mut ctx)
772        } else {
773            self.create_node(new_root, None, 0, 0, &mut ctx)
774        };
775
776        self.root = Some(root_id);
777        self.collect_explicit_removals(&mut ctx);
778
779        self.stats.total_nodes = self.nodes.len();
780        self.stats.dirty_nodes = self.dirty.len();
781        self.stats.reconciled_nodes = ctx.reconciled;
782        self.stats.skipped_nodes = ctx.skipped;
783        self.stats.created_nodes = ctx.created;
784        self.stats.removed_nodes = ctx.removed;
785
786        root_id
787    }
788
789    /// Reconcile an existing node with a new View.
790    fn reconcile_node(
791        &mut self,
792        node_id: NodeId,
793        view: &View,
794        parent: Option<NodeId>,
795        depth: u32,
796        index_in_parent: u32,
797        ctx: &mut ReconcileContext,
798    ) -> NodeId {
799        let hashes = hash_view_facets(view);
800        let Some(node) = self.nodes.get(node_id) else {
801            log::error!(
802                "reconcile_node: node {:?} not found - creating fresh",
803                node_id
804            );
805            return self.create_node(view, parent, depth, index_in_parent, ctx);
806        };
807
808        let old_hashes = ViewHashes {
809            layout: node.layout_hash,
810            measurement: node.measurement_hash,
811            paint: node.paint_hash,
812            semantics: node.semantics_hash,
813        };
814        let identity = view_identity_change(node, view);
815        let old_subtree = SubtreeHashes {
816            layout: node.layout_subtree_hash,
817            measurement: node.measurement_subtree_hash,
818            paint: node.paint_subtree_hash,
819            semantics: node.semantics_subtree_hash,
820        };
821        let old_subtree_hash = node.subtree_hash;
822        let old_scope_key = node.scope_key.clone();
823        let old_view_id = node.view_id;
824        let old_is_subcompose = matches!(&node.kind, ViewKind::SubcomposeLayout { .. });
825        let new_is_subcompose = matches!(&view.kind, ViewKind::SubcomposeLayout { .. });
826        let hashes_equal = old_hashes == hashes;
827        let content_hash = hashes.combined();
828        let content_changed = !hashes_equal;
829        let view_semantics_changed =
830            !hashes_equal && !semantics_equal(node.semantics.as_ref(), view.semantics.as_ref());
831        let modifier_semantics_changed = !hashes_equal
832            && !semantics_equal(
833                node.modifier.semantics.as_ref(),
834                view.modifier.semantics.as_ref(),
835            );
836        let scope_effect_changed = node.modifier.transform != view.modifier.transform
837            || node.modifier.alpha != view.modifier.alpha
838            || node.modifier.graphics_layer != view.modifier.graphics_layer
839            || rc_identity_changed(
840                &node.modifier.graphics_layer_scope,
841                &view.modifier.graphics_layer_scope,
842            );
843        let kind_changed = !view_kind_equal(&node.kind, &view.kind);
844        let modifier_changed = old_hashes.layout != hashes.layout
845            || old_hashes.measurement != hashes.measurement
846            || old_hashes.paint != hashes.paint
847            || modifier_semantics_changed
848            || identity.paint
849            || identity.layout;
850        let scope_changed = old_scope_key.as_deref() != view.scope_key.as_deref();
851        let node_layout_changed = old_hashes.layout != hashes.layout
852            || old_hashes.measurement != hashes.measurement
853            || identity.layout
854            || identity.subcompose
855            || old_is_subcompose != new_is_subcompose;
856        let subcompose_changed = identity.subcompose
857            || (new_is_subcompose
858                && (old_hashes.layout != hashes.layout
859                    || old_hashes.measurement != hashes.measurement
860                    || identity.layout))
861            || old_is_subcompose != new_is_subcompose;
862        if subcompose_changed {
863            self.invalidate_subcompose_cache(node_id);
864        }
865
866        let view_id = self.compute_view_id(view, node_id, parent, index_in_parent);
867        self.assign_view_id(
868            node_id,
869            old_view_id,
870            view_id,
871            view.id == 0,
872            "reconcile_node",
873        );
874
875        {
876            let Some(node) = self.nodes.get_mut(node_id) else {
877                log::error!("reconcile_node: node {:?} vanished mid-reconcile", node_id);
878                return node_id;
879            };
880            node.parent = parent;
881            node.depth = depth;
882            node.generation = self.generation;
883            if kind_changed {
884                node.kind = view.kind.clone();
885            }
886            let old_modifier = node.modifier.clone();
887            if modifier_changed || !old_modifier.nodes.is_empty() || !view.modifier.nodes.is_empty()
888            {
889                let mut next = view.modifier.clone();
890                next.adopt_nodes_from(&old_modifier);
891                node.modifier = next;
892            }
893            if view_semantics_changed {
894                node.semantics = view.semantics.clone();
895            }
896            if scope_changed {
897                node.scope_key = view.scope_key.clone();
898            }
899            node.user_key = view.modifier.key;
900            if node_layout_changed {
901                node.layout_cache = None;
902            }
903        }
904
905        let new_children_hashes = if let ViewKind::SubcomposeLayout { content } = &view.kind {
906            let subcomposed = self.run_subcompose(node_id, content);
907            self.reconcile_children(node_id, subcomposed.as_slice(), depth, ctx)
908        } else {
909            self.reconcile_children(node_id, &view.children, depth, ctx)
910        };
911        let new_subtree = new_children_hashes.finish(hashes);
912        let new_subtree_hash = new_subtree.combined();
913        let layout_subtree_changed = old_subtree.layout != new_subtree.layout
914            || old_subtree.measurement != new_subtree.measurement
915            || identity.layout
916            || identity.subcompose;
917        let paint_subtree_changed =
918            old_subtree.paint != new_subtree.paint || identity.paint || identity.subcompose;
919        let semantics_subtree_changed = old_subtree.semantics != new_subtree.semantics;
920        let subtree_changed = old_subtree_hash != new_subtree_hash || identity.subcompose;
921
922        {
923            let Some(node) = self.nodes.get_mut(node_id) else {
924                log::error!("reconcile_node: node {:?} vanished mid-reconcile", node_id);
925                return node_id;
926            };
927            if layout_subtree_changed {
928                node.layout_cache = None;
929            }
930            node.content_hash = content_hash;
931            node.layout_hash = hashes.layout;
932            node.measurement_hash = hashes.measurement;
933            node.paint_hash = hashes.paint;
934            node.semantics_hash = hashes.semantics;
935            node.subtree_hash = new_subtree_hash;
936            node.layout_subtree_hash = new_subtree.layout;
937            node.measurement_subtree_hash = new_subtree.measurement;
938            node.paint_subtree_hash = new_subtree.paint;
939            node.semantics_subtree_hash = new_subtree.semantics;
940
941            if content_changed || identity.paint || identity.layout || identity.subcompose {
942                ctx.reconciled += 1;
943            } else if !subtree_changed {
944                ctx.skipped += 1;
945            }
946        }
947
948        if paint_subtree_changed || semantics_subtree_changed {
949            self.mark_paint_dirty(node_id);
950        }
951        if layout_subtree_changed {
952            self.mark_dirty(node_id);
953        }
954        if scope_effect_changed {
955            self.mark_scope_descendants_dirty(node_id);
956        }
957
958        node_id
959    }
960    fn node_subtree_hashes(&self, node_id: NodeId) -> SubtreeHashes {
961        self.nodes
962            .get(node_id)
963            .map_or_default(|node| SubtreeHashes {
964                layout: node.layout_subtree_hash,
965                measurement: node.measurement_subtree_hash,
966                paint: node.paint_subtree_hash,
967                semantics: node.semantics_subtree_hash,
968            })
969    }
970
971    /// Reconcile children of a node.
972    /// Returns the subtree hashes of all children (for computing parent's subtree hash).
973    fn reconcile_children(
974        &mut self,
975        parent_id: NodeId,
976        new_children: &[View],
977        parent_depth: u32,
978        ctx: &mut ReconcileContext,
979    ) -> SubtreeHashBuilder {
980        let child_depth = parent_depth + 1;
981        let old_children: SmallVec<[NodeId; 4]> = self
982            .nodes
983            .get_mut(parent_id)
984            .map(|node| std::mem::take(&mut node.children))
985            .unwrap_or_default();
986
987        let mut keyed_children: FxHashMap<u64, NodeId> = FxHashMap::default();
988        let mut unkeyed_children: SmallVec<[NodeId; 4]> = SmallVec::new();
989        for &child_id in &old_children {
990            if let Some(node) = self.nodes.get(child_id) {
991                match node.user_key {
992                    Some(key) => {
993                        keyed_children.entry(key).or_insert(child_id);
994                    }
995                    None => unkeyed_children.push(child_id),
996                }
997            }
998        }
999
1000        let mut new_child_ids: SmallVec<[NodeId; 4]> = SmallVec::new();
1001        let mut child_hashes = SubtreeHashBuilder::new(new_children.len());
1002        let mut unkeyed_index = 0;
1003        let mut used_nodes: FxHashSet<NodeId> = FxHashSet::default();
1004        let mut new_seen_keys: FxHashSet<u64> = FxHashSet::default();
1005
1006        for (i, new_child) in new_children.iter().enumerate() {
1007            let mut owned_child: Option<View>;
1008            let child_ref = if let Some(key) = new_child.modifier.key {
1009                if new_seen_keys.insert(key) {
1010                    new_child
1011                } else {
1012                    log::error!(
1013                        "reconcile_children: duplicate modifier.key={} in children of node {:?} - deduplicating (suffixing). Ensure get_key returns unique keys.",
1014                        key,
1015                        parent_id
1016                    );
1017                    let salt =
1018                        next_dedup_key(key, i, parent_id, &mut new_seen_keys, &keyed_children);
1019                    owned_child = Some(new_child.clone());
1020                    let child = owned_child.as_mut().expect("owned child inserted");
1021                    child.modifier.key = Some(salt);
1022                    child
1023                }
1024            } else {
1025                new_child
1026            };
1027
1028            let is_subcompose = matches!(&child_ref.kind, ViewKind::SubcomposeLayout { .. });
1029            let child_id = if let Some(key) = child_ref.modifier.key {
1030                if let Some(&existing_id) = keyed_children.get(&key) {
1031                    if used_nodes.insert(existing_id) {
1032                        self.reconcile_node(
1033                            existing_id,
1034                            child_ref,
1035                            Some(parent_id),
1036                            child_depth,
1037                            i as u32,
1038                            ctx,
1039                        )
1040                    } else {
1041                        let salt =
1042                            next_dedup_key(key, i, parent_id, &mut new_seen_keys, &keyed_children);
1043                        let mut fresh = child_ref.clone();
1044                        fresh.modifier.key = Some(salt);
1045                        self.create_node(&fresh, Some(parent_id), child_depth, i as u32, ctx)
1046                    }
1047                } else if is_subcompose && unkeyed_index < unkeyed_children.len() {
1048                    let existing_id = unkeyed_children[unkeyed_index];
1049                    unkeyed_index += 1;
1050                    if used_nodes.insert(existing_id) {
1051                        self.reconcile_node(
1052                            existing_id,
1053                            child_ref,
1054                            Some(parent_id),
1055                            child_depth,
1056                            i as u32,
1057                            ctx,
1058                        )
1059                    } else {
1060                        self.create_node(child_ref, Some(parent_id), child_depth, i as u32, ctx)
1061                    }
1062                } else {
1063                    self.create_node(child_ref, Some(parent_id), child_depth, i as u32, ctx)
1064                }
1065            } else if let Some(&existing_id) = unkeyed_children.get(unkeyed_index) {
1066                unkeyed_index += 1;
1067                if used_nodes.insert(existing_id) {
1068                    self.reconcile_node(
1069                        existing_id,
1070                        child_ref,
1071                        Some(parent_id),
1072                        child_depth,
1073                        i as u32,
1074                        ctx,
1075                    )
1076                } else {
1077                    self.create_node(child_ref, Some(parent_id), child_depth, i as u32, ctx)
1078                }
1079            } else {
1080                self.create_node(child_ref, Some(parent_id), child_depth, i as u32, ctx)
1081            };
1082
1083            new_child_ids.push(child_id);
1084            child_hashes.push(self.node_subtree_hashes(child_id));
1085        }
1086
1087        for &old_child in &old_children {
1088            if !used_nodes.contains(&old_child) {
1089                self.mark_for_removal(old_child);
1090            }
1091        }
1092
1093        if let Some(parent) = self.nodes.get_mut(parent_id) {
1094            parent.children = new_child_ids;
1095        }
1096
1097        child_hashes
1098    }
1099
1100    /// Create a new node from a View.
1101    fn create_node(
1102        &mut self,
1103        view: &View,
1104        parent: Option<NodeId>,
1105        depth: u32,
1106        index_in_parent: u32,
1107        ctx: &mut ReconcileContext,
1108    ) -> NodeId {
1109        let hashes = hash_view_facets(view);
1110        let content_hash = hashes.combined();
1111
1112        let node_id = self.nodes.insert_with_key(|id| {
1113            TreeNode::new(
1114                id,
1115                0,
1116                view.kind.clone(),
1117                view.modifier.clone(),
1118                self.generation,
1119            )
1120        });
1121        ctx.created += 1;
1122
1123        {
1124            let node = self
1125                .nodes
1126                .get_mut(node_id)
1127                .expect("create_node: node just inserted");
1128            node.parent = parent;
1129            node.depth = depth;
1130            node.semantics = view.semantics.clone();
1131            node.content_hash = content_hash;
1132            node.layout_hash = hashes.layout;
1133            node.measurement_hash = hashes.measurement;
1134            node.paint_hash = hashes.paint;
1135            node.semantics_hash = hashes.semantics;
1136            node.user_key = view.modifier.key;
1137            node.scope_key = view.scope_key.clone();
1138        }
1139
1140        let view_id = self.compute_view_id(view, node_id, parent, index_in_parent);
1141        self.assign_view_id(node_id, 0, view_id, view.id == 0, "create_node");
1142
1143        let child_depth = depth + 1;
1144        let mut child_ids: SmallVec<[NodeId; 4]> = SmallVec::new();
1145        let subcomposed = if let ViewKind::SubcomposeLayout { content } = &view.kind {
1146            Some(self.run_subcompose(node_id, content))
1147        } else {
1148            None
1149        };
1150        let children_to_create = subcomposed
1151            .as_ref()
1152            .map_or(view.children.as_slice(), |views| views.as_slice());
1153        let mut child_hashes = SubtreeHashBuilder::new(children_to_create.len());
1154        for (i, child_view) in children_to_create.iter().enumerate() {
1155            let child_id = self.create_node(child_view, Some(node_id), child_depth, i as u32, ctx);
1156            child_ids.push(child_id);
1157            child_hashes.push(self.node_subtree_hashes(child_id));
1158        }
1159
1160        let subtree = child_hashes.finish(hashes);
1161        let subtree_hash = subtree.combined();
1162
1163        let node = self
1164            .nodes
1165            .get_mut(node_id)
1166            .expect("create_node: node just inserted");
1167        node.children = child_ids;
1168        node.subtree_hash = subtree_hash;
1169        node.layout_subtree_hash = subtree.layout;
1170        node.measurement_subtree_hash = subtree.measurement;
1171        node.paint_subtree_hash = subtree.paint;
1172        node.semantics_subtree_hash = subtree.semantics;
1173        self.dirty.insert(node_id);
1174
1175        node_id
1176    }
1177    /// Compute a stable ViewId for a node.
1178    fn compute_view_id(
1179        &self,
1180        view: &View,
1181        _node_id: NodeId,
1182        parent: Option<NodeId>,
1183        index_in_parent: u32,
1184    ) -> ViewId {
1185        if view.id != 0 {
1186            return view.id;
1187        }
1188
1189        let parent_id = parent
1190            .and_then(|p| self.nodes.get(p))
1191            .map(|n| n.view_id)
1192            .unwrap_or(0);
1193
1194        let salt = match view.modifier.key {
1195            Some(key) => key.wrapping_mul(2).wrapping_add(1),
1196            None => (index_in_parent as u64).wrapping_mul(2),
1197        };
1198
1199        let mut id = parent_id.wrapping_mul(31).wrapping_add(salt);
1200        id = id.wrapping_mul(0x9E3779B97F4A7C15);
1201        id ^= id >> 30;
1202
1203        if id == 0 {
1204            id = 1;
1205        }
1206
1207        id
1208    }
1209
1210    /// Recompute the lookup owner and duplicate flag for one id from its
1211    /// member list. The first member owns the id; anything longer is a
1212    /// duplicate the user has to fix with unique `View.id`s.
1213    fn sync_view_id_owner(&mut self, view_id: ViewId) {
1214        let Some(members) = self.view_id_members.get(&view_id) else {
1215            self.view_id_map.remove(&view_id);
1216            self.duplicate_view_ids.remove(&view_id);
1217            return;
1218        };
1219        match members.split_first() {
1220            Some((owner, rest)) => {
1221                self.view_id_map.insert(view_id, *owner);
1222                if rest.is_empty() {
1223                    self.duplicate_view_ids.remove(&view_id);
1224                } else {
1225                    self.duplicate_view_ids.insert(view_id);
1226                }
1227            }
1228            None => {
1229                self.view_id_members.remove(&view_id);
1230                self.view_id_map.remove(&view_id);
1231                self.duplicate_view_ids.remove(&view_id);
1232            }
1233        }
1234    }
1235
1236    fn claim_view_id(&mut self, node_id: NodeId, view_id: ViewId) {
1237        let members = self.view_id_members.entry(view_id).or_default();
1238        if !members.contains(&node_id) {
1239            members.push(node_id);
1240        }
1241        self.sync_view_id_owner(view_id);
1242    }
1243
1244    fn release_view_id(&mut self, node_id: NodeId, view_id: ViewId) {
1245        let empty = match self.view_id_members.get_mut(&view_id) {
1246            Some(members) => {
1247                if let Some(index) = members.iter().position(|member| *member == node_id) {
1248                    members.remove(index);
1249                }
1250                members.is_empty()
1251            }
1252            None => return,
1253        };
1254        if empty {
1255            self.view_id_members.remove(&view_id);
1256        }
1257        self.sync_view_id_owner(view_id);
1258    }
1259
1260    fn assign_view_id(
1261        &mut self,
1262        node_id: NodeId,
1263        old_view_id: ViewId,
1264        requested_view_id: ViewId,
1265        generated: bool,
1266        phase: &str,
1267    ) {
1268        let view_id = if generated {
1269            self.available_generated_view_id(node_id, requested_view_id)
1270        } else {
1271            requested_view_id
1272        };
1273
1274        if old_view_id == view_id && self.view_id_map.get(&view_id).copied() == Some(node_id) {
1275            return;
1276        }
1277
1278        if old_view_id != 0 && old_view_id != view_id {
1279            self.release_view_id(node_id, old_view_id);
1280        }
1281
1282        if let Some(existing) = self
1283            .view_id_members
1284            .get(&view_id)
1285            .and_then(|m| m.first())
1286            .copied()
1287            && existing != node_id
1288        {
1289            log::error!(
1290                "{}: duplicate View.id {}; keeping the first node {:?}",
1291                phase,
1292                view_id,
1293                existing
1294            );
1295        }
1296
1297        self.claim_view_id(node_id, view_id);
1298
1299        if let Some(node) = self.nodes.get_mut(node_id) {
1300            node.view_id = view_id;
1301        }
1302    }
1303
1304    fn available_generated_view_id(&self, node_id: NodeId, requested: ViewId) -> ViewId {
1305        if self
1306            .view_id_map
1307            .get(&requested)
1308            .is_none_or(|existing| *existing == node_id)
1309        {
1310            return requested;
1311        }
1312
1313        let mut candidate = requested;
1314        loop {
1315            candidate = candidate.wrapping_add(1);
1316            if candidate == 0 {
1317                candidate = 1;
1318            }
1319            if self
1320                .view_id_map
1321                .get(&candidate)
1322                .is_none_or(|existing| *existing == node_id)
1323            {
1324                return candidate;
1325            }
1326        }
1327    }
1328
1329    /// Mark a node and its descendants for removal.
1330    fn mark_for_removal(&mut self, node_id: NodeId) {
1331        if !self.removal_seen.insert(node_id) {
1332            return;
1333        }
1334        let Some((view_id, children)) = self.nodes.get_mut(node_id).map(|node| {
1335            node.generation = 0;
1336            let children = std::mem::take(&mut node.children);
1337            (node.view_id, children)
1338        }) else {
1339            return;
1340        };
1341        self.pending_removals.push(node_id);
1342        self.release_view_id(node_id, view_id);
1343        self.dirty.remove(&node_id);
1344        self.dirty_propagated.remove(&node_id);
1345        self.paint_dirty.remove(&node_id);
1346        self.paint_dirty_propagated.remove(&node_id);
1347        self.scope_invalidation_seen.remove(&node_id);
1348        let removed_cache = self.subcompose_cache.remove(&node_id);
1349        drop(removed_cache);
1350        for child_id in children {
1351            self.mark_for_removal(child_id);
1352        }
1353    }
1354
1355    fn collect_explicit_removals(&mut self, ctx: &mut ReconcileContext) {
1356        let pending = std::mem::take(&mut self.pending_removals);
1357        for node_id in pending {
1358            if self.nodes.remove(node_id).is_none() {
1359                continue;
1360            }
1361            ctx.removed += 1;
1362            self.removed_ids.push(node_id);
1363        }
1364        self.removal_seen.clear();
1365    }
1366
1367    /// Set cached layout for a node.
1368    pub fn set_layout(
1369        &mut self,
1370        id: NodeId,
1371        rect: Rect,
1372        screen_rect: Rect,
1373        constraints: LayoutConstraints,
1374    ) {
1375        if let Some(node) = self.nodes.get_mut(id) {
1376            node.layout_cache = Some(LayoutCache {
1377                rect,
1378                screen_rect,
1379                constraints,
1380                generation: self.generation,
1381            });
1382        }
1383    }
1384
1385    /// Iterate over all nodes (parent before children).
1386    pub fn iter(&self) -> impl Iterator<Item = &TreeNode> {
1387        self.nodes.values()
1388    }
1389
1390    /// Iterate over all nodes with their IDs.
1391    pub fn iter_with_ids(&self) -> impl Iterator<Item = (NodeId, &TreeNode)> {
1392        self.nodes.iter()
1393    }
1394
1395    /// Walk the tree from root, calling `f` for each node.
1396    /// Returns early if `f` returns false.
1397    pub fn walk<F>(&self, mut f: F)
1398    where
1399        F: FnMut(&TreeNode, u32) -> bool,
1400    {
1401        if let Some(root_id) = self.root {
1402            self.walk_node(root_id, 0, &mut f);
1403        }
1404    }
1405
1406    fn walk_node<F>(&self, id: NodeId, depth: u32, f: &mut F)
1407    where
1408        F: FnMut(&TreeNode, u32) -> bool,
1409    {
1410        if let Some(node) = self.nodes.get(id) {
1411            if !f(node, depth) {
1412                return;
1413            }
1414
1415            for &child_id in &node.children {
1416                self.walk_node(child_id, depth + 1, f);
1417            }
1418        }
1419    }
1420
1421    /// Get children of a node.
1422    pub fn children(&self, id: NodeId) -> Option<&[NodeId]> {
1423        self.nodes.get(id).map(|n| n.children.as_slice())
1424    }
1425}
1426
1427/// Intersect a `SubcomposeScope` with a `Modifier`'s size-related fields.
1428/// `Modifier::width` / `Modifier::height` are treated as exact sizes (the
1429/// resulting min and max both equal that value). Padding values reduce the
1430/// available content area (matching Compose semantics where padding offsets
1431/// the child constraints). `fill_max_w` / `fill_max_h` are layout-direction
1432/// hints resolved by Taffy and cannot produce a concrete size here. They
1433/// are handled by storing the Taffy-computed size after layout.
1434fn intersect_scope_with_modifier(scope: SubcomposeScope, modifier: &Modifier) -> SubcomposeScope {
1435    let mut s = scope;
1436    // `size()` sets both min and max to the same value (exact size).
1437    if let Some(sz) = modifier.size {
1438        s.min_width = s.min_width.max(sz.width);
1439        s.max_width = s.max_width.min(sz.width);
1440        s.min_height = s.min_height.max(sz.height);
1441        s.max_height = s.max_height.min(sz.height);
1442    }
1443    if let Some(w) = modifier.width {
1444        s.min_width = s.min_width.max(w);
1445        s.max_width = s.max_width.min(w);
1446    }
1447    if let Some(h) = modifier.height {
1448        s.min_height = s.min_height.max(h);
1449        s.max_height = s.max_height.min(h);
1450    }
1451    if let Some(mw) = modifier.min_width {
1452        s.min_width = s.min_width.max(mw);
1453    }
1454    if let Some(mh) = modifier.min_height {
1455        s.min_height = s.min_height.max(mh);
1456    }
1457    if let Some(mw) = modifier.max_width {
1458        s.max_width = s.max_width.min(mw);
1459    }
1460    if let Some(mh) = modifier.max_height {
1461        s.max_height = s.max_height.min(mh);
1462    }
1463    // Padding reduces the available content area (Compose semantics:
1464    // constraints are offset by the padding amount).
1465    if let Some(p) = modifier.padding {
1466        let total = p * 2.0;
1467        s.min_width = (s.min_width - total).max(repose_core::Dp::ZERO);
1468        s.max_width = (s.max_width - total).max(repose_core::Dp::ZERO);
1469        s.min_height = (s.min_height - total).max(repose_core::Dp::ZERO);
1470        s.max_height = (s.max_height - total).max(repose_core::Dp::ZERO);
1471    }
1472    if let Some(pv) = modifier.padding_values {
1473        let h_total = pv.left + pv.right;
1474        let v_total = pv.top + pv.bottom;
1475        s.min_width = (s.min_width - h_total).max(repose_core::Dp::ZERO);
1476        s.max_width = (s.max_width - h_total).max(repose_core::Dp::ZERO);
1477        s.min_height = (s.min_height - v_total).max(repose_core::Dp::ZERO);
1478        s.max_height = (s.max_height - v_total).max(repose_core::Dp::ZERO);
1479    }
1480    if let Some(required) = modifier.required_size {
1481        s.min_width = required.width.max(repose_core::Dp::ZERO);
1482        s.max_width = s.min_width;
1483        s.min_height = required.height.max(repose_core::Dp::ZERO);
1484        s.max_height = s.min_height;
1485    }
1486    if let Some(value) = modifier.required_min_width {
1487        s.min_width = value.max(repose_core::Dp::ZERO);
1488        if s.min_width > s.max_width {
1489            s.max_width = s.min_width;
1490        }
1491    }
1492    if let Some(value) = modifier.required_max_width {
1493        s.max_width = value.max(repose_core::Dp::ZERO);
1494        if s.min_width > s.max_width {
1495            s.min_width = s.max_width;
1496        }
1497    }
1498    if let Some(value) = modifier.required_min_height {
1499        s.min_height = value.max(repose_core::Dp::ZERO);
1500        if s.min_height > s.max_height {
1501            s.max_height = s.min_height;
1502        }
1503    }
1504    if let Some(value) = modifier.required_max_height {
1505        s.max_height = value.max(repose_core::Dp::ZERO);
1506        if s.min_height > s.max_height {
1507            s.min_height = s.max_height;
1508        }
1509    }
1510    if s.min_width > s.max_width {
1511        let coerced = s.max_width.max(repose_core::Dp::ZERO);
1512        s.min_width = coerced;
1513        s.max_width = coerced;
1514    }
1515    if s.min_height > s.max_height {
1516        let coerced = s.max_height.max(repose_core::Dp::ZERO);
1517        s.min_height = coerced;
1518        s.max_height = coerced;
1519    }
1520    SubcomposeScope::new(s.min_width, s.max_width, s.min_height, s.max_height)
1521}
1522
1523#[cfg(test)]
1524mod tests {
1525    use super::*;
1526    use repose_core::{
1527        Color, Dp, DrawStyle, FontStyle, FontWeight, Modifier, Sp, SubcomposeScope, TextAlign,
1528        TextDecoration, UnitExt, View, ViewKind,
1529    };
1530    use std::rc::Rc;
1531    use std::sync::Arc;
1532
1533    fn text_view(text: &str) -> View {
1534        View::new(
1535            0,
1536            ViewKind::Text {
1537                text: text.to_string(),
1538                color: Color::WHITE,
1539                font_size: 16.0.sp(),
1540                soft_wrap: true,
1541                max_lines: None,
1542                overflow: repose_core::TextOverflow::Visible,
1543                font_family: None,
1544                annotations: None,
1545                text_align: TextAlign::Unspecified,
1546                font_weight: FontWeight::NORMAL,
1547                font_style: FontStyle::Normal,
1548                text_decoration: TextDecoration::default(),
1549                letter_spacing: Sp::ZERO,
1550                line_height: Sp::ZERO,
1551                url: None,
1552                font_variation_settings: None,
1553                draw_style: DrawStyle::Fill,
1554            },
1555        )
1556    }
1557
1558    fn box_view() -> View {
1559        View::new(0, ViewKind::Box)
1560    }
1561
1562    #[test]
1563    fn test_create_tree() {
1564        let mut tree = ViewTree::new();
1565
1566        let root = box_view().with_children(vec![text_view("Hello"), text_view("World")]);
1567
1568        tree.update(&root);
1569
1570        assert_eq!(tree.len(), 3); // box + 2 text
1571        assert!(tree.root().is_some());
1572    }
1573
1574    #[test]
1575    fn test_unchanged_tree_skips() {
1576        let mut tree = ViewTree::new();
1577
1578        let root = box_view().with_children(vec![text_view("Hello")]);
1579
1580        tree.update(&root);
1581        let gen1 = tree.generation();
1582
1583        tree.update(&root);
1584        let gen2 = tree.generation();
1585
1586        assert_eq!(gen2, gen1 + 1);
1587        assert!(tree.stats.skipped_nodes > 0);
1588    }
1589
1590    #[test]
1591    fn test_changed_content_reconciles() {
1592        let mut tree = ViewTree::new();
1593
1594        let root1 = box_view().with_children(vec![text_view("Hello")]);
1595
1596        tree.update(&root1);
1597
1598        let root2 = box_view().with_children(vec![text_view("Changed")]);
1599
1600        tree.update(&root2);
1601
1602        assert!(tree.stats.reconciled_nodes > 0);
1603    }
1604
1605    #[test]
1606    fn generated_view_ids_are_unique_and_stable() {
1607        let mut tree = ViewTree::new();
1608        let branch = |text: &str| box_view().with_children(vec![text_view(text)]);
1609        let root = box_view().with_children(vec![
1610            text_view("keyed").modifier(Modifier::new().key(1)),
1611            text_view("unkeyed"),
1612            branch("left"),
1613            branch("right"),
1614        ]);
1615
1616        tree.update(&root);
1617        let first: Vec<(NodeId, u64)> = tree
1618            .iter_with_ids()
1619            .map(|(id, node)| (id, node.view_id))
1620            .collect();
1621        let unique: std::collections::HashSet<u64> = first.iter().map(|(_, id)| *id).collect();
1622        assert_eq!(unique.len(), first.len());
1623        for (node_id, view_id) in &first {
1624            assert_eq!(
1625                tree.get_by_view_id(*view_id).map(|node| node.id),
1626                Some(*node_id)
1627            );
1628        }
1629
1630        tree.update(&root);
1631        let second: Vec<(NodeId, u64)> = tree
1632            .iter_with_ids()
1633            .map(|(id, node)| (id, node.view_id))
1634            .collect();
1635        assert_eq!(first, second);
1636    }
1637
1638    #[test]
1639    fn duplicate_explicit_ids_keep_first_lookup_stable() {
1640        let mut tree = ViewTree::new();
1641        let mut first = text_view("first").modifier(Modifier::new().key(1));
1642        let mut second = text_view("second").modifier(Modifier::new().key(2));
1643        first.id = 42;
1644        second.id = 42;
1645        let root = box_view().with_children(vec![first.clone(), second.clone()]);
1646        let root_id = tree.update(&root);
1647        let first_id = tree.children(root_id).unwrap()[0];
1648        assert_eq!(tree.get_by_view_id(42).map(|node| node.id), Some(first_id));
1649        let root = box_view().with_children(vec![second]);
1650        tree.update(&root);
1651        let second_id = tree.children(tree.root().unwrap()).unwrap()[0];
1652        assert_eq!(tree.get_by_view_id(42).map(|node| node.id), Some(second_id));
1653    }
1654
1655    #[test]
1656    fn replaced_text_selection_is_picked_up() {
1657        let mut tree = ViewTree::new();
1658        let first = repose_core::text::TextSelection::default();
1659        let second = repose_core::text::TextSelection::default();
1660        assert_ne!(first.stable_id(), second.stable_id());
1661
1662        let root = box_view().with_children(vec![
1663            text_view("hi").modifier(Modifier::new().text_selection(first.clone())),
1664        ]);
1665        let node = tree.update(&root);
1666        let node = tree.children(node).unwrap()[0];
1667        tree.set_layout(
1668            node,
1669            Rect::default(),
1670            Rect::default(),
1671            crate::LayoutConstraints::default(),
1672        );
1673        tree.update(&root);
1674        assert!(tree.get(node).unwrap().has_valid_layout());
1675
1676        let replaced = box_view().with_children(vec![
1677            text_view("hi").modifier(Modifier::new().text_selection(second.clone())),
1678        ]);
1679        tree.update(&replaced);
1680
1681        let stored = &tree.get(node).unwrap().modifier.text_selection;
1682        assert_eq!(
1683            stored.as_ref().map(|selection| selection.stable_id()),
1684            Some(second.stable_id())
1685        );
1686        assert!(tree.paint_dirty_nodes().contains(&node));
1687        assert!(tree.get(node).unwrap().has_valid_layout());
1688    }
1689
1690    #[test]
1691    fn explicit_id_change_releases_the_old_id() {
1692        let mut tree = ViewTree::new();
1693        let mut view = text_view("first").modifier(Modifier::new().key(1));
1694        view.id = 7;
1695        let root = box_view().with_children(vec![view.clone()]);
1696        let child = tree.update(&root);
1697        let child = tree.children(child).unwrap()[0];
1698        assert_eq!(tree.get_by_view_id(7).map(|node| node.id), Some(child));
1699
1700        let mut renamed = view;
1701        renamed.id = 9;
1702        tree.update(&box_view().with_children(vec![renamed]));
1703        let child = tree.children(tree.root().unwrap()).unwrap()[0];
1704
1705        assert_eq!(tree.get_by_view_id(7).map(|node| node.id), None);
1706        assert_eq!(tree.get_by_view_id(9).map(|node| node.id), Some(child));
1707    }
1708
1709    #[test]
1710    fn test_keyed_children_stable() {
1711        let mut tree = ViewTree::new();
1712
1713        // Initial: A, B, C
1714        let root1 = box_view().with_children(vec![
1715            text_view("A").modifier(Modifier::new().key(1)),
1716            text_view("B").modifier(Modifier::new().key(2)),
1717            text_view("C").modifier(Modifier::new().key(3)),
1718        ]);
1719
1720        tree.update(&root1);
1721
1722        let _b_view_id = tree
1723            .root()
1724            .and_then(|r| tree.children(r))
1725            .and_then(|c| c.get(1).copied())
1726            .and_then(|id| tree.get(id))
1727            .map(|n| n.view_id);
1728
1729        // Reorder: C, A, B
1730        let root2 = box_view().with_children(vec![
1731            text_view("C").modifier(Modifier::new().key(3)),
1732            text_view("A").modifier(Modifier::new().key(1)),
1733            text_view("B").modifier(Modifier::new().key(2)),
1734        ]);
1735
1736        tree.update(&root2);
1737
1738        // B should have same view_id (key-based stability)
1739        // Note: Implementation detail - the node may be reused
1740        assert_eq!(tree.len(), 4); // Still 4 nodes (box + 3 text)
1741    }
1742
1743    fn subcompose_view<F>(f: F) -> View
1744    where
1745        F: Fn(&SubcomposeScope) -> View + 'static,
1746    {
1747        let content: Arc<dyn Fn(&SubcomposeScope) -> Vec<(u64, View)>> =
1748            Arc::new(move |scope| vec![(0, f(scope))]);
1749        View {
1750            id: 0,
1751            kind: ViewKind::SubcomposeLayout { content },
1752            modifier: Modifier::default(),
1753            children: Vec::new(),
1754            scope_key: None,
1755            semantics: None,
1756        }
1757    }
1758
1759    #[test]
1760    fn callback_identity_updates_handlers_without_layout_reset() {
1761        let mut tree = ViewTree::new();
1762        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1763        let content_calls = calls.clone();
1764        let content: Arc<dyn Fn(&SubcomposeScope) -> Vec<(u64, View)>> = Arc::new(move |_| {
1765            content_calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1766            vec![(0, text_view("callback"))]
1767        });
1768        let make = |callback: Rc<dyn Fn()>| {
1769            let callback = callback.clone();
1770            View {
1771                id: 0,
1772                kind: ViewKind::SubcomposeLayout {
1773                    content: content.clone(),
1774                },
1775                modifier: Modifier::new().on_click(move || callback()),
1776                children: Vec::new(),
1777                scope_key: None,
1778                semantics: None,
1779            }
1780        };
1781        let root = make(Rc::new(|| {}));
1782        let root_id = tree.update(&root);
1783        tree.set_layout(
1784            root_id,
1785            Rect {
1786                x: 0.0,
1787                y: 0.0,
1788                w: 100.0,
1789                h: 100.0,
1790            },
1791            Rect {
1792                x: 0.0,
1793                y: 0.0,
1794                w: 100.0,
1795                h: 100.0,
1796            },
1797            crate::LayoutConstraints::default(),
1798        );
1799        let root = make(Rc::new(|| {}));
1800        tree.update(&root);
1801        let calls_before = calls.load(std::sync::atomic::Ordering::SeqCst);
1802        tree.update(&root);
1803        assert!(tree.get(root_id).unwrap().has_valid_layout());
1804        assert_eq!(
1805            calls.load(std::sync::atomic::Ordering::SeqCst),
1806            calls_before
1807        );
1808        let calls_before = calls.load(std::sync::atomic::Ordering::SeqCst);
1809        let root = make(Rc::new(|| {}));
1810        tree.update(&root);
1811        assert!(tree.get(root_id).unwrap().has_valid_layout());
1812        assert_eq!(
1813            calls.load(std::sync::atomic::Ordering::SeqCst),
1814            calls_before
1815        );
1816        assert!(tree.paint_dirty_nodes().contains(&root_id));
1817    }
1818
1819    #[test]
1820    fn test_subcompose_invokes_content() {
1821        let mut tree = ViewTree::new();
1822        let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1823        let counter2 = counter.clone();
1824
1825        let root = box_view().with_children(vec![subcompose_view(move |_scope| {
1826            counter2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1827            text_view("from subcompose")
1828        })]);
1829
1830        tree.update(&root);
1831
1832        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
1833        assert_eq!(tree.len(), 3); // box + subcompose + text
1834    }
1835
1836    #[test]
1837    fn test_subcompose_receives_scope() {
1838        let mut tree = ViewTree::new();
1839        let captured = Arc::new(std::sync::Mutex::new(None));
1840        let captured2 = captured.clone();
1841
1842        let root = box_view().with_children(vec![subcompose_view(move |scope| {
1843            *captured2.lock().unwrap() = Some(*scope);
1844            text_view("hi")
1845        })]);
1846
1847        tree.set_subcompose_scope(SubcomposeScope::new(Dp(0.0), Dp(360.0), Dp(0.0), Dp(640.0)));
1848        tree.update(&root);
1849
1850        let observed = captured.lock().unwrap().expect("scope captured");
1851        assert_eq!(observed.max_width, Dp(360.0));
1852        assert_eq!(observed.max_height, Dp(640.0));
1853        assert_eq!(observed.min_width, Dp(0.0));
1854        assert_eq!(observed.min_height, Dp(0.0));
1855    }
1856
1857    #[test]
1858    fn zero_subcompose_bounds_are_real() {
1859        let mut tree = ViewTree::new();
1860        let captured = Arc::new(std::sync::Mutex::new(None));
1861        let captured2 = captured.clone();
1862        let root = box_view().with_children(vec![subcompose_view(move |scope| {
1863            *captured2.lock().unwrap() = Some(*scope);
1864            text_view("zero")
1865        })]);
1866        tree.set_subcompose_scope(SubcomposeScope::new(Dp(0.0), Dp(0.0), Dp(0.0), Dp(0.0)));
1867        tree.update(&root);
1868        let scope = captured.lock().unwrap().unwrap();
1869        assert_eq!(scope.min_width, Dp(0.0));
1870        assert_eq!(scope.max_width, Dp(0.0));
1871        assert_eq!(scope.min_height, Dp(0.0));
1872        assert_eq!(scope.max_height, Dp(0.0));
1873    }
1874
1875    #[test]
1876    fn test_subcompose_re_invokes_on_update() {
1877        let mut tree = ViewTree::new();
1878        let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1879        let counter2 = counter.clone();
1880
1881        let root = box_view().with_children(vec![subcompose_view(move |_scope| {
1882            counter2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1883            text_view("hi")
1884        })]);
1885
1886        tree.update(&root);
1887        tree.update(&root);
1888        tree.update(&root);
1889
1890        // Closure should run only on the first update; subsequent updates hit
1891        // the cache because the scope and content are unchanged.
1892        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
1893    }
1894
1895    #[test]
1896    fn test_subcompose_reruns_on_scope_change() {
1897        let mut tree = ViewTree::new();
1898        let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1899        let counter2 = counter.clone();
1900
1901        let root = box_view().with_children(vec![subcompose_view(move |_scope| {
1902            counter2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1903            text_view("hi")
1904        })]);
1905
1906        tree.set_subcompose_scope(SubcomposeScope::new(Dp(0.0), Dp(100.0), Dp(0.0), Dp(100.0)));
1907        tree.update(&root);
1908        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
1909
1910        // Same scope: cache hit.
1911        tree.update(&root);
1912        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
1913
1914        // Scope changed: closure re-runs.
1915        tree.set_subcompose_scope(SubcomposeScope::new(Dp(0.0), Dp(200.0), Dp(0.0), Dp(200.0)));
1916        tree.update(&root);
1917        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 2);
1918    }
1919
1920    #[test]
1921    fn test_subcompose_settles_on_final_scope() {
1922        let mut tree = ViewTree::new();
1923        let root = box_view().with_children(vec![subcompose_view(|scope| {
1924            text_view("content").modifier(Modifier::new().width(scope.max_width))
1925        })]);
1926
1927        for width in [100.0f32, 200.0, 300.0, 400.0, 500.0, 500.0, 500.0, 500.0] {
1928            tree.set_subcompose_scope(SubcomposeScope::new(Dp(0.0), Dp(width), Dp(0.0), Dp(width)));
1929            tree.update(&root);
1930        }
1931
1932        let sub_id = tree.children(tree.root().unwrap()).unwrap()[0];
1933        let child_id = tree.children(sub_id).unwrap()[0];
1934        assert_eq!(
1935            tree.get(child_id).unwrap().modifier.width,
1936            Some(Dp(500.0)),
1937            "closure must end up holding the scope that settled"
1938        );
1939    }
1940
1941    #[test]
1942    fn test_subcompose_scope_ignores_own_measured_size() {
1943        let mut tree = ViewTree::new();
1944        let captured = Arc::new(std::sync::Mutex::new(SubcomposeScope::UNBOUNDED));
1945        let captured2 = captured.clone();
1946        let root = box_view().with_children(vec![subcompose_view(move |scope| {
1947            *captured2.lock().unwrap() = *scope;
1948            text_view("hi")
1949        })]);
1950
1951        tree.set_subcompose_scope(SubcomposeScope::new(
1952            Dp(0.0),
1953            Dp(1000.0),
1954            Dp(0.0),
1955            Dp(1000.0),
1956        ));
1957        let root_id = tree.update(&root);
1958        let sub_id = tree.children(root_id).unwrap()[0];
1959
1960        let narrow = Rect {
1961            x: 0.0,
1962            y: 0.0,
1963            w: 120.0,
1964            h: 40.0,
1965        };
1966        tree.set_layout(sub_id, narrow, narrow, crate::LayoutConstraints::default());
1967        tree.update(&root);
1968
1969        assert_eq!(captured.lock().unwrap().max_width, Dp(1000.0));
1970    }
1971
1972    #[test]
1973    fn test_subcompose_reruns_on_content_change() {
1974        let mut tree = ViewTree::new();
1975        let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1976        let c1 = counter.clone();
1977
1978        let root1 = box_view().with_children(vec![subcompose_view(move |_scope| {
1979            c1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1980            text_view("hi")
1981        })]);
1982
1983        tree.update(&root1);
1984        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
1985
1986        // Same content: cache hit.
1987        tree.update(&root1);
1988        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
1989
1990        // Changed modifier: closure re-runs.
1991        let c2 = counter.clone();
1992        let root2 = box_view().with_children(vec![
1993            subcompose_view(move |_scope| {
1994                c2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1995                text_view("hi")
1996            })
1997            .modifier(Modifier::new().padding(4.0.dp())),
1998        ]);
1999
2000        tree.update(&root2);
2001        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 2);
2002    }
2003
2004    #[test]
2005    fn test_subcompose_cache_drops_on_node_removal() {
2006        let mut tree = ViewTree::new();
2007        tree.set_subcompose_scope(SubcomposeScope::new(Dp(0.0), Dp(100.0), Dp(0.0), Dp(100.0)));
2008
2009        // First root has a SubcomposeLayout child.
2010        let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
2011        let c1 = counter.clone();
2012        let root_with_sub = box_view().with_children(vec![subcompose_view(move |_scope| {
2013            c1.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2014            text_view("hi")
2015        })]);
2016
2017        tree.update(&root_with_sub);
2018        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 1);
2019
2020        // Swap to a root without the SubcomposeLayout - the old node should be
2021        // garbage-collected and its cache entry dropped.
2022        let root_no_sub = box_view().with_children(vec![text_view("plain")]);
2023        tree.update(&root_no_sub);
2024        assert_eq!(tree.len(), 2);
2025
2026        // Bring the SubcomposeLayout back - it must run the closure again
2027        // because the cache entry was dropped during GC.
2028        let c2 = counter.clone();
2029        let root_with_sub_again = box_view().with_children(vec![subcompose_view(move |_scope| {
2030            c2.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2031            text_view("hi")
2032        })]);
2033
2034        tree.update(&root_with_sub_again);
2035        assert_eq!(counter.load(std::sync::atomic::Ordering::SeqCst), 2);
2036    }
2037
2038    fn multi_slot_view<F>(f: F) -> View
2039    where
2040        F: Fn(&SubcomposeScope) -> Vec<(u64, View)> + 'static,
2041    {
2042        let content: Arc<dyn Fn(&SubcomposeScope) -> Vec<(u64, View)>> = Arc::new(f);
2043        View {
2044            id: 0,
2045            kind: ViewKind::SubcomposeLayout { content },
2046            modifier: Modifier::default(),
2047            children: Vec::new(),
2048            scope_key: None,
2049            semantics: None,
2050        }
2051    }
2052
2053    #[test]
2054    fn test_subcompose_multi_slot_produces_multiple_children() {
2055        let mut tree = ViewTree::new();
2056        let root = box_view().with_children(vec![multi_slot_view(|_scope| {
2057            vec![
2058                (0, text_view("a")),
2059                (1, text_view("b")),
2060                (2, text_view("c")),
2061            ]
2062        })]);
2063
2064        tree.update(&root);
2065
2066        // box + subcompose + 3 texts
2067        assert_eq!(tree.len(), 5);
2068        let sub_id = tree
2069            .root()
2070            .and_then(|r| tree.children(r))
2071            .and_then(|c| c.first().copied())
2072            .expect("subcompose node");
2073        let sub_children = tree.children(sub_id).expect("subcompose has children");
2074        assert_eq!(sub_children.len(), 3);
2075    }
2076
2077    #[test]
2078    fn test_subcompose_multi_slot_preserves_identity_across_removal() {
2079        let mut tree = ViewTree::new();
2080
2081        // 3 slots: 0, 1, 2
2082        let root3 = box_view().with_children(vec![multi_slot_view(|_scope| {
2083            vec![
2084                (0, text_view("a")),
2085                (1, text_view("b")),
2086                (2, text_view("c")),
2087            ]
2088        })]);
2089        tree.update(&root3);
2090
2091        let sub_id = tree
2092            .root()
2093            .and_then(|r| tree.children(r))
2094            .and_then(|c| c.first().copied())
2095            .expect("subcompose node");
2096        let before = tree.children(sub_id).expect("children").to_vec();
2097        let a_node = before[0];
2098        let b_node = before[1];
2099        let c_node = before[2];
2100
2101        // 2 slots: 0, 2 (middle removed). The Modifier change (padding) forces
2102        // the subcompose cache to invalidate so the new closure runs.
2103        let root2 = box_view().with_children(vec![
2104            multi_slot_view(|_scope| vec![(0, text_view("a")), (2, text_view("c"))])
2105                .modifier(Modifier::new().padding(4.0.dp())),
2106        ]);
2107        tree.update(&root2);
2108
2109        let after = tree.children(sub_id).expect("children after");
2110        assert_eq!(after.len(), 2);
2111        // Slot 0 (a) and slot 2 (c) should keep their NodeId.
2112        assert_eq!(after[0], a_node);
2113        assert_eq!(after[1], c_node);
2114        // Slot 1 (b) should be gone.
2115        assert!(tree.get(b_node).is_none());
2116    }
2117
2118    #[test]
2119    fn test_subcompose_ancestor_modifier_narrows_scope() {
2120        let mut tree = ViewTree::new();
2121        tree.set_subcompose_scope(SubcomposeScope::new(
2122            Dp(0.0),
2123            Dp(1000.0),
2124            Dp(0.0),
2125            Dp(1000.0),
2126        ));
2127
2128        let captured = Arc::new(std::sync::Mutex::new(SubcomposeScope::UNBOUNDED));
2129        let cap2 = captured.clone();
2130
2131        // SubcomposeLayout inside a Box with width(200.dp) - the closure should
2132        // see max_width == 200.
2133        let sub = multi_slot_view(move |scope| {
2134            *cap2.lock().unwrap() = *scope;
2135            vec![(0, text_view("hi"))]
2136        });
2137        let root = box_view()
2138            .modifier(Modifier::new().width(200.0.dp()))
2139            .with_children(vec![sub]);
2140
2141        tree.update(&root);
2142
2143        let observed = *captured.lock().unwrap();
2144        assert_eq!(observed.max_width, Dp(200.0));
2145    }
2146
2147    #[test]
2148    fn test_subcompose_chained_ancestor_constraints_intersect() {
2149        let mut tree = ViewTree::new();
2150        tree.set_subcompose_scope(SubcomposeScope::new(
2151            Dp(0.0),
2152            Dp(1000.0),
2153            Dp(0.0),
2154            Dp(1000.0),
2155        ));
2156
2157        let captured = Arc::new(std::sync::Mutex::new(SubcomposeScope::UNBOUNDED));
2158        let cap2 = captured.clone();
2159
2160        let sub = multi_slot_view(move |scope| {
2161            *cap2.lock().unwrap() = *scope;
2162            vec![(0, text_view("hi"))]
2163        });
2164        // Box(width=400) -> Box(max_width=300) -> SubcomposeLayout.
2165        // The intersection should give max_width = 300.
2166        let root = box_view()
2167            .modifier(Modifier::new().width(400.0.dp()))
2168            .with_children(vec![
2169                box_view()
2170                    .modifier(Modifier::new().max_width(300.0.dp()))
2171                    .with_children(vec![sub]),
2172            ]);
2173
2174        tree.update(&root);
2175
2176        let observed = *captured.lock().unwrap();
2177        assert_eq!(observed.max_width, Dp(300.0));
2178    }
2179
2180    #[test]
2181    // Test-only: the view is shared across closures on one thread; Arc is structural.
2182    #[allow(clippy::arc_with_non_send_sync)]
2183    fn test_subcompose_nested_layouts_inherit_narrowed_scope() {
2184        let mut tree = ViewTree::new();
2185        tree.set_subcompose_scope(SubcomposeScope::new(
2186            Dp(0.0),
2187            Dp(1000.0),
2188            Dp(0.0),
2189            Dp(1000.0),
2190        ));
2191
2192        let outer_captured = Arc::new(std::sync::Mutex::new(SubcomposeScope::UNBOUNDED));
2193        let inner_captured = Arc::new(std::sync::Mutex::new(SubcomposeScope::UNBOUNDED));
2194        let outer2 = outer_captured.clone();
2195        let inner2 = inner_captured.clone();
2196
2197        // Outer SubcomposeLayout(width=400) hosts an inner SubcomposeLayout.
2198        // The inner closure should observe max_width = 400, not 1000.
2199        let inner = Arc::new(multi_slot_view(move |scope| {
2200            *inner2.lock().unwrap() = *scope;
2201            vec![(0, text_view("inner"))]
2202        }));
2203        let inner_clone = inner.clone();
2204        let outer = multi_slot_view(move |scope| {
2205            *outer2.lock().unwrap() = *scope;
2206            vec![(0, (*inner_clone).clone())]
2207        })
2208        .modifier(Modifier::new().width(400.0.dp()));
2209        let root = box_view().with_children(vec![outer]);
2210
2211        tree.update(&root);
2212
2213        let outer_obs = *outer_captured.lock().unwrap();
2214        let inner_obs = *inner_captured.lock().unwrap();
2215        assert_eq!(outer_obs.max_width, Dp(400.0));
2216        assert_eq!(inner_obs.max_width, Dp(400.0));
2217    }
2218}