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