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        self.update_modifier_slices_cache();
544    }
545
546    /// Get this node's ID.
547    pub fn node_id(&self) -> Option<NodeId> {
548        self.id.get()
549    }
550
551    /// Set this node's parent (called when node is added as child).
552    /// Sets both folded_parent (direct) and parent (first non-virtual ancestor for bubbling).
553    pub fn set_parent(&self, parent: NodeId) {
554        self.folded_parent.set(Some(parent));
555        // For now, parent = folded_parent. Virtual parent skipping requires applier access.
556        // The actual virtual-skipping happens in bubble_measure_dirty via applier traversal.
557        self.parent.set(Some(parent));
558        self.refresh_registry_state();
559    }
560
561    /// Clear this node's parent (called when node is removed from parent).
562    pub fn clear_parent(&self) {
563        self.folded_parent.set(None);
564        self.parent.set(None);
565        self.refresh_registry_state();
566    }
567
568    /// Get this node's parent for dirty flag bubbling (may skip virtual nodes).
569    pub fn parent(&self) -> Option<NodeId> {
570        self.parent.get()
571    }
572
573    /// Get this node's direct parent (may be a virtual node).
574    pub fn folded_parent(&self) -> Option<NodeId> {
575        self.folded_parent.get()
576    }
577
578    /// Returns true if this is a virtual node (transparent container for subcomposition).
579    pub fn is_virtual(&self) -> bool {
580        self.is_virtual
581    }
582
583    pub(crate) fn cache_handles(&self) -> LayoutNodeCacheHandles {
584        self.cache.clone()
585    }
586
587    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
588        self.resolved_modifiers
589    }
590
591    pub fn modifier_capabilities(&self) -> NodeCapabilities {
592        self.modifier_capabilities
593    }
594
595    pub fn modifier_child_capabilities(&self) -> NodeCapabilities {
596        self.modifier_child_capabilities
597    }
598
599    pub fn set_debug_modifiers(&mut self, enabled: bool) {
600        self.debug_modifiers.set(enabled);
601        self.modifier_chain.set_debug_logging(enabled);
602    }
603
604    pub fn debug_modifiers_enabled(&self) -> bool {
605        self.debug_modifiers.get()
606    }
607
608    pub fn modifier_locals_handle(&self) -> ModifierLocalsHandle {
609        self.modifier_chain.modifier_locals_handle()
610    }
611
612    pub fn has_layout_modifier_nodes(&self) -> bool {
613        self.modifier_capabilities
614            .contains(NodeCapabilities::LAYOUT)
615    }
616
617    pub fn has_draw_modifier_nodes(&self) -> bool {
618        self.modifier_capabilities.contains(NodeCapabilities::DRAW)
619    }
620
621    pub fn has_pointer_input_modifier_nodes(&self) -> bool {
622        self.modifier_capabilities
623            .contains(NodeCapabilities::POINTER_INPUT)
624    }
625
626    pub fn has_semantics_modifier_nodes(&self) -> bool {
627        self.modifier_capabilities
628            .contains(NodeCapabilities::SEMANTICS)
629    }
630
631    pub fn has_focus_modifier_nodes(&self) -> bool {
632        self.modifier_capabilities.contains(NodeCapabilities::FOCUS)
633    }
634
635    fn refresh_registry_state(&self) {
636        if let Some(id) = self.id.get() {
637            let parent = self.parent();
638            let capabilities = self.modifier_child_capabilities();
639            let modifier_locals = self.modifier_locals_handle();
640            LAYOUT_NODE_REGISTRY.with(|registry| {
641                if let Some(entry) = registry.borrow_mut().get_mut(&id) {
642                    entry.parent = parent;
643                    entry.modifier_child_capabilities = capabilities;
644                    entry.modifier_locals = modifier_locals;
645                }
646            });
647        }
648    }
649
650    pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
651        if self.modifier_slices_dirty.get() {
652            self.update_modifier_slices_cache();
653        }
654        self.modifier_slices_snapshot.borrow().clone()
655    }
656
657    // ═══════════════════════════════════════════════════════════════════════
658    // Retained Layout State API
659    // ═══════════════════════════════════════════════════════════════════════
660
661    /// Returns a clone of the current layout state.
662    pub fn layout_state(&self) -> LayoutState {
663        self.layout_state.borrow().clone()
664    }
665
666    /// Returns the measured size of this node.
667    pub fn measured_size(&self) -> Size {
668        self.layout_state.borrow().size
669    }
670
671    /// Returns the position of this node relative to its parent.
672    pub fn position(&self) -> Point {
673        self.layout_state.borrow().position
674    }
675
676    /// Returns true if this node has been placed in the current layout pass.
677    pub fn is_placed(&self) -> bool {
678        self.layout_state.borrow().is_placed
679    }
680
681    /// Updates the measured size of this node. Called during measurement.
682    pub fn set_measured_size(&self, size: Size) {
683        let mut state = self.layout_state.borrow_mut();
684        state.size = size;
685    }
686
687    /// Updates the position of this node. Called during placement.
688    pub fn set_position(&self, position: Point) {
689        let mut state = self.layout_state.borrow_mut();
690        state.position = position;
691        state.is_placed = true;
692    }
693
694    /// Records the constraints used for measurement. Used for relayout optimization.
695    pub fn set_measurement_constraints(&self, constraints: Constraints) {
696        self.layout_state.borrow_mut().measurement_constraints = constraints;
697    }
698
699    /// Records the content offset (e.g. from padding).
700    pub fn set_content_offset(&self, offset: Point) {
701        self.layout_state.borrow_mut().content_offset = offset;
702    }
703
704    /// Clears the is_placed flag. Called at the start of a layout pass.
705    pub fn clear_placed(&self) {
706        self.layout_state.borrow_mut().is_placed = false;
707    }
708
709    pub fn semantics_configuration(&self) -> Option<SemanticsConfiguration> {
710        crate::modifier::collect_semantics_from_chain(self.modifier_chain.chain())
711    }
712
713    /// Returns a reference to the modifier chain for layout/draw pipeline integration.
714    pub(crate) fn modifier_chain(&self) -> &ModifierChainHandle {
715        &self.modifier_chain
716    }
717
718    /// Access the text field modifier node (if present) with a mutable callback.
719    ///
720    /// This is used for keyboard event dispatch to text fields.
721    /// Returns `None` if no text field modifier is found in the chain.
722    pub fn with_text_field_modifier_mut<R>(
723        &mut self,
724        f: impl FnMut(&mut crate::TextFieldModifierNode) -> R,
725    ) -> Option<R> {
726        self.modifier_chain.with_text_field_modifier_mut(f)
727    }
728
729    /// Returns a handle to the shared layout state.
730    /// Used by layout system to update state without borrowing the Applier.
731    pub fn layout_state_handle(&self) -> Rc<RefCell<LayoutState>> {
732        self.layout_state.clone()
733    }
734}
735impl Clone for LayoutNode {
736    fn clone(&self) -> Self {
737        let mut node = Self {
738            modifier: self.modifier.clone(),
739            modifier_chain: ModifierChainHandle::new(),
740            resolved_modifiers: ResolvedModifiers::default(),
741            modifier_capabilities: self.modifier_capabilities,
742            modifier_child_capabilities: self.modifier_child_capabilities,
743            measure_policy: self.measure_policy.clone(),
744            children: self.children.clone(),
745            cache: self.cache.clone(),
746            needs_measure: Cell::new(self.needs_measure.get()),
747            needs_layout: Cell::new(self.needs_layout.get()),
748            needs_semantics: Cell::new(self.needs_semantics.get()),
749            needs_redraw: Cell::new(self.needs_redraw.get()),
750            needs_pointer_pass: Cell::new(self.needs_pointer_pass.get()),
751            needs_focus_sync: Cell::new(self.needs_focus_sync.get()),
752            parent: Cell::new(self.parent.get()),
753            folded_parent: Cell::new(self.folded_parent.get()),
754            id: Cell::new(None),
755            debug_modifiers: Cell::new(self.debug_modifiers.get()),
756            is_virtual: self.is_virtual,
757            virtual_children_count: Cell::new(self.virtual_children_count.get()),
758            modifier_slices_snapshot: RefCell::new(Rc::default()),
759            modifier_slices_dirty: Cell::new(true),
760            // Share the same layout state across clones
761            layout_state: self.layout_state.clone(),
762        };
763        node.sync_modifier_chain();
764        node
765    }
766}
767
768impl Node for LayoutNode {
769    fn mount(&mut self) {
770        let (chain, mut context) = self.modifier_chain.chain_and_context_mut();
771        chain.repair_chain();
772        chain.attach_nodes(&mut *context);
773    }
774
775    fn unmount(&mut self) {
776        self.modifier_chain.chain_mut().detach_nodes();
777    }
778
779    fn set_node_id(&mut self, id: NodeId) {
780        // Delegate to inherent method to ensure proper registration and chain updates
781        LayoutNode::set_node_id(self, id);
782    }
783
784    fn insert_child(&mut self, child: NodeId) {
785        if self.children.contains(&child) {
786            return;
787        }
788        if is_virtual_node(child) {
789            let count = self.virtual_children_count.get();
790            self.virtual_children_count.set(count + 1);
791        }
792        self.children.push(child);
793        self.cache.clear();
794        self.mark_needs_measure();
795    }
796
797    fn remove_child(&mut self, child: NodeId) {
798        let before = self.children.len();
799        self.children.retain(|&id| id != child);
800        if self.children.len() < before {
801            if is_virtual_node(child) {
802                let count = self.virtual_children_count.get();
803                if count > 0 {
804                    self.virtual_children_count.set(count - 1);
805                }
806            }
807            self.cache.clear();
808            self.mark_needs_measure();
809        }
810    }
811
812    fn move_child(&mut self, from: usize, to: usize) {
813        if from == to || from >= self.children.len() {
814            return;
815        }
816        let child = self.children.remove(from);
817        let target = to.min(self.children.len());
818        self.children.insert(target, child);
819        self.cache.clear();
820        self.mark_needs_measure();
821    }
822
823    fn update_children(&mut self, children: &[NodeId]) {
824        self.children.clear();
825        self.children.extend_from_slice(children);
826        self.cache.clear();
827        self.mark_needs_measure();
828    }
829
830    fn children(&self) -> Vec<NodeId> {
831        self.children.clone()
832    }
833
834    fn collect_children_into(&self, out: &mut smallvec::SmallVec<[NodeId; 8]>) {
835        out.clear();
836        out.extend(self.children.iter().copied());
837    }
838
839    fn on_attached_to_parent(&mut self, parent: NodeId) {
840        self.set_parent(parent);
841    }
842
843    fn on_removed_from_parent(&mut self) {
844        self.clear_parent();
845    }
846
847    fn parent(&self) -> Option<NodeId> {
848        self.parent.get()
849    }
850
851    fn mark_needs_layout(&self) {
852        self.needs_layout.set(true);
853    }
854
855    fn needs_layout(&self) -> bool {
856        self.needs_layout.get()
857    }
858
859    fn mark_needs_measure(&self) {
860        self.needs_measure.set(true);
861        self.needs_layout.set(true);
862    }
863
864    fn needs_measure(&self) -> bool {
865        self.needs_measure.get()
866    }
867
868    fn mark_needs_semantics(&self) {
869        self.needs_semantics.set(true);
870    }
871
872    fn needs_semantics(&self) -> bool {
873        self.needs_semantics.get()
874    }
875
876    /// Minimal parent setter for dirty flag bubbling.
877    /// Only sets the parent Cell without triggering registry updates.
878    /// This is used during SubcomposeLayout measurement where we need parent
879    /// pointers for bubble_measure_dirty but don't want full attachment side effects.
880    fn set_parent_for_bubbling(&mut self, parent: NodeId) {
881        self.parent.set(Some(parent));
882    }
883
884    fn recycle_key(&self) -> Option<TypeId> {
885        Some(TypeId::of::<Self>())
886    }
887
888    fn recycle_pool_limit(&self) -> Option<usize> {
889        Some(RECYCLED_LAYOUT_NODE_POOL_LIMIT)
890    }
891
892    fn prepare_for_recycle(&mut self) {
893        *self = Self::new_recycled_shell(self.is_virtual);
894    }
895
896    fn rehouse_for_recycle(&self) -> Option<Box<dyn cranpose_core::Node>> {
897        Some(Box::new(Self::new_recycled_shell(self.is_virtual)))
898    }
899
900    fn rehouse_for_live_compaction(&mut self) -> Option<Box<dyn cranpose_core::Node>> {
901        let mut previous = std::mem::replace(self, Self::new_recycled_shell(self.is_virtual));
902        let node_id = previous.id.replace(None);
903        let parent = previous.parent.get();
904        let folded_parent = previous.folded_parent.get();
905        let debug_modifiers = previous.debug_modifiers.get();
906        let needs_measure = previous.needs_measure.get();
907        let needs_layout = previous.needs_layout.get();
908        let needs_semantics = previous.needs_semantics.get();
909        let needs_redraw = previous.needs_redraw.get();
910        let needs_pointer_pass = previous.needs_pointer_pass.get();
911        let needs_focus_sync = previous.needs_focus_sync.get();
912        let virtual_children_count = previous.virtual_children_count.get();
913        let children = previous.children.to_vec();
914        let modifier = previous.modifier.rehouse_for_live_compaction();
915        let measure_policy = previous.measure_policy.clone();
916        let layout_state = previous.layout_state.clone();
917
918        previous.modifier_chain.chain_mut().detach_nodes();
919
920        let mut compact = Self::new_with_virtual(modifier, measure_policy, previous.is_virtual);
921        compact.children = children;
922        compact.parent.set(parent);
923        compact.folded_parent.set(folded_parent);
924        compact.id.set(node_id);
925        compact.debug_modifiers.set(debug_modifiers);
926        compact.needs_measure.set(needs_measure);
927        compact.needs_layout.set(needs_layout);
928        compact.needs_semantics.set(needs_semantics);
929        compact.needs_redraw.set(needs_redraw);
930        compact.needs_pointer_pass.set(needs_pointer_pass);
931        compact.needs_focus_sync.set(needs_focus_sync);
932        compact.virtual_children_count.set(virtual_children_count);
933        compact.layout_state = layout_state;
934        compact.sync_modifier_chain();
935        if let Some(id) = node_id {
936            register_layout_node(id, &compact);
937        }
938
939        Some(Box::new(compact))
940    }
941}
942
943impl Drop for LayoutNode {
944    fn drop(&mut self) {
945        if let Some(id) = self.id.get() {
946            unregister_layout_node(id);
947        }
948    }
949}
950
951thread_local! {
952    static LAYOUT_NODE_REGISTRY: RefCell<HashMap<NodeId, LayoutNodeRegistryEntry>> =
953        RefCell::new(HashMap::new());
954    // Start at a high value to avoid conflicts with SlotTable IDs (which start low).
955    // We use a value compatible with 32-bit (WASM) usize to prevent truncation issues.
956    // 0xC0000000 is ~3.2 billion, leaving ~1 billion IDs before overflow.
957    static VIRTUAL_NODE_ID_COUNTER: std::sync::atomic::AtomicUsize = const { std::sync::atomic::AtomicUsize::new(0xC0000000) };
958}
959
960const MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY: usize = 128;
961
962#[cfg(test)]
963#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
964struct LayoutNodeRegistryDebugStats {
965    len: usize,
966    capacity: usize,
967}
968
969struct LayoutNodeRegistryEntry {
970    parent: Option<NodeId>,
971    modifier_child_capabilities: NodeCapabilities,
972    modifier_locals: ModifierLocalsHandle,
973    is_virtual: bool,
974}
975
976pub(crate) fn register_layout_node(id: NodeId, node: &LayoutNode) {
977    LAYOUT_NODE_REGISTRY.with(|registry| {
978        registry.borrow_mut().insert(
979            id,
980            LayoutNodeRegistryEntry {
981                parent: node.parent(),
982                modifier_child_capabilities: node.modifier_child_capabilities(),
983                modifier_locals: node.modifier_locals_handle(),
984                is_virtual: node.is_virtual(),
985            },
986        );
987    });
988}
989
990pub(crate) fn unregister_layout_node(id: NodeId) {
991    LAYOUT_NODE_REGISTRY.with(|registry| {
992        let mut registry = registry.borrow_mut();
993        registry.remove(&id);
994        let should_shrink = (registry.len() <= MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY
995            && registry.capacity() > MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY)
996            || registry.capacity()
997                > registry
998                    .len()
999                    .max(MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY)
1000                    .saturating_mul(4);
1001        if should_shrink {
1002            let retained = registry
1003                .len()
1004                .max(MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY);
1005            let mut rebuilt = HashMap::new();
1006            rebuilt.reserve(retained);
1007            rebuilt.extend(registry.drain());
1008            *registry = rebuilt;
1009        }
1010    });
1011}
1012
1013#[cfg(test)]
1014fn layout_node_registry_stats() -> LayoutNodeRegistryDebugStats {
1015    LAYOUT_NODE_REGISTRY.with(|registry| {
1016        let registry = registry.borrow();
1017        LayoutNodeRegistryDebugStats {
1018            len: registry.len(),
1019            capacity: registry.capacity(),
1020        }
1021    })
1022}
1023
1024pub(crate) fn is_virtual_node(id: NodeId) -> bool {
1025    LAYOUT_NODE_REGISTRY.with(|registry| {
1026        registry
1027            .borrow()
1028            .get(&id)
1029            .map(|entry| entry.is_virtual)
1030            .unwrap_or(false)
1031    })
1032}
1033
1034pub(crate) fn allocate_virtual_node_id() -> NodeId {
1035    use std::sync::atomic::Ordering;
1036    // Allocate IDs from a high range to avoid conflict with SlotTable IDs.
1037    // Thread-local counter avoids cross-thread contention (WASM is single-threaded anyway).
1038    VIRTUAL_NODE_ID_COUNTER.with(|counter| counter.fetch_add(1, Ordering::Relaxed))
1039}
1040
1041fn resolve_modifier_local_from_parent_chain(
1042    start: Option<NodeId>,
1043    token: ModifierLocalToken,
1044) -> Option<ResolvedModifierLocal> {
1045    let mut current = start;
1046    while let Some(parent_id) = current {
1047        let (next_parent, resolved) = LAYOUT_NODE_REGISTRY.with(|registry| {
1048            let registry = registry.borrow();
1049            if let Some(entry) = registry.get(&parent_id) {
1050                let resolved = if entry
1051                    .modifier_child_capabilities
1052                    .contains(NodeCapabilities::MODIFIER_LOCALS)
1053                {
1054                    entry
1055                        .modifier_locals
1056                        .borrow()
1057                        .resolve(token)
1058                        .map(|value| value.with_source(ModifierLocalSource::Ancestor))
1059                } else {
1060                    None
1061                };
1062                (entry.parent, resolved)
1063            } else {
1064                (None, None)
1065            }
1066        });
1067        if let Some(value) = resolved {
1068            return Some(value);
1069        }
1070        current = next_parent;
1071    }
1072    None
1073}
1074
1075#[cfg(test)]
1076mod tests {
1077    use super::*;
1078    use cranpose_ui_graphics::Size as GeometrySize;
1079    use cranpose_ui_layout::{Measurable, MeasureResult};
1080    use std::rc::Rc;
1081
1082    #[derive(Default)]
1083    struct TestMeasurePolicy;
1084
1085    impl MeasurePolicy for TestMeasurePolicy {
1086        fn measure(
1087            &self,
1088            _measurables: &[Box<dyn Measurable>],
1089            _constraints: Constraints,
1090        ) -> MeasureResult {
1091            MeasureResult::new(
1092                GeometrySize {
1093                    width: 0.0,
1094                    height: 0.0,
1095                },
1096                Vec::new(),
1097            )
1098        }
1099
1100        fn min_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
1101            0.0
1102        }
1103
1104        fn max_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
1105            0.0
1106        }
1107
1108        fn min_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
1109            0.0
1110        }
1111
1112        fn max_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
1113            0.0
1114        }
1115    }
1116
1117    fn fresh_node() -> LayoutNode {
1118        LayoutNode::new(Modifier::empty(), Rc::new(TestMeasurePolicy))
1119    }
1120
1121    #[test]
1122    fn modifier_slices_cache_reuses_unique_snapshot_allocation() {
1123        let mut node = fresh_node();
1124        let snapshot = node.modifier_slices_snapshot();
1125        let snapshot_ptr = Rc::as_ptr(&snapshot);
1126        drop(snapshot);
1127
1128        node.set_modifier(Modifier::empty().padding(4.0));
1129
1130        let updated = node.modifier_slices_snapshot();
1131        assert_eq!(Rc::as_ptr(&updated), snapshot_ptr);
1132    }
1133
1134    #[test]
1135    fn modifier_slices_cache_preserves_live_snapshot_isolation() {
1136        let mut node = fresh_node();
1137        let old_snapshot = node.modifier_slices_snapshot();
1138        let old_snapshot_ptr = Rc::as_ptr(&old_snapshot);
1139
1140        node.set_modifier(Modifier::empty().padding(4.0));
1141
1142        let updated = node.modifier_slices_snapshot();
1143        assert_ne!(Rc::as_ptr(&updated), old_snapshot_ptr);
1144        assert_eq!(old_snapshot.draw_commands().len(), 0);
1145    }
1146
1147    #[test]
1148    fn layout_node_registry_retains_warm_capacity_after_large_cleanup() {
1149        let nodes: Vec<_> = (0..2048)
1150            .map(|_| {
1151                let id = allocate_virtual_node_id();
1152                let node = fresh_node();
1153                register_layout_node(id, &node);
1154                (id, node)
1155            })
1156            .collect();
1157
1158        for (id, _) in &nodes {
1159            unregister_layout_node(*id);
1160        }
1161
1162        let stats = layout_node_registry_stats();
1163        assert_eq!(stats.len, 0);
1164        assert!(
1165            (MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY
1166                ..=MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY.saturating_mul(2))
1167                .contains(&stats.capacity),
1168            "registry warm capacity {} fell outside expected retained range {}..={}",
1169            stats.capacity,
1170            MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY,
1171            MIN_RETAINED_LAYOUT_NODE_REGISTRY_CAPACITY.saturating_mul(2),
1172        );
1173    }
1174
1175    fn invalidation(kind: InvalidationKind) -> ModifierInvalidation {
1176        ModifierInvalidation::new(kind, NodeCapabilities::for_invalidation(kind))
1177    }
1178
1179    #[test]
1180    fn layout_invalidation_requires_layout_capability() {
1181        let mut node = fresh_node();
1182        node.clear_needs_measure();
1183        node.clear_needs_layout();
1184        node.modifier_capabilities = NodeCapabilities::DRAW;
1185        node.modifier_child_capabilities = node.modifier_capabilities;
1186
1187        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
1188
1189        assert!(!node.needs_measure());
1190        assert!(!node.needs_layout());
1191    }
1192
1193    #[test]
1194    fn semantics_configuration_reflects_modifier_state() {
1195        let mut node = fresh_node();
1196        node.set_modifier(Modifier::empty().semantics(|config| {
1197            config.content_description = Some("greeting".into());
1198            config.is_clickable = true;
1199        }));
1200
1201        let config = node
1202            .semantics_configuration()
1203            .expect("expected semantics configuration");
1204        assert_eq!(config.content_description.as_deref(), Some("greeting"));
1205        assert!(config.is_clickable);
1206    }
1207
1208    #[test]
1209    fn layout_invalidation_marks_flags_when_capability_present() {
1210        let _guard = crate::render_state::render_state_test_guard();
1211        crate::reset_render_state_for_tests();
1212        let mut node = fresh_node();
1213        node.id.set(Some(11));
1214        node.clear_needs_measure();
1215        node.clear_needs_layout();
1216        node.modifier_capabilities = NodeCapabilities::LAYOUT;
1217        node.modifier_child_capabilities = node.modifier_capabilities;
1218
1219        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
1220
1221        assert!(node.needs_measure());
1222        assert!(node.needs_layout());
1223        assert_eq!(crate::take_layout_repass_nodes(), vec![11]);
1224        assert!(crate::take_layout_invalidation());
1225    }
1226
1227    #[test]
1228    fn layout_invalidation_skips_repass_while_composing() {
1229        let _guard = crate::render_state::render_state_test_guard();
1230        crate::reset_render_state_for_tests();
1231
1232        let node = Rc::new(RefCell::new(fresh_node()));
1233        {
1234            let mut node = node.borrow_mut();
1235            node.id.set(Some(17));
1236            node.clear_needs_measure();
1237            node.clear_needs_layout();
1238            node.modifier_capabilities = NodeCapabilities::LAYOUT;
1239            node.modifier_child_capabilities = node.modifier_capabilities;
1240        }
1241
1242        let node_for_composition = Rc::clone(&node);
1243        let _composition = crate::run_test_composition(move || {
1244            node_for_composition
1245                .borrow()
1246                .dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
1247        });
1248
1249        let node = node.borrow();
1250        assert!(node.needs_measure());
1251        assert!(node.needs_layout());
1252        assert!(crate::take_layout_repass_nodes().is_empty());
1253        assert!(!crate::take_layout_invalidation());
1254    }
1255
1256    #[test]
1257    fn draw_invalidation_marks_redraw_flag_when_capable() {
1258        let mut node = fresh_node();
1259        node.clear_needs_measure();
1260        node.clear_needs_layout();
1261        node.modifier_capabilities = NodeCapabilities::DRAW;
1262        node.modifier_child_capabilities = node.modifier_capabilities;
1263
1264        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Draw)]);
1265
1266        assert!(node.needs_redraw());
1267        assert!(!node.needs_layout());
1268    }
1269
1270    #[test]
1271    fn semantics_invalidation_sets_semantics_flag_only() {
1272        let mut node = fresh_node();
1273        node.clear_needs_measure();
1274        node.clear_needs_layout();
1275        node.clear_needs_semantics();
1276        node.modifier_capabilities = NodeCapabilities::SEMANTICS;
1277        node.modifier_child_capabilities = node.modifier_capabilities;
1278
1279        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Semantics)]);
1280
1281        assert!(node.needs_semantics());
1282        assert!(!node.needs_measure());
1283        assert!(!node.needs_layout());
1284    }
1285
1286    #[test]
1287    fn pointer_invalidation_requires_pointer_capability() {
1288        let mut node = fresh_node();
1289        node.clear_needs_pointer_pass();
1290        node.modifier_capabilities = NodeCapabilities::DRAW;
1291        node.modifier_child_capabilities = node.modifier_capabilities;
1292        // Note: We don't assert on global take_pointer_invalidation() because
1293        // it's shared across tests running in parallel and causes flakiness.
1294        // The node's local state is sufficient to verify correct dispatch behavior.
1295
1296        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::PointerInput)]);
1297
1298        assert!(!node.needs_pointer_pass());
1299    }
1300
1301    #[test]
1302    fn pointer_invalidation_marks_flag_and_requests_queue() {
1303        let mut node = fresh_node();
1304        node.clear_needs_pointer_pass();
1305        node.modifier_capabilities = NodeCapabilities::POINTER_INPUT;
1306        node.modifier_child_capabilities = node.modifier_capabilities;
1307        // Note: We don't assert on global take_pointer_invalidation() because
1308        // it's shared across tests running in parallel and causes flakiness.
1309        // The node's local state is sufficient to verify correct dispatch behavior.
1310
1311        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::PointerInput)]);
1312
1313        assert!(node.needs_pointer_pass());
1314    }
1315
1316    #[test]
1317    fn focus_invalidation_requires_focus_capability() {
1318        let mut node = fresh_node();
1319        node.clear_needs_focus_sync();
1320        node.modifier_capabilities = NodeCapabilities::DRAW;
1321        node.modifier_child_capabilities = node.modifier_capabilities;
1322        crate::take_focus_invalidation();
1323
1324        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Focus)]);
1325
1326        assert!(!node.needs_focus_sync());
1327        assert!(!crate::take_focus_invalidation());
1328    }
1329
1330    #[test]
1331    fn focus_invalidation_marks_flag_and_requests_queue() {
1332        let mut node = fresh_node();
1333        node.clear_needs_focus_sync();
1334        node.modifier_capabilities = NodeCapabilities::FOCUS;
1335        node.modifier_child_capabilities = node.modifier_capabilities;
1336        crate::take_focus_invalidation();
1337
1338        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Focus)]);
1339
1340        assert!(node.needs_focus_sync());
1341        assert!(crate::take_focus_invalidation());
1342    }
1343
1344    #[test]
1345    fn set_modifier_marks_semantics_dirty() {
1346        let mut node = fresh_node();
1347        node.clear_needs_semantics();
1348        node.set_modifier(Modifier::empty().semantics(|config| {
1349            config.is_clickable = true;
1350        }));
1351
1352        assert!(node.needs_semantics());
1353    }
1354
1355    #[test]
1356    fn modifier_child_capabilities_reflect_chain_head() {
1357        let mut node = fresh_node();
1358        node.set_modifier(Modifier::empty().padding(4.0));
1359        assert!(
1360            node.modifier_child_capabilities()
1361                .contains(NodeCapabilities::LAYOUT),
1362            "padding should introduce layout capability"
1363        );
1364    }
1365}