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        }
367    }
368
369    /// Mark this node as needing measure. Also marks it as needing layout.
370    pub fn mark_needs_measure(&self) {
371        self.needs_measure.set(true);
372        self.needs_layout.set(true);
373    }
374
375    /// Mark this node as needing layout (but not necessarily measure).
376    pub fn mark_needs_layout(&self) {
377        self.needs_layout.set(true);
378    }
379
380    /// Mark this node as needing redraw without forcing measure/layout.
381    pub fn mark_needs_redraw(&self) {
382        self.needs_redraw.set(true);
383        if let Some(id) = self.id.get() {
384            crate::schedule_draw_repass(id);
385        }
386        crate::request_render_invalidation();
387    }
388
389    /// Check if this node needs measure.
390    pub fn needs_measure(&self) -> bool {
391        self.needs_measure.get()
392    }
393
394    /// Check if this node needs layout.
395    pub fn needs_layout(&self) -> bool {
396        self.needs_layout.get()
397    }
398
399    /// Mark this node as needing semantics recomputation.
400    pub fn mark_needs_semantics(&self) {
401        self.needs_semantics.set(true);
402    }
403
404    /// Clear the semantics dirty flag after rebuilding semantics.
405    pub(crate) fn clear_needs_semantics(&self) {
406        self.needs_semantics.set(false);
407    }
408
409    /// Returns true when semantics need to be recomputed.
410    pub fn needs_semantics(&self) -> bool {
411        self.needs_semantics.get()
412    }
413
414    /// Returns true when this node requested a redraw since the last render pass.
415    pub fn needs_redraw(&self) -> bool {
416        self.needs_redraw.get()
417    }
418
419    pub fn clear_needs_redraw(&self) {
420        self.needs_redraw.set(false);
421    }
422
423    fn request_semantics_update(&self) {
424        let already_dirty = self.needs_semantics.replace(true);
425        if already_dirty {
426            return;
427        }
428
429        if let Some(id) = self.id.get() {
430            cranpose_core::queue_semantics_invalidation(id);
431        }
432    }
433
434    /// Clear the measure dirty flag after measuring.
435    pub(crate) fn clear_needs_measure(&self) {
436        self.needs_measure.set(false);
437    }
438
439    /// Clear the layout dirty flag after laying out.
440    pub(crate) fn clear_needs_layout(&self) {
441        self.needs_layout.set(false);
442    }
443
444    /// Marks this node as needing a fresh pointer-input pass.
445    pub fn mark_needs_pointer_pass(&self) {
446        self.needs_pointer_pass.set(true);
447    }
448
449    /// Returns true when pointer-input state needs to be recomputed.
450    pub fn needs_pointer_pass(&self) -> bool {
451        self.needs_pointer_pass.get()
452    }
453
454    /// Clears the pointer-input dirty flag after hosts service it.
455    pub fn clear_needs_pointer_pass(&self) {
456        self.needs_pointer_pass.set(false);
457    }
458
459    /// Marks this node as needing a focus synchronization.
460    pub fn mark_needs_focus_sync(&self) {
461        self.needs_focus_sync.set(true);
462    }
463
464    /// Returns true when focus state needs to be synchronized.
465    pub fn needs_focus_sync(&self) -> bool {
466        self.needs_focus_sync.get()
467    }
468
469    /// Clears the focus dirty flag after the focus manager processes it.
470    pub fn clear_needs_focus_sync(&self) {
471        self.needs_focus_sync.set(false);
472    }
473
474    /// Set this node's ID (called by applier after creation).
475    pub fn set_node_id(&mut self, id: NodeId) {
476        if let Some(existing) = self.id.replace(Some(id)) {
477            unregister_layout_node(existing);
478        }
479        register_layout_node(id, self);
480        self.refresh_registry_state();
481
482        // Propagate the ID to the modifier chain. This triggers a lifecycle update
483        // for nodes that depend on the node ID for invalidation (e.g., ScrollNode).
484        self.modifier_chain.set_node_id(Some(id));
485    }
486
487    /// Get this node's ID.
488    pub fn node_id(&self) -> Option<NodeId> {
489        self.id.get()
490    }
491
492    /// Set this node's parent (called when node is added as child).
493    /// Sets both folded_parent (direct) and parent (first non-virtual ancestor for bubbling).
494    pub fn set_parent(&self, parent: NodeId) {
495        self.folded_parent.set(Some(parent));
496        // For now, parent = folded_parent. Virtual parent skipping requires applier access.
497        // The actual virtual-skipping happens in bubble_measure_dirty via applier traversal.
498        self.parent.set(Some(parent));
499        self.refresh_registry_state();
500    }
501
502    /// Clear this node's parent (called when node is removed from parent).
503    pub fn clear_parent(&self) {
504        self.folded_parent.set(None);
505        self.parent.set(None);
506        self.refresh_registry_state();
507    }
508
509    /// Get this node's parent for dirty flag bubbling (may skip virtual nodes).
510    pub fn parent(&self) -> Option<NodeId> {
511        self.parent.get()
512    }
513
514    /// Get this node's direct parent (may be a virtual node).
515    pub fn folded_parent(&self) -> Option<NodeId> {
516        self.folded_parent.get()
517    }
518
519    /// Returns true if this is a virtual node (transparent container for subcomposition).
520    pub fn is_virtual(&self) -> bool {
521        self.is_virtual
522    }
523
524    pub(crate) fn cache_handles(&self) -> LayoutNodeCacheHandles {
525        self.cache.clone()
526    }
527
528    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
529        self.resolved_modifiers
530    }
531
532    pub fn modifier_capabilities(&self) -> NodeCapabilities {
533        self.modifier_capabilities
534    }
535
536    pub fn modifier_child_capabilities(&self) -> NodeCapabilities {
537        self.modifier_child_capabilities
538    }
539
540    pub fn set_debug_modifiers(&mut self, enabled: bool) {
541        self.debug_modifiers.set(enabled);
542        self.modifier_chain.set_debug_logging(enabled);
543    }
544
545    pub fn debug_modifiers_enabled(&self) -> bool {
546        self.debug_modifiers.get()
547    }
548
549    pub fn modifier_locals_handle(&self) -> ModifierLocalsHandle {
550        self.modifier_chain.modifier_locals_handle()
551    }
552
553    pub fn has_layout_modifier_nodes(&self) -> bool {
554        self.modifier_capabilities
555            .contains(NodeCapabilities::LAYOUT)
556    }
557
558    pub fn has_draw_modifier_nodes(&self) -> bool {
559        self.modifier_capabilities.contains(NodeCapabilities::DRAW)
560    }
561
562    pub fn has_pointer_input_modifier_nodes(&self) -> bool {
563        self.modifier_capabilities
564            .contains(NodeCapabilities::POINTER_INPUT)
565    }
566
567    pub fn has_semantics_modifier_nodes(&self) -> bool {
568        self.modifier_capabilities
569            .contains(NodeCapabilities::SEMANTICS)
570    }
571
572    pub fn has_focus_modifier_nodes(&self) -> bool {
573        self.modifier_capabilities.contains(NodeCapabilities::FOCUS)
574    }
575
576    fn refresh_registry_state(&self) {
577        if let Some(id) = self.id.get() {
578            let parent = self.parent();
579            let capabilities = self.modifier_child_capabilities();
580            let modifier_locals = self.modifier_locals_handle();
581            LAYOUT_NODE_REGISTRY.with(|registry| {
582                if let Some(entry) = registry.borrow_mut().get_mut(&id) {
583                    entry.parent = parent;
584                    entry.modifier_child_capabilities = capabilities;
585                    entry.modifier_locals = modifier_locals;
586                }
587            });
588        }
589    }
590
591    pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
592        self.modifier_slices_snapshot.borrow().clone()
593    }
594
595    // ═══════════════════════════════════════════════════════════════════════
596    // Retained Layout State API
597    // ═══════════════════════════════════════════════════════════════════════
598
599    /// Returns a clone of the current layout state.
600    pub fn layout_state(&self) -> LayoutState {
601        self.layout_state.borrow().clone()
602    }
603
604    /// Returns the measured size of this node.
605    pub fn measured_size(&self) -> Size {
606        self.layout_state.borrow().size
607    }
608
609    /// Returns the position of this node relative to its parent.
610    pub fn position(&self) -> Point {
611        self.layout_state.borrow().position
612    }
613
614    /// Returns true if this node has been placed in the current layout pass.
615    pub fn is_placed(&self) -> bool {
616        self.layout_state.borrow().is_placed
617    }
618
619    /// Updates the measured size of this node. Called during measurement.
620    pub fn set_measured_size(&self, size: Size) {
621        let mut state = self.layout_state.borrow_mut();
622        state.size = size;
623    }
624
625    /// Updates the position of this node. Called during placement.
626    pub fn set_position(&self, position: Point) {
627        let mut state = self.layout_state.borrow_mut();
628        state.position = position;
629        state.is_placed = true;
630    }
631
632    /// Records the constraints used for measurement. Used for relayout optimization.
633    pub fn set_measurement_constraints(&self, constraints: Constraints) {
634        self.layout_state.borrow_mut().measurement_constraints = constraints;
635    }
636
637    /// Records the content offset (e.g. from padding).
638    pub fn set_content_offset(&self, offset: Point) {
639        self.layout_state.borrow_mut().content_offset = offset;
640    }
641
642    /// Clears the is_placed flag. Called at the start of a layout pass.
643    pub fn clear_placed(&self) {
644        self.layout_state.borrow_mut().is_placed = false;
645    }
646
647    pub fn semantics_configuration(&self) -> Option<SemanticsConfiguration> {
648        crate::modifier::collect_semantics_from_chain(self.modifier_chain.chain())
649    }
650
651    /// Returns a reference to the modifier chain for layout/draw pipeline integration.
652    pub(crate) fn modifier_chain(&self) -> &ModifierChainHandle {
653        &self.modifier_chain
654    }
655
656    /// Access the text field modifier node (if present) with a mutable callback.
657    ///
658    /// This is used for keyboard event dispatch to text fields.
659    /// Returns `None` if no text field modifier is found in the chain.
660    pub fn with_text_field_modifier_mut<R>(
661        &mut self,
662        f: impl FnMut(&mut crate::TextFieldModifierNode) -> R,
663    ) -> Option<R> {
664        self.modifier_chain.with_text_field_modifier_mut(f)
665    }
666
667    /// Returns a handle to the shared layout state.
668    /// Used by layout system to update state without borrowing the Applier.
669    pub fn layout_state_handle(&self) -> Rc<RefCell<LayoutState>> {
670        self.layout_state.clone()
671    }
672}
673impl Clone for LayoutNode {
674    fn clone(&self) -> Self {
675        let mut node = Self {
676            modifier: self.modifier.clone(),
677            modifier_chain: ModifierChainHandle::new(),
678            resolved_modifiers: ResolvedModifiers::default(),
679            modifier_capabilities: self.modifier_capabilities,
680            modifier_child_capabilities: self.modifier_child_capabilities,
681            measure_policy: self.measure_policy.clone(),
682            children: self.children.clone(),
683            cache: self.cache.clone(),
684            needs_measure: Cell::new(self.needs_measure.get()),
685            needs_layout: Cell::new(self.needs_layout.get()),
686            needs_semantics: Cell::new(self.needs_semantics.get()),
687            needs_redraw: Cell::new(self.needs_redraw.get()),
688            needs_pointer_pass: Cell::new(self.needs_pointer_pass.get()),
689            needs_focus_sync: Cell::new(self.needs_focus_sync.get()),
690            parent: Cell::new(self.parent.get()),
691            folded_parent: Cell::new(self.folded_parent.get()),
692            id: Cell::new(None),
693            debug_modifiers: Cell::new(self.debug_modifiers.get()),
694            is_virtual: self.is_virtual,
695            virtual_children_count: Cell::new(self.virtual_children_count.get()),
696            modifier_slices_buffer: RefCell::new(ModifierNodeSlices::default()),
697            modifier_slices_snapshot: RefCell::new(Rc::default()),
698            // Share the same layout state across clones
699            layout_state: self.layout_state.clone(),
700        };
701        node.sync_modifier_chain();
702        node
703    }
704}
705
706impl Node for LayoutNode {
707    fn mount(&mut self) {
708        let (chain, mut context) = self.modifier_chain.chain_and_context_mut();
709        chain.repair_chain();
710        chain.attach_nodes(&mut *context);
711    }
712
713    fn unmount(&mut self) {
714        self.modifier_chain.chain_mut().detach_nodes();
715    }
716
717    fn set_node_id(&mut self, id: NodeId) {
718        // Delegate to inherent method to ensure proper registration and chain updates
719        LayoutNode::set_node_id(self, id);
720    }
721
722    fn insert_child(&mut self, child: NodeId) {
723        if self.children.contains(&child) {
724            return;
725        }
726        if is_virtual_node(child) {
727            let count = self.virtual_children_count.get();
728            self.virtual_children_count.set(count + 1);
729        }
730        self.children.push(child);
731        self.cache.clear();
732        self.mark_needs_measure();
733    }
734
735    fn remove_child(&mut self, child: NodeId) {
736        let before = self.children.len();
737        self.children.retain(|&id| id != child);
738        if self.children.len() < before {
739            if is_virtual_node(child) {
740                let count = self.virtual_children_count.get();
741                if count > 0 {
742                    self.virtual_children_count.set(count - 1);
743                }
744            }
745            self.cache.clear();
746            self.mark_needs_measure();
747        }
748    }
749
750    fn move_child(&mut self, from: usize, to: usize) {
751        if from == to || from >= self.children.len() {
752            return;
753        }
754        let child = self.children.remove(from);
755        let target = to.min(self.children.len());
756        self.children.insert(target, child);
757        self.cache.clear();
758        self.mark_needs_measure();
759    }
760
761    fn update_children(&mut self, children: &[NodeId]) {
762        self.children.clear();
763        self.children.extend_from_slice(children);
764        self.cache.clear();
765        self.mark_needs_measure();
766    }
767
768    fn children(&self) -> Vec<NodeId> {
769        self.children.clone()
770    }
771
772    fn on_attached_to_parent(&mut self, parent: NodeId) {
773        self.set_parent(parent);
774    }
775
776    fn on_removed_from_parent(&mut self) {
777        self.clear_parent();
778    }
779
780    fn parent(&self) -> Option<NodeId> {
781        self.parent.get()
782    }
783
784    fn mark_needs_layout(&self) {
785        self.needs_layout.set(true);
786    }
787
788    fn needs_layout(&self) -> bool {
789        self.needs_layout.get()
790    }
791
792    fn mark_needs_measure(&self) {
793        self.needs_measure.set(true);
794        self.needs_layout.set(true);
795    }
796
797    fn needs_measure(&self) -> bool {
798        self.needs_measure.get()
799    }
800
801    fn mark_needs_semantics(&self) {
802        self.needs_semantics.set(true);
803    }
804
805    fn needs_semantics(&self) -> bool {
806        self.needs_semantics.get()
807    }
808
809    /// Minimal parent setter for dirty flag bubbling.
810    /// Only sets the parent Cell without triggering registry updates.
811    /// This is used during SubcomposeLayout measurement where we need parent
812    /// pointers for bubble_measure_dirty but don't want full attachment side effects.
813    fn set_parent_for_bubbling(&mut self, parent: NodeId) {
814        self.parent.set(Some(parent));
815    }
816}
817
818impl Drop for LayoutNode {
819    fn drop(&mut self) {
820        if let Some(id) = self.id.get() {
821            unregister_layout_node(id);
822        }
823    }
824}
825
826thread_local! {
827    static LAYOUT_NODE_REGISTRY: RefCell<HashMap<NodeId, LayoutNodeRegistryEntry>> =
828        RefCell::new(HashMap::new());
829    // Start at a high value to avoid conflicts with SlotTable IDs (which start low).
830    // We use a value compatible with 32-bit (WASM) usize to prevent truncation issues.
831    // 0xC0000000 is ~3.2 billion, leaving ~1 billion IDs before overflow.
832    static VIRTUAL_NODE_ID_COUNTER: std::sync::atomic::AtomicUsize = const { std::sync::atomic::AtomicUsize::new(0xC0000000) };
833}
834
835struct LayoutNodeRegistryEntry {
836    parent: Option<NodeId>,
837    modifier_child_capabilities: NodeCapabilities,
838    modifier_locals: ModifierLocalsHandle,
839    is_virtual: bool,
840}
841
842pub(crate) fn register_layout_node(id: NodeId, node: &LayoutNode) {
843    LAYOUT_NODE_REGISTRY.with(|registry| {
844        registry.borrow_mut().insert(
845            id,
846            LayoutNodeRegistryEntry {
847                parent: node.parent(),
848                modifier_child_capabilities: node.modifier_child_capabilities(),
849                modifier_locals: node.modifier_locals_handle(),
850                is_virtual: node.is_virtual(),
851            },
852        );
853    });
854}
855
856pub(crate) fn unregister_layout_node(id: NodeId) {
857    LAYOUT_NODE_REGISTRY.with(|registry| {
858        registry.borrow_mut().remove(&id);
859    });
860}
861
862pub(crate) fn is_virtual_node(id: NodeId) -> bool {
863    LAYOUT_NODE_REGISTRY.with(|registry| {
864        registry
865            .borrow()
866            .get(&id)
867            .map(|entry| entry.is_virtual)
868            .unwrap_or(false)
869    })
870}
871
872pub(crate) fn allocate_virtual_node_id() -> NodeId {
873    use std::sync::atomic::Ordering;
874    // Allocate IDs from a high range to avoid conflict with SlotTable IDs.
875    // Thread-local counter avoids cross-thread contention (WASM is single-threaded anyway).
876    VIRTUAL_NODE_ID_COUNTER.with(|counter| counter.fetch_add(1, Ordering::Relaxed))
877}
878
879fn resolve_modifier_local_from_parent_chain(
880    start: Option<NodeId>,
881    token: ModifierLocalToken,
882) -> Option<ResolvedModifierLocal> {
883    let mut current = start;
884    while let Some(parent_id) = current {
885        let (next_parent, resolved) = LAYOUT_NODE_REGISTRY.with(|registry| {
886            let registry = registry.borrow();
887            if let Some(entry) = registry.get(&parent_id) {
888                let resolved = if entry
889                    .modifier_child_capabilities
890                    .contains(NodeCapabilities::MODIFIER_LOCALS)
891                {
892                    entry
893                        .modifier_locals
894                        .borrow()
895                        .resolve(token)
896                        .map(|value| value.with_source(ModifierLocalSource::Ancestor))
897                } else {
898                    None
899                };
900                (entry.parent, resolved)
901            } else {
902                (None, None)
903            }
904        });
905        if let Some(value) = resolved {
906            return Some(value);
907        }
908        current = next_parent;
909    }
910    None
911}
912
913#[cfg(test)]
914mod tests {
915    use super::*;
916    use cranpose_ui_graphics::Size as GeometrySize;
917    use cranpose_ui_layout::{Measurable, MeasureResult};
918    use std::rc::Rc;
919
920    #[derive(Default)]
921    struct TestMeasurePolicy;
922
923    impl MeasurePolicy for TestMeasurePolicy {
924        fn measure(
925            &self,
926            _measurables: &[Box<dyn Measurable>],
927            _constraints: Constraints,
928        ) -> MeasureResult {
929            MeasureResult::new(
930                GeometrySize {
931                    width: 0.0,
932                    height: 0.0,
933                },
934                Vec::new(),
935            )
936        }
937
938        fn min_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
939            0.0
940        }
941
942        fn max_intrinsic_width(&self, _measurables: &[Box<dyn Measurable>], _height: f32) -> f32 {
943            0.0
944        }
945
946        fn min_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
947            0.0
948        }
949
950        fn max_intrinsic_height(&self, _measurables: &[Box<dyn Measurable>], _width: f32) -> f32 {
951            0.0
952        }
953    }
954
955    fn fresh_node() -> LayoutNode {
956        LayoutNode::new(Modifier::empty(), Rc::new(TestMeasurePolicy))
957    }
958
959    fn invalidation(kind: InvalidationKind) -> ModifierInvalidation {
960        ModifierInvalidation::new(kind, NodeCapabilities::for_invalidation(kind))
961    }
962
963    #[test]
964    fn layout_invalidation_requires_layout_capability() {
965        let mut node = fresh_node();
966        node.clear_needs_measure();
967        node.clear_needs_layout();
968        node.modifier_capabilities = NodeCapabilities::DRAW;
969        node.modifier_child_capabilities = node.modifier_capabilities;
970
971        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
972
973        assert!(!node.needs_measure());
974        assert!(!node.needs_layout());
975    }
976
977    #[test]
978    fn semantics_configuration_reflects_modifier_state() {
979        let mut node = fresh_node();
980        node.set_modifier(Modifier::empty().semantics(|config| {
981            config.content_description = Some("greeting".into());
982            config.is_clickable = true;
983        }));
984
985        let config = node
986            .semantics_configuration()
987            .expect("expected semantics configuration");
988        assert_eq!(config.content_description.as_deref(), Some("greeting"));
989        assert!(config.is_clickable);
990    }
991
992    #[test]
993    fn layout_invalidation_marks_flags_when_capability_present() {
994        let mut node = fresh_node();
995        node.clear_needs_measure();
996        node.clear_needs_layout();
997        node.modifier_capabilities = NodeCapabilities::LAYOUT;
998        node.modifier_child_capabilities = node.modifier_capabilities;
999
1000        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Layout)]);
1001
1002        assert!(node.needs_measure());
1003        assert!(node.needs_layout());
1004    }
1005
1006    #[test]
1007    fn draw_invalidation_marks_redraw_flag_when_capable() {
1008        let mut node = fresh_node();
1009        node.clear_needs_measure();
1010        node.clear_needs_layout();
1011        node.modifier_capabilities = NodeCapabilities::DRAW;
1012        node.modifier_child_capabilities = node.modifier_capabilities;
1013
1014        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Draw)]);
1015
1016        assert!(node.needs_redraw());
1017        assert!(!node.needs_layout());
1018    }
1019
1020    #[test]
1021    fn semantics_invalidation_sets_semantics_flag_only() {
1022        let mut node = fresh_node();
1023        node.clear_needs_measure();
1024        node.clear_needs_layout();
1025        node.clear_needs_semantics();
1026        node.modifier_capabilities = NodeCapabilities::SEMANTICS;
1027        node.modifier_child_capabilities = node.modifier_capabilities;
1028
1029        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Semantics)]);
1030
1031        assert!(node.needs_semantics());
1032        assert!(!node.needs_measure());
1033        assert!(!node.needs_layout());
1034    }
1035
1036    #[test]
1037    fn pointer_invalidation_requires_pointer_capability() {
1038        let mut node = fresh_node();
1039        node.clear_needs_pointer_pass();
1040        node.modifier_capabilities = NodeCapabilities::DRAW;
1041        node.modifier_child_capabilities = node.modifier_capabilities;
1042        // Note: We don't assert on global take_pointer_invalidation() because
1043        // it's shared across tests running in parallel and causes flakiness.
1044        // The node's local state is sufficient to verify correct dispatch behavior.
1045
1046        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::PointerInput)]);
1047
1048        assert!(!node.needs_pointer_pass());
1049    }
1050
1051    #[test]
1052    fn pointer_invalidation_marks_flag_and_requests_queue() {
1053        let mut node = fresh_node();
1054        node.clear_needs_pointer_pass();
1055        node.modifier_capabilities = NodeCapabilities::POINTER_INPUT;
1056        node.modifier_child_capabilities = node.modifier_capabilities;
1057        // Note: We don't assert on global take_pointer_invalidation() because
1058        // it's shared across tests running in parallel and causes flakiness.
1059        // The node's local state is sufficient to verify correct dispatch behavior.
1060
1061        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::PointerInput)]);
1062
1063        assert!(node.needs_pointer_pass());
1064    }
1065
1066    #[test]
1067    fn focus_invalidation_requires_focus_capability() {
1068        let mut node = fresh_node();
1069        node.clear_needs_focus_sync();
1070        node.modifier_capabilities = NodeCapabilities::DRAW;
1071        node.modifier_child_capabilities = node.modifier_capabilities;
1072        crate::take_focus_invalidation();
1073
1074        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Focus)]);
1075
1076        assert!(!node.needs_focus_sync());
1077        assert!(!crate::take_focus_invalidation());
1078    }
1079
1080    #[test]
1081    fn focus_invalidation_marks_flag_and_requests_queue() {
1082        let mut node = fresh_node();
1083        node.clear_needs_focus_sync();
1084        node.modifier_capabilities = NodeCapabilities::FOCUS;
1085        node.modifier_child_capabilities = node.modifier_capabilities;
1086        crate::take_focus_invalidation();
1087
1088        node.dispatch_modifier_invalidations(&[invalidation(InvalidationKind::Focus)]);
1089
1090        assert!(node.needs_focus_sync());
1091        assert!(crate::take_focus_invalidation());
1092    }
1093
1094    #[test]
1095    fn set_modifier_marks_semantics_dirty() {
1096        let mut node = fresh_node();
1097        node.clear_needs_semantics();
1098        node.set_modifier(Modifier::empty().semantics(|config| {
1099            config.is_clickable = true;
1100        }));
1101
1102        assert!(node.needs_semantics());
1103    }
1104
1105    #[test]
1106    fn modifier_child_capabilities_reflect_chain_head() {
1107        let mut node = fresh_node();
1108        node.set_modifier(Modifier::empty().padding(4.0));
1109        assert!(
1110            node.modifier_child_capabilities()
1111                .contains(NodeCapabilities::LAYOUT),
1112            "padding should introduce layout capability"
1113        );
1114    }
1115}