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