Skip to main content

cranpose_ui/widgets/nodes/
layout_node.rs

1use crate::{
2    layout::MeasuredNode,
3    modifier::{
4        Modifier, ModifierChainHandle, ModifierLocalSource, ModifierLocalToken,
5        ModifierLocalsHandle, ModifierNodeSlices, Point, ResolvedModifierLocal, ResolvedModifiers,
6        Size,
7    },
8};
9use cranpose_core::{Node, NodeId};
10use cranpose_foundation::{
11    InvalidationKind, ModifierInvalidation, NodeCapabilities, SemanticsConfiguration,
12};
13use cranpose_ui_layout::{Constraints, MeasurePolicy};
14use std::any::TypeId;
15use std::cell::{Cell, RefCell};
16use std::collections::HashMap;
17use std::hash::{Hash, Hasher};
18use std::rc::Rc;
19
20/// Retained layout state for a LayoutNode.
21/// This mirrors Jetpack Compose's approach where each node stores its own
22/// measured size and placed position, eliminating the need for per-frame
23/// LayoutTree reconstruction.
24#[derive(Clone, Debug)]
25pub struct LayoutState {
26    /// The measured size of this node (width, height).
27    pub size: Size,
28    /// Position relative to parent's content origin.
29    pub position: Point,
30    /// True if this node has been placed in the current layout pass.
31    pub is_placed: bool,
32    /// The constraints used for the last measurement.
33    pub measurement_constraints: Constraints,
34    /// Offset of the content box relative to the node origin (e.g. due to padding).
35    pub content_offset: Point,
36}
37
38impl Default for LayoutState {
39    fn default() -> Self {
40        Self {
41            size: Size::default(),
42            position: Point::default(),
43            is_placed: false,
44            measurement_constraints: Constraints {
45                min_width: 0.0,
46                max_width: f32::INFINITY,
47                min_height: 0.0,
48                max_height: f32::INFINITY,
49            },
50            content_offset: Point::default(),
51        }
52    }
53}
54
55#[derive(Clone)]
56struct MeasurementCacheEntry {
57    constraints: Constraints,
58    measured: Rc<MeasuredNode>,
59}
60
61#[derive(Clone, Copy, Debug)]
62pub enum IntrinsicKind {
63    MinWidth(f32),
64    MaxWidth(f32),
65    MinHeight(f32),
66    MaxHeight(f32),
67}
68
69impl IntrinsicKind {
70    fn discriminant(&self) -> u8 {
71        match self {
72            IntrinsicKind::MinWidth(_) => 0,
73            IntrinsicKind::MaxWidth(_) => 1,
74            IntrinsicKind::MinHeight(_) => 2,
75            IntrinsicKind::MaxHeight(_) => 3,
76        }
77    }
78
79    fn value_bits(&self) -> u32 {
80        match self {
81            IntrinsicKind::MinWidth(value)
82            | IntrinsicKind::MaxWidth(value)
83            | IntrinsicKind::MinHeight(value)
84            | IntrinsicKind::MaxHeight(value) => value.to_bits(),
85        }
86    }
87}
88
89impl PartialEq for IntrinsicKind {
90    fn eq(&self, other: &Self) -> bool {
91        self.discriminant() == other.discriminant() && self.value_bits() == other.value_bits()
92    }
93}
94
95impl Eq for IntrinsicKind {}
96
97impl Hash for IntrinsicKind {
98    fn hash<H: Hasher>(&self, state: &mut H) {
99        self.discriminant().hash(state);
100        self.value_bits().hash(state);
101    }
102}
103
104#[derive(Default)]
105struct NodeCacheState {
106    epoch: u64,
107    measurements: Vec<MeasurementCacheEntry>,
108    intrinsics: Vec<(IntrinsicKind, f32)>,
109}
110
111#[derive(Clone, Default)]
112pub(crate) struct LayoutNodeCacheHandles {
113    state: Rc<RefCell<NodeCacheState>>,
114}
115
116impl LayoutNodeCacheHandles {
117    pub(crate) fn clear(&self) {
118        let mut state = self.state.borrow_mut();
119        state.measurements.clear();
120        state.intrinsics.clear();
121        state.epoch = 0;
122    }
123
124    pub(crate) fn activate(&self, epoch: u64) {
125        let mut state = self.state.borrow_mut();
126        if state.epoch != epoch {
127            state.measurements.clear();
128            state.intrinsics.clear();
129            state.epoch = epoch;
130        }
131    }
132
133    pub(crate) fn epoch(&self) -> u64 {
134        self.state.borrow().epoch
135    }
136
137    pub(crate) fn get_measurement(&self, constraints: Constraints) -> Option<Rc<MeasuredNode>> {
138        let state = self.state.borrow();
139        state
140            .measurements
141            .iter()
142            .find(|entry| entry.constraints == constraints)
143            .map(|entry| Rc::clone(&entry.measured))
144    }
145
146    pub(crate) fn store_measurement(&self, constraints: Constraints, measured: Rc<MeasuredNode>) {
147        let mut state = self.state.borrow_mut();
148        if let Some(entry) = state
149            .measurements
150            .iter_mut()
151            .find(|entry| entry.constraints == constraints)
152        {
153            entry.measured = measured;
154        } else {
155            state.measurements.push(MeasurementCacheEntry {
156                constraints,
157                measured,
158            });
159        }
160    }
161
162    pub(crate) fn get_intrinsic(&self, kind: &IntrinsicKind) -> Option<f32> {
163        let state = self.state.borrow();
164        state
165            .intrinsics
166            .iter()
167            .find(|(stored_kind, _)| stored_kind == kind)
168            .map(|(_, value)| *value)
169    }
170
171    pub(crate) fn store_intrinsic(&self, kind: IntrinsicKind, value: f32) {
172        let mut state = self.state.borrow_mut();
173        if let Some((_, existing)) = state
174            .intrinsics
175            .iter_mut()
176            .find(|(stored_kind, _)| stored_kind == &kind)
177        {
178            *existing = value;
179        } else {
180            state.intrinsics.push((kind, value));
181        }
182    }
183}
184
185pub struct LayoutNode {
186    pub modifier: Modifier,
187    modifier_chain: ModifierChainHandle,
188    resolved_modifiers: ResolvedModifiers,
189    modifier_capabilities: NodeCapabilities,
190    modifier_child_capabilities: NodeCapabilities,
191    pub measure_policy: Rc<dyn MeasurePolicy>,
192    /// The actual children of this node (folded view - includes virtual nodes as-is)
193    pub children: Vec<NodeId>,
194    cache: LayoutNodeCacheHandles,
195    // Dirty flags for selective measure/layout/render
196    needs_measure: Cell<bool>,
197    needs_layout: Cell<bool>,
198    needs_semantics: Cell<bool>,
199    needs_redraw: Cell<bool>,
200    needs_pointer_pass: Cell<bool>,
201    needs_focus_sync: Cell<bool>,
202    /// Parent for dirty flag bubbling (skips virtual nodes)
203    parent: Cell<Option<NodeId>>,
204    /// Direct parent in the tree (may be virtual)
205    folded_parent: Cell<Option<NodeId>>,
206    // Node's own ID (set by applier after creation)
207    id: Cell<Option<NodeId>>,
208    debug_modifiers: Cell<bool>,
209    /// Virtual node flag - virtual nodes are transparent containers for subcomposition
210    /// Their children are flattened into the parent's children list for measurement
211    is_virtual: bool,
212    /// Count of virtual children (for lazy unfolded children computation)
213    virtual_children_count: Cell<usize>,
214
215    modifier_slices_snapshot: RefCell<Rc<ModifierNodeSlices>>,
216    modifier_slices_dirty: Cell<bool>,
217
218    /// Retained layout state (size, position) for this node.
219    /// Updated by measure/place and read by renderer.
220    /// Wrapped in Rc to ensure state is shared across clones (e.g. SubcomposeLayout usage).
221    layout_state: Rc<RefCell<LayoutState>>,
222}
223
224pub(crate) const RECYCLED_LAYOUT_NODE_POOL_LIMIT: usize = 128;
225
226thread_local! {
227    static EMPTY_MEASURE_POLICY: Rc<dyn MeasurePolicy> =
228        Rc::new(crate::layout::policies::EmptyMeasurePolicy);
229}
230
231fn empty_measure_policy() -> Rc<dyn MeasurePolicy> {
232    EMPTY_MEASURE_POLICY.with(Rc::clone)
233}
234
235impl LayoutNode {
236    pub fn new(modifier: Modifier, measure_policy: Rc<dyn MeasurePolicy>) -> Self {
237        Self::new_with_virtual(modifier, measure_policy, false)
238    }
239
240    /// Create a virtual LayoutNode for subcomposition slot containers.
241    /// Virtual nodes are transparent - their children are flattened into parent's children list.
242    pub fn new_virtual() -> Self {
243        Self::new_with_virtual(Modifier::empty(), empty_measure_policy(), true)
244    }
245
246    fn new_recycled_shell(is_virtual: bool) -> Self {
247        let mut shell =
248            Self::new_with_virtual(Modifier::empty(), empty_measure_policy(), is_virtual);
249        shell.needs_measure.set(false);
250        shell.needs_layout.set(false);
251        shell.needs_semantics.set(false);
252        shell.needs_redraw.set(false);
253        shell.needs_pointer_pass.set(false);
254        shell.needs_focus_sync.set(false);
255        shell.parent.set(None);
256        shell.folded_parent.set(None);
257        shell.id.set(None);
258        shell.debug_modifiers.set(false);
259        shell.virtual_children_count.set(0);
260        shell.cache = LayoutNodeCacheHandles::default();
261        shell.modifier_slices_snapshot = RefCell::new(Rc::default());
262        shell.modifier_slices_dirty = Cell::new(true);
263        shell.layout_state = Rc::new(RefCell::new(LayoutState::default()));
264        shell
265    }
266
267    fn new_with_virtual(
268        modifier: Modifier,
269        measure_policy: Rc<dyn MeasurePolicy>,
270        is_virtual: bool,
271    ) -> Self {
272        let mut node = Self {
273            modifier,
274            modifier_chain: ModifierChainHandle::new(),
275            resolved_modifiers: ResolvedModifiers::default(),
276            modifier_capabilities: NodeCapabilities::default(),
277            modifier_child_capabilities: NodeCapabilities::default(),
278            measure_policy,
279            children: Vec::new(),
280            cache: LayoutNodeCacheHandles::default(),
281            needs_measure: Cell::new(true), // New nodes need initial measure
282            needs_layout: Cell::new(true),  // New nodes need initial layout
283            needs_semantics: Cell::new(true), // Semantics snapshot needs initial build
284            needs_redraw: Cell::new(true),  // First render should draw the node
285            needs_pointer_pass: Cell::new(false),
286            needs_focus_sync: Cell::new(false),
287            parent: Cell::new(None),        // Non-virtual parent for bubbling
288            folded_parent: Cell::new(None), // Direct parent (may be virtual)
289            id: Cell::new(None),            // ID set by applier after creation
290            debug_modifiers: Cell::new(false),
291            is_virtual,
292            virtual_children_count: Cell::new(0),
293            modifier_slices_snapshot: RefCell::new(Rc::default()),
294            modifier_slices_dirty: Cell::new(true),
295            layout_state: Rc::new(RefCell::new(LayoutState::default())),
296        };
297        node.sync_modifier_chain();
298        node
299    }
300
301    pub fn set_modifier(&mut self, modifier: Modifier) {
302        // Always sync the modifier chain because element equality is used for node
303        // matching/reuse, not for skipping updates. Closures may capture updated
304        // state values that need to be passed to nodes even when the Modifier
305        // compares as equal. This matches Jetpack Compose where update() is always
306        // called on matched nodes.
307        let modifier_changed = !self.modifier.structural_eq(&modifier);
308        self.modifier = modifier;
309        self.sync_modifier_chain();
310        if modifier_changed {
311            self.cache.clear();
312            self.request_semantics_update();
313        }
314    }
315
316    fn sync_modifier_chain(&mut self) {
317        let prev_caps = self.modifier_capabilities;
318        let start_parent = self.parent();
319        let mut resolver = move |token: ModifierLocalToken| {
320            resolve_modifier_local_from_parent_chain(start_parent, token)
321        };
322        self.modifier_chain
323            .set_debug_logging(self.debug_modifiers.get());
324        self.modifier_chain.set_node_id(self.id.get());
325        let modifier_local_invalidations = self
326            .modifier_chain
327            .update_with_resolver(&self.modifier, &mut resolver);
328        self.resolved_modifiers = self.modifier_chain.resolved_modifiers();
329        self.modifier_capabilities = self.modifier_chain.capabilities();
330        self.modifier_child_capabilities = self.modifier_chain.aggregate_child_capabilities();
331
332        self.update_modifier_slices_cache();
333
334        let mut invalidations = self.modifier_chain.take_invalidations();
335        invalidations.extend(modifier_local_invalidations);
336        self.dispatch_modifier_invalidations_with_prev(&invalidations, prev_caps);
337        self.refresh_registry_state();
338    }
339
340    fn update_modifier_slices_cache(&self) {
341        use crate::modifier::collect_modifier_slices_into;
342
343        let mut snapshot = self.modifier_slices_snapshot.borrow_mut();
344        collect_modifier_slices_into(self.modifier_chain.chain(), Rc::make_mut(&mut snapshot));
345        self.modifier_slices_dirty.set(false);
346    }
347
348    #[cfg(test)]
349    fn dispatch_modifier_invalidations(&self, invalidations: &[ModifierInvalidation]) {
350        self.dispatch_modifier_invalidations_with_prev(invalidations, NodeCapabilities::empty());
351    }
352
353    fn dispatch_modifier_invalidations_with_prev(
354        &self,
355        invalidations: &[ModifierInvalidation],
356        prev_caps: NodeCapabilities,
357    ) {
358        let curr_caps = self.modifier_capabilities;
359        for invalidation in invalidations {
360            self.modifier_slices_dirty.set(true);
361            match invalidation.kind() {
362                InvalidationKind::Layout => {
363                    if curr_caps.contains(NodeCapabilities::LAYOUT)
364                        || prev_caps.contains(NodeCapabilities::LAYOUT)
365                    {
366                        self.mark_needs_measure();
367                        if let Some(id) = self.id.get() {
368                            let inside_composition =
369                                cranpose_core::composer_context::try_with_composer(|_| ())
370                                    .is_some();
371                            if !inside_composition {
372                                crate::schedule_layout_repass(id);
373                            }
374                        }
375                    }
376                }
377                InvalidationKind::Draw => {
378                    if curr_caps.contains(NodeCapabilities::DRAW)
379                        || prev_caps.contains(NodeCapabilities::DRAW)
380                    {
381                        self.mark_needs_redraw();
382                    }
383                }
384                InvalidationKind::PointerInput => {
385                    if curr_caps.contains(NodeCapabilities::POINTER_INPUT)
386                        || prev_caps.contains(NodeCapabilities::POINTER_INPUT)
387                    {
388                        self.mark_needs_pointer_pass();
389                        crate::request_pointer_invalidation();
390                        // Schedule pointer repass for this node
391                        if let Some(id) = self.id.get() {
392                            crate::schedule_pointer_repass(id);
393                        }
394                    }
395                }
396                InvalidationKind::Semantics => {
397                    self.request_semantics_update();
398                }
399                InvalidationKind::Focus => {
400                    if curr_caps.contains(NodeCapabilities::FOCUS)
401                        || prev_caps.contains(NodeCapabilities::FOCUS)
402                    {
403                        self.mark_needs_focus_sync();
404                        crate::request_focus_invalidation();
405                        // Schedule focus invalidation for this node
406                        if let Some(id) = self.id.get() {
407                            crate::schedule_focus_invalidation(id);
408                        }
409                    }
410                }
411            }
412        }
413    }
414
415    pub fn set_measure_policy(&mut self, policy: Rc<dyn MeasurePolicy>) {
416        // Only mark dirty if policy actually changed (pointer comparison)
417        if !Rc::ptr_eq(&self.measure_policy, &policy) {
418            self.measure_policy = policy;
419            self.cache.clear();
420            self.mark_needs_measure();
421            if let Some(id) = self.id.get() {
422                cranpose_core::bubble_measure_dirty_in_composer(id);
423            }
424        }
425    }
426
427    /// Mark this node as needing measure. Also marks it as needing layout.
428    pub fn mark_needs_measure(&self) {
429        self.needs_measure.set(true);
430        self.needs_layout.set(true);
431    }
432
433    /// Mark this node as needing layout (but not necessarily measure).
434    pub fn mark_needs_layout(&self) {
435        self.needs_layout.set(true);
436    }
437
438    /// Mark this node as needing redraw without forcing measure/layout.
439    pub fn mark_needs_redraw(&self) {
440        self.needs_redraw.set(true);
441        if let Some(id) = self.id.get() {
442            crate::schedule_draw_repass(id);
443        }
444        crate::request_render_invalidation();
445    }
446
447    /// Check if this node needs measure.
448    pub fn needs_measure(&self) -> bool {
449        self.needs_measure.get()
450    }
451
452    /// Check if this node needs layout.
453    pub fn needs_layout(&self) -> bool {
454        self.needs_layout.get()
455    }
456
457    /// Mark this node as needing semantics recomputation.
458    pub fn mark_needs_semantics(&self) {
459        self.needs_semantics.set(true);
460    }
461
462    /// Clear the semantics dirty flag after rebuilding semantics.
463    pub(crate) fn clear_needs_semantics(&self) {
464        self.needs_semantics.set(false);
465    }
466
467    /// Returns true when semantics need to be recomputed.
468    pub fn needs_semantics(&self) -> bool {
469        self.needs_semantics.get()
470    }
471
472    /// Returns true when this node requested a redraw since the last render pass.
473    pub fn needs_redraw(&self) -> bool {
474        self.needs_redraw.get()
475    }
476
477    pub fn clear_needs_redraw(&self) {
478        self.needs_redraw.set(false);
479    }
480
481    fn request_semantics_update(&self) {
482        let already_dirty = self.needs_semantics.replace(true);
483        if already_dirty {
484            return;
485        }
486
487        if let Some(id) = self.id.get() {
488            cranpose_core::queue_semantics_invalidation(id);
489        }
490    }
491
492    /// Clear the measure dirty flag after measuring.
493    pub(crate) fn clear_needs_measure(&self) {
494        self.needs_measure.set(false);
495    }
496
497    /// Clear the layout dirty flag after laying out.
498    pub(crate) fn clear_needs_layout(&self) {
499        self.needs_layout.set(false);
500    }
501
502    /// Marks this node as needing a fresh pointer-input pass.
503    pub fn mark_needs_pointer_pass(&self) {
504        self.needs_pointer_pass.set(true);
505    }
506
507    /// Returns true when pointer-input state needs to be recomputed.
508    pub fn needs_pointer_pass(&self) -> bool {
509        self.needs_pointer_pass.get()
510    }
511
512    /// Clears the pointer-input dirty flag after hosts service it.
513    pub fn clear_needs_pointer_pass(&self) {
514        self.needs_pointer_pass.set(false);
515    }
516
517    /// Marks this node as needing a focus synchronization.
518    pub fn mark_needs_focus_sync(&self) {
519        self.needs_focus_sync.set(true);
520    }
521
522    /// Returns true when focus state needs to be synchronized.
523    pub fn needs_focus_sync(&self) -> bool {
524        self.needs_focus_sync.get()
525    }
526
527    /// Clears the focus dirty flag after the focus manager processes it.
528    pub fn clear_needs_focus_sync(&self) {
529        self.needs_focus_sync.set(false);
530    }
531
532    /// Set this node's ID (called by applier after creation).
533    pub fn set_node_id(&mut self, id: NodeId) {
534        if let Some(existing) = self.id.replace(Some(id)) {
535            unregister_layout_node(existing);
536        }
537        register_layout_node(id, self);
538        self.refresh_registry_state();
539
540        // Propagate the ID to the modifier chain. This triggers a lifecycle update
541        // for nodes that depend on the node ID for invalidation (e.g., ScrollNode).
542        self.modifier_chain.set_node_id(Some(id));
543    }
544
545    /// Get this node's ID.
546    pub fn node_id(&self) -> Option<NodeId> {
547        self.id.get()
548    }
549
550    /// Set this node's parent (called when node is added as child).
551    /// Sets both folded_parent (direct) and parent (first non-virtual ancestor for bubbling).
552    pub fn set_parent(&self, parent: NodeId) {
553        self.folded_parent.set(Some(parent));
554        // For now, parent = folded_parent. Virtual parent skipping requires applier access.
555        // The actual virtual-skipping happens in bubble_measure_dirty via applier traversal.
556        self.parent.set(Some(parent));
557        self.refresh_registry_state();
558    }
559
560    /// Clear this node's parent (called when node is removed from parent).
561    pub fn clear_parent(&self) {
562        self.folded_parent.set(None);
563        self.parent.set(None);
564        self.refresh_registry_state();
565    }
566
567    /// Get this node's parent for dirty flag bubbling (may skip virtual nodes).
568    pub fn parent(&self) -> Option<NodeId> {
569        self.parent.get()
570    }
571
572    /// Get this node's direct parent (may be a virtual node).
573    pub fn folded_parent(&self) -> Option<NodeId> {
574        self.folded_parent.get()
575    }
576
577    /// Returns true if this is a virtual node (transparent container for subcomposition).
578    pub fn is_virtual(&self) -> bool {
579        self.is_virtual
580    }
581
582    pub(crate) fn cache_handles(&self) -> LayoutNodeCacheHandles {
583        self.cache.clone()
584    }
585
586    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
587        self.resolved_modifiers
588    }
589
590    pub fn modifier_capabilities(&self) -> NodeCapabilities {
591        self.modifier_capabilities
592    }
593
594    pub fn modifier_child_capabilities(&self) -> NodeCapabilities {
595        self.modifier_child_capabilities
596    }
597
598    pub fn set_debug_modifiers(&mut self, enabled: bool) {
599        self.debug_modifiers.set(enabled);
600        self.modifier_chain.set_debug_logging(enabled);
601    }
602
603    pub fn debug_modifiers_enabled(&self) -> bool {
604        self.debug_modifiers.get()
605    }
606
607    pub fn modifier_locals_handle(&self) -> ModifierLocalsHandle {
608        self.modifier_chain.modifier_locals_handle()
609    }
610
611    pub fn has_layout_modifier_nodes(&self) -> bool {
612        self.modifier_capabilities
613            .contains(NodeCapabilities::LAYOUT)
614    }
615
616    pub fn has_draw_modifier_nodes(&self) -> bool {
617        self.modifier_capabilities.contains(NodeCapabilities::DRAW)
618    }
619
620    pub fn has_pointer_input_modifier_nodes(&self) -> bool {
621        self.modifier_capabilities
622            .contains(NodeCapabilities::POINTER_INPUT)
623    }
624
625    pub fn has_semantics_modifier_nodes(&self) -> bool {
626        self.modifier_capabilities
627            .contains(NodeCapabilities::SEMANTICS)
628    }
629
630    pub fn has_focus_modifier_nodes(&self) -> bool {
631        self.modifier_capabilities.contains(NodeCapabilities::FOCUS)
632    }
633
634    fn refresh_registry_state(&self) {
635        if let Some(id) = self.id.get() {
636            let parent = self.parent();
637            let capabilities = self.modifier_child_capabilities();
638            let modifier_locals = self.modifier_locals_handle();
639            LAYOUT_NODE_REGISTRY.with(|registry| {
640                if let Some(entry) = registry.borrow_mut().get_mut(&id) {
641                    entry.parent = parent;
642                    entry.modifier_child_capabilities = capabilities;
643                    entry.modifier_locals = modifier_locals;
644                }
645            });
646        }
647    }
648
649    pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
650        if self.modifier_slices_dirty.get() {
651            self.update_modifier_slices_cache();
652        }
653        self.modifier_slices_snapshot.borrow().clone()
654    }
655
656    // ═══════════════════════════════════════════════════════════════════════
657    // Retained Layout State API
658    // ═══════════════════════════════════════════════════════════════════════
659
660    /// Returns a clone of the current layout state.
661    pub fn layout_state(&self) -> LayoutState {
662        self.layout_state.borrow().clone()
663    }
664
665    /// Returns the measured size of this node.
666    pub fn measured_size(&self) -> Size {
667        self.layout_state.borrow().size
668    }
669
670    /// Returns the position of this node relative to its parent.
671    pub fn position(&self) -> Point {
672        self.layout_state.borrow().position
673    }
674
675    /// Returns true if this node has been placed in the current layout pass.
676    pub fn is_placed(&self) -> bool {
677        self.layout_state.borrow().is_placed
678    }
679
680    /// Updates the measured size of this node. Called during measurement.
681    pub fn set_measured_size(&self, size: Size) {
682        let mut state = self.layout_state.borrow_mut();
683        state.size = size;
684    }
685
686    /// Updates the position of this node. Called during placement.
687    pub fn set_position(&self, position: Point) {
688        let mut state = self.layout_state.borrow_mut();
689        state.position = position;
690        state.is_placed = true;
691    }
692
693    /// Records the constraints used for measurement. Used for relayout optimization.
694    pub fn set_measurement_constraints(&self, constraints: Constraints) {
695        self.layout_state.borrow_mut().measurement_constraints = constraints;
696    }
697
698    /// Records the content offset (e.g. from padding).
699    pub fn set_content_offset(&self, offset: Point) {
700        self.layout_state.borrow_mut().content_offset = offset;
701    }
702
703    /// Clears the is_placed flag. Called at the start of a layout pass.
704    pub fn clear_placed(&self) {
705        self.layout_state.borrow_mut().is_placed = false;
706    }
707
708    pub fn semantics_configuration(&self) -> Option<SemanticsConfiguration> {
709        crate::modifier::collect_semantics_from_chain(self.modifier_chain.chain())
710    }
711
712    /// Returns a reference to the modifier chain for layout/draw pipeline integration.
713    pub(crate) fn modifier_chain(&self) -> &ModifierChainHandle {
714        &self.modifier_chain
715    }
716
717    /// Access the text field modifier node (if present) with a mutable callback.
718    ///
719    /// This is used for keyboard event dispatch to text fields.
720    /// Returns `None` if no text field modifier is found in the chain.
721    pub fn with_text_field_modifier_mut<R>(
722        &mut self,
723        f: impl FnMut(&mut crate::TextFieldModifierNode) -> R,
724    ) -> Option<R> {
725        self.modifier_chain.with_text_field_modifier_mut(f)
726    }
727
728    /// Returns a handle to the shared layout state.
729    /// Used by layout system to update state without borrowing the Applier.
730    pub fn layout_state_handle(&self) -> Rc<RefCell<LayoutState>> {
731        self.layout_state.clone()
732    }
733}
734impl Clone for LayoutNode {
735    fn clone(&self) -> Self {
736        let mut node = Self {
737            modifier: self.modifier.clone(),
738            modifier_chain: ModifierChainHandle::new(),
739            resolved_modifiers: ResolvedModifiers::default(),
740            modifier_capabilities: self.modifier_capabilities,
741            modifier_child_capabilities: self.modifier_child_capabilities,
742            measure_policy: self.measure_policy.clone(),
743            children: self.children.clone(),
744            cache: self.cache.clone(),
745            needs_measure: Cell::new(self.needs_measure.get()),
746            needs_layout: Cell::new(self.needs_layout.get()),
747            needs_semantics: Cell::new(self.needs_semantics.get()),
748            needs_redraw: Cell::new(self.needs_redraw.get()),
749            needs_pointer_pass: Cell::new(self.needs_pointer_pass.get()),
750            needs_focus_sync: Cell::new(self.needs_focus_sync.get()),
751            parent: Cell::new(self.parent.get()),
752            folded_parent: Cell::new(self.folded_parent.get()),
753            id: Cell::new(None),
754            debug_modifiers: Cell::new(self.debug_modifiers.get()),
755            is_virtual: self.is_virtual,
756            virtual_children_count: Cell::new(self.virtual_children_count.get()),
757            modifier_slices_snapshot: RefCell::new(Rc::default()),
758            modifier_slices_dirty: Cell::new(true),
759            // Share the same layout state across clones
760            layout_state: self.layout_state.clone(),
761        };
762        node.sync_modifier_chain();
763        node
764    }
765}
766
767impl Node for LayoutNode {
768    fn mount(&mut self) {
769        let (chain, mut context) = self.modifier_chain.chain_and_context_mut();
770        chain.repair_chain();
771        chain.attach_nodes(&mut *context);
772    }
773
774    fn unmount(&mut self) {
775        self.modifier_chain.chain_mut().detach_nodes();
776    }
777
778    fn set_node_id(&mut self, id: NodeId) {
779        // Delegate to inherent method to ensure proper registration and chain updates
780        LayoutNode::set_node_id(self, id);
781    }
782
783    fn insert_child(&mut self, child: NodeId) {
784        if self.children.contains(&child) {
785            return;
786        }
787        if is_virtual_node(child) {
788            let count = self.virtual_children_count.get();
789            self.virtual_children_count.set(count + 1);
790        }
791        self.children.push(child);
792        self.cache.clear();
793        self.mark_needs_measure();
794    }
795
796    fn remove_child(&mut self, child: NodeId) {
797        let before = self.children.len();
798        self.children.retain(|&id| id != child);
799        if self.children.len() < before {
800            if is_virtual_node(child) {
801                let count = self.virtual_children_count.get();
802                if count > 0 {
803                    self.virtual_children_count.set(count - 1);
804                }
805            }
806            self.cache.clear();
807            self.mark_needs_measure();
808        }
809    }
810
811    fn move_child(&mut self, from: usize, to: usize) {
812        if from == to || from >= self.children.len() {
813            return;
814        }
815        let child = self.children.remove(from);
816        let target = to.min(self.children.len());
817        self.children.insert(target, child);
818        self.cache.clear();
819        self.mark_needs_measure();
820    }
821
822    fn update_children(&mut self, children: &[NodeId]) {
823        self.children.clear();
824        self.children.extend_from_slice(children);
825        self.cache.clear();
826        self.mark_needs_measure();
827    }
828
829    fn children(&self) -> Vec<NodeId> {
830        self.children.clone()
831    }
832
833    fn collect_children_into(&self, out: &mut smallvec::SmallVec<[NodeId; 8]>) {
834        out.clear();
835        out.extend(self.children.iter().copied());
836    }
837
838    fn on_attached_to_parent(&mut self, parent: NodeId) {
839        self.set_parent(parent);
840    }
841
842    fn on_removed_from_parent(&mut self) {
843        self.clear_parent();
844    }
845
846    fn parent(&self) -> Option<NodeId> {
847        self.parent.get()
848    }
849
850    fn mark_needs_layout(&self) {
851        self.needs_layout.set(true);
852    }
853
854    fn needs_layout(&self) -> bool {
855        self.needs_layout.get()
856    }
857
858    fn mark_needs_measure(&self) {
859        self.needs_measure.set(true);
860        self.needs_layout.set(true);
861    }
862
863    fn needs_measure(&self) -> bool {
864        self.needs_measure.get()
865    }
866
867    fn mark_needs_semantics(&self) {
868        self.needs_semantics.set(true);
869    }
870
871    fn needs_semantics(&self) -> bool {
872        self.needs_semantics.get()
873    }
874
875    /// Minimal parent setter for dirty flag bubbling.
876    /// Only sets the parent Cell without triggering registry updates.
877    /// This is used during SubcomposeLayout measurement where we need parent
878    /// pointers for bubble_measure_dirty but don't want full attachment side effects.
879    fn set_parent_for_bubbling(&mut self, parent: NodeId) {
880        self.parent.set(Some(parent));
881    }
882
883    fn recycle_key(&self) -> Option<TypeId> {
884        Some(TypeId::of::<Self>())
885    }
886
887    fn recycle_pool_limit(&self) -> Option<usize> {
888        Some(RECYCLED_LAYOUT_NODE_POOL_LIMIT)
889    }
890
891    fn prepare_for_recycle(&mut self) {
892        *self = Self::new_recycled_shell(self.is_virtual);
893    }
894
895    fn rehouse_for_recycle(&self) -> Option<Box<dyn cranpose_core::Node>> {
896        Some(Box::new(Self::new_recycled_shell(self.is_virtual)))
897    }
898
899    fn rehouse_for_live_compaction(&mut self) -> Option<Box<dyn cranpose_core::Node>> {
900        let mut previous = std::mem::replace(self, Self::new_recycled_shell(self.is_virtual));
901        let node_id = previous.id.replace(None);
902        let parent = previous.parent.get();
903        let folded_parent = previous.folded_parent.get();
904        let debug_modifiers = previous.debug_modifiers.get();
905        let needs_measure = previous.needs_measure.get();
906        let needs_layout = previous.needs_layout.get();
907        let needs_semantics = previous.needs_semantics.get();
908        let needs_redraw = previous.needs_redraw.get();
909        let needs_pointer_pass = previous.needs_pointer_pass.get();
910        let needs_focus_sync = previous.needs_focus_sync.get();
911        let virtual_children_count = previous.virtual_children_count.get();
912        let children = previous.children.to_vec();
913        let modifier = previous.modifier.rehouse_for_live_compaction();
914        let measure_policy = previous.measure_policy.clone();
915        let layout_state = previous.layout_state.clone();
916
917        previous.modifier_chain.chain_mut().detach_nodes();
918
919        let mut compact = Self::new_with_virtual(modifier, measure_policy, previous.is_virtual);
920        compact.children = children;
921        compact.parent.set(parent);
922        compact.folded_parent.set(folded_parent);
923        compact.id.set(node_id);
924        compact.debug_modifiers.set(debug_modifiers);
925        compact.needs_measure.set(needs_measure);
926        compact.needs_layout.set(needs_layout);
927        compact.needs_semantics.set(needs_semantics);
928        compact.needs_redraw.set(needs_redraw);
929        compact.needs_pointer_pass.set(needs_pointer_pass);
930        compact.needs_focus_sync.set(needs_focus_sync);
931        compact.virtual_children_count.set(virtual_children_count);
932        compact.layout_state = layout_state;
933        compact.sync_modifier_chain();
934        if let Some(id) = node_id {
935            register_layout_node(id, &compact);
936        }
937
938        Some(Box::new(compact))
939    }
940}
941
942impl Drop for LayoutNode {
943    fn drop(&mut self) {
944        if let Some(id) = self.id.get() {
945            unregister_layout_node(id);
946        }
947    }
948}
949
950thread_local! {
951    static LAYOUT_NODE_REGISTRY: RefCell<HashMap<NodeId, LayoutNodeRegistryEntry>> =
952        RefCell::new(HashMap::new());
953    // Start at a high value to avoid conflicts with SlotTable IDs (which start low).
954    // We use a value compatible with 32-bit (WASM) usize to prevent truncation issues.
955    // 0xC0000000 is ~3.2 billion, leaving ~1 billion IDs before overflow.
956    static VIRTUAL_NODE_ID_COUNTER: std::sync::atomic::AtomicUsize = const { std::sync::atomic::AtomicUsize::new(0xC0000000) };
957}
958
959const MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY: usize = 128;
960
961#[cfg(test)]
962#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
963struct LayoutNodeRegistryDebugStats {
964    len: usize,
965    capacity: usize,
966}
967
968struct LayoutNodeRegistryEntry {
969    parent: Option<NodeId>,
970    modifier_child_capabilities: NodeCapabilities,
971    modifier_locals: ModifierLocalsHandle,
972    is_virtual: bool,
973}
974
975pub(crate) fn register_layout_node(id: NodeId, node: &LayoutNode) {
976    LAYOUT_NODE_REGISTRY.with(|registry| {
977        registry.borrow_mut().insert(
978            id,
979            LayoutNodeRegistryEntry {
980                parent: node.parent(),
981                modifier_child_capabilities: node.modifier_child_capabilities(),
982                modifier_locals: node.modifier_locals_handle(),
983                is_virtual: node.is_virtual(),
984            },
985        );
986    });
987}
988
989pub(crate) fn unregister_layout_node(id: NodeId) {
990    LAYOUT_NODE_REGISTRY.with(|registry| {
991        let mut registry = registry.borrow_mut();
992        registry.remove(&id);
993        let should_shrink = (registry.len() <= MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY
994            && registry.capacity() > MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY)
995            || registry.capacity()
996                > registry
997                    .len()
998                    .max(MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY)
999                    .saturating_mul(4);
1000        if should_shrink {
1001            let retained = registry
1002                .len()
1003                .max(MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY);
1004            let mut rebuilt = HashMap::new();
1005            rebuilt.reserve(retained);
1006            rebuilt.extend(registry.drain());
1007            *registry = rebuilt;
1008        }
1009    });
1010}
1011
1012#[cfg(test)]
1013fn layout_node_registry_stats() -> LayoutNodeRegistryDebugStats {
1014    LAYOUT_NODE_REGISTRY.with(|registry| {
1015        let registry = registry.borrow();
1016        LayoutNodeRegistryDebugStats {
1017            len: registry.len(),
1018            capacity: registry.capacity(),
1019        }
1020    })
1021}
1022
1023pub(crate) fn is_virtual_node(id: NodeId) -> bool {
1024    LAYOUT_NODE_REGISTRY.with(|registry| {
1025        registry
1026            .borrow()
1027            .get(&id)
1028            .map(|entry| entry.is_virtual)
1029            .unwrap_or(false)
1030    })
1031}
1032
1033pub(crate) fn allocate_virtual_node_id() -> NodeId {
1034    use std::sync::atomic::Ordering;
1035    // Allocate IDs from a high range to avoid conflict with SlotTable IDs.
1036    // Thread-local counter avoids cross-thread contention (WASM is single-threaded anyway).
1037    VIRTUAL_NODE_ID_COUNTER.with(|counter| counter.fetch_add(1, Ordering::Relaxed))
1038}
1039
1040fn resolve_modifier_local_from_parent_chain(
1041    start: Option<NodeId>,
1042    token: ModifierLocalToken,
1043) -> Option<ResolvedModifierLocal> {
1044    let mut current = start;
1045    while let Some(parent_id) = current {
1046        let (next_parent, resolved) = LAYOUT_NODE_REGISTRY.with(|registry| {
1047            let registry = registry.borrow();
1048            if let Some(entry) = registry.get(&parent_id) {
1049                let resolved = if entry
1050                    .modifier_child_capabilities
1051                    .contains(NodeCapabilities::MODIFIER_LOCALS)
1052                {
1053                    entry
1054                        .modifier_locals
1055                        .borrow()
1056                        .resolve(token)
1057                        .map(|value| value.with_source(ModifierLocalSource::Ancestor))
1058                } else {
1059                    None
1060                };
1061                (entry.parent, resolved)
1062            } else {
1063                (None, None)
1064            }
1065        });
1066        if let Some(value) = resolved {
1067            return Some(value);
1068        }
1069        current = next_parent;
1070    }
1071    None
1072}
1073
1074#[cfg(test)]
1075mod tests {
1076    use super::*;
1077    use cranpose_ui_graphics::Size as GeometrySize;
1078    use cranpose_ui_layout::{Measurable, MeasureResult};
1079    use std::rc::Rc;
1080
1081    #[derive(Default)]
1082    struct TestMeasurePolicy;
1083
1084    impl MeasurePolicy for TestMeasurePolicy {
1085        fn measure(
1086            &self,
1087            _measurables: &[Box<dyn Measurable>],
1088            _constraints: Constraints,
1089        ) -> MeasureResult {
1090            MeasureResult::new(
1091                GeometrySize {
1092                    width: 0.0,
1093                    height: 0.0,
1094                },
1095                Vec::new(),
1096            )
1097        }
1098
1099        fn min_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
1100            0.0
1101        }
1102
1103        fn max_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
1104            0.0
1105        }
1106
1107        fn min_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
1108            0.0
1109        }
1110
1111        fn max_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
1112            0.0
1113        }
1114    }
1115
1116    fn fresh_node() -> LayoutNode {
1117        LayoutNode::new(Modifier::empty(), Rc::new(TestMeasurePolicy))
1118    }
1119
1120    #[test]
1121    fn modifier_slices_cache_reuses_unique_snapshot_allocation() {
1122        let mut node = fresh_node();
1123        let snapshot = node.modifier_slices_snapshot();
1124        let snapshot_ptr = Rc::as_ptr(&snapshot);
1125        drop(snapshot);
1126
1127        node.set_modifier(Modifier::empty().padding(4.0));
1128
1129        let updated = node.modifier_slices_snapshot();
1130        assert_eq!(Rc::as_ptr(&updated), snapshot_ptr);
1131    }
1132
1133    #[test]
1134    fn modifier_slices_cache_preserves_live_snapshot_isolation() {
1135        let mut node = fresh_node();
1136        let old_snapshot = node.modifier_slices_snapshot();
1137        let old_snapshot_ptr = Rc::as_ptr(&old_snapshot);
1138
1139        node.set_modifier(Modifier::empty().padding(4.0));
1140
1141        let updated = node.modifier_slices_snapshot();
1142        assert_ne!(Rc::as_ptr(&updated), old_snapshot_ptr);
1143        assert_eq!(old_snapshot.draw_commands().len(), 0);
1144    }
1145
1146    #[test]
1147    fn layout_node_registry_retains_warm_capacity_after_large_cleanup() {
1148        let nodes: Vec<_> = (0..2048)
1149            .map(|_| {
1150                let id = allocate_virtual_node_id();
1151                let node = fresh_node();
1152                register_layout_node(id, &node);
1153                (id, node)
1154            })
1155            .collect();
1156
1157        for (id, _) in &nodes {
1158            unregister_layout_node(*id);
1159        }
1160
1161        let stats = layout_node_registry_stats();
1162        assert_eq!(stats.len, 0);
1163        assert!(
1164            (MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY
1165                ..=MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY.saturating_mul(2))
1166                .contains(&stats.capacity),
1167            "registry warm capacity {} fell outside expected retained range {}..={}",
1168            stats.capacity,
1169            MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY,
1170            MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY.saturating_mul(2),
1171        );
1172    }
1173
1174    fn invalidation(kind: InvalidationKind) -> ModifierInvalidation {
1175        ModifierInvalidation::new(kind, NodeCapabilities::for_invalidation(kind))
1176    }
1177
1178    #[test]
1179    fn layout_invalidation_requires_layout_capability() {
1180        let mut node = fresh_node();
1181        node.clear_needs_measure();
1182        node.clear_needs_layout();
1183        node.modifier_capabilities = NodeCapabilities::DRAW;
1184        node.modifier_child_capabilities = node.modifier_capabilities;
1185
1186        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
1187
1188        assert!(!node.needs_measure());
1189        assert!(!node.needs_layout());
1190    }
1191
1192    #[test]
1193    fn semantics_configuration_reflects_modifier_state() {
1194        let mut node = fresh_node();
1195        node.set_modifier(Modifier::empty().semantics(|config| {
1196            config.content_description = Some("greeting".into());
1197            config.is_clickable = true;
1198        }));
1199
1200        let config = node
1201            .semantics_configuration()
1202            .expect("expected semantics configuration");
1203        assert_eq!(config.content_description.as_deref(), Some("greeting"));
1204        assert!(config.is_clickable);
1205    }
1206
1207    #[test]
1208    fn layout_invalidation_marks_flags_when_capability_present() {
1209        let _guard = crate::render_state::render_state_test_guard();
1210        crate::reset_render_state_for_tests();
1211        let mut node = fresh_node();
1212        node.id.set(Some(11));
1213        node.clear_needs_measure();
1214        node.clear_needs_layout();
1215        node.modifier_capabilities = NodeCapabilities::LAYOUT;
1216        node.modifier_child_capabilities = node.modifier_capabilities;
1217
1218        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
1219
1220        assert!(node.needs_measure());
1221        assert!(node.needs_layout());
1222        assert_eq!(crate::take_layout_repass_nodes(), vec![11]);
1223        assert!(crate::take_layout_invalidation());
1224    }
1225
1226    #[test]
1227    fn layout_invalidation_skips_repass_while_composing() {
1228        let _guard = crate::render_state::render_state_test_guard();
1229        crate::reset_render_state_for_tests();
1230
1231        let node = Rc::new(RefCell::new(fresh_node()));
1232        {
1233            let mut node = node.borrow_mut();
1234            node.id.set(Some(17));
1235            node.clear_needs_measure();
1236            node.clear_needs_layout();
1237            node.modifier_capabilities = NodeCapabilities::LAYOUT;
1238            node.modifier_child_capabilities = node.modifier_capabilities;
1239        }
1240
1241        let node_for_composition = Rc::clone(&node);
1242        let _composition = crate::run_test_composition(move || {
1243            node_for_composition
1244                .borrow()
1245                .dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
1246        });
1247
1248        let node = node.borrow();
1249        assert!(node.needs_measure());
1250        assert!(node.needs_layout());
1251        assert!(crate::take_layout_repass_nodes().is_empty());
1252        assert!(!crate::take_layout_invalidation());
1253    }
1254
1255    #[test]
1256    fn draw_invalidation_marks_redraw_flag_when_capable() {
1257        let mut node = fresh_node();
1258        node.clear_needs_measure();
1259        node.clear_needs_layout();
1260        node.modifier_capabilities = NodeCapabilities::DRAW;
1261        node.modifier_child_capabilities = node.modifier_capabilities;
1262
1263        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Draw)]);
1264
1265        assert!(node.needs_redraw());
1266        assert!(!node.needs_layout());
1267    }
1268
1269    #[test]
1270    fn semantics_invalidation_sets_semantics_flag_only() {
1271        let mut node = fresh_node();
1272        node.clear_needs_measure();
1273        node.clear_needs_layout();
1274        node.clear_needs_semantics();
1275        node.modifier_capabilities = NodeCapabilities::SEMANTICS;
1276        node.modifier_child_capabilities = node.modifier_capabilities;
1277
1278        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Semantics)]);
1279
1280        assert!(node.needs_semantics());
1281        assert!(!node.needs_measure());
1282        assert!(!node.needs_layout());
1283    }
1284
1285    #[test]
1286    fn pointer_invalidation_requires_pointer_capability() {
1287        let mut node = fresh_node();
1288        node.clear_needs_pointer_pass();
1289        node.modifier_capabilities = NodeCapabilities::DRAW;
1290        node.modifier_child_capabilities = node.modifier_capabilities;
1291        // Note: We don't assert on global take_pointer_invalidation() because
1292        // it's shared across tests running in parallel and causes flakiness.
1293        // The node's local state is sufficient to verify correct dispatch behavior.
1294
1295        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::PointerInput)]);
1296
1297        assert!(!node.needs_pointer_pass());
1298    }
1299
1300    #[test]
1301    fn pointer_invalidation_marks_flag_and_requests_queue() {
1302        let mut node = fresh_node();
1303        node.clear_needs_pointer_pass();
1304        node.modifier_capabilities = NodeCapabilities::POINTER_INPUT;
1305        node.modifier_child_capabilities = node.modifier_capabilities;
1306        // Note: We don't assert on global take_pointer_invalidation() because
1307        // it's shared across tests running in parallel and causes flakiness.
1308        // The node's local state is sufficient to verify correct dispatch behavior.
1309
1310        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::PointerInput)]);
1311
1312        assert!(node.needs_pointer_pass());
1313    }
1314
1315    #[test]
1316    fn focus_invalidation_requires_focus_capability() {
1317        let mut node = fresh_node();
1318        node.clear_needs_focus_sync();
1319        node.modifier_capabilities = NodeCapabilities::DRAW;
1320        node.modifier_child_capabilities = node.modifier_capabilities;
1321        crate::take_focus_invalidation();
1322
1323        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Focus)]);
1324
1325        assert!(!node.needs_focus_sync());
1326        assert!(!crate::take_focus_invalidation());
1327    }
1328
1329    #[test]
1330    fn focus_invalidation_marks_flag_and_requests_queue() {
1331        let mut node = fresh_node();
1332        node.clear_needs_focus_sync();
1333        node.modifier_capabilities = NodeCapabilities::FOCUS;
1334        node.modifier_child_capabilities = node.modifier_capabilities;
1335        crate::take_focus_invalidation();
1336
1337        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Focus)]);
1338
1339        assert!(node.needs_focus_sync());
1340        assert!(crate::take_focus_invalidation());
1341    }
1342
1343    #[test]
1344    fn set_modifier_marks_semantics_dirty() {
1345        let mut node = fresh_node();
1346        node.clear_needs_semantics();
1347        node.set_modifier(Modifier::empty().semantics(|config| {
1348            config.is_clickable = true;
1349        }));
1350
1351        assert!(node.needs_semantics());
1352    }
1353
1354    #[test]
1355    fn modifier_child_capabilities_reflect_chain_head() {
1356        let mut node = fresh_node();
1357        node.set_modifier(Modifier::empty().padding(4.0));
1358        assert!(
1359            node.modifier_child_capabilities()
1360                .contains(NodeCapabilities::LAYOUT),
1361            "padding should introduce layout capability"
1362        );
1363    }
1364}