cranpose-ui 0.0.58

UI primitives for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
use std::cell::{Cell, Ref, RefCell, RefMut};
use std::collections::HashMap;
use std::rc::Rc;

use cranpose_core::{
    Composer, NodeError, NodeId, Phase, SlotId, SlotTable, SlotsHost, SubcomposeState,
};

use crate::modifier::{
    collect_modifier_slices_into, Modifier, ModifierChainHandle, ModifierNodeSlices, Point,
    ResolvedModifiers, Size,
};
use crate::widgets::nodes::{
    allocate_virtual_node_id, is_virtual_node, register_layout_node, LayoutNode, LayoutState,
};

use cranpose_foundation::{InvalidationKind, ModifierInvalidation, NodeCapabilities};

pub use cranpose_ui_layout::{Constraints, MeasureResult, Placement};

/// Representation of a subcomposed child that can later be measured by the policy.
///
/// In lazy layouts, this represents an item that has been composed but may or
/// may not have been measured yet. Call `measure()` to get the actual size.
#[derive(Clone, Copy, Debug)]
pub struct SubcomposeChild {
    node_id: NodeId,
    /// Measured size of the child (set after measurement).
    /// Width in x, height in y.
    measured_size: Option<Size>,
}

impl SubcomposeChild {
    pub fn new(node_id: NodeId) -> Self {
        Self {
            node_id,
            measured_size: None,
        }
    }

    /// Creates a SubcomposeChild with a known size.
    pub fn with_size(node_id: NodeId, size: Size) -> Self {
        Self {
            node_id,
            measured_size: Some(size),
        }
    }

    pub fn node_id(&self) -> NodeId {
        self.node_id
    }

    /// Returns the measured size of this child.
    ///
    /// Returns a default size if the child hasn't been measured yet.
    /// For lazy layouts using placeholder sizes, this returns the estimated size.
    pub fn size(&self) -> Size {
        self.measured_size.unwrap_or(Size {
            width: 0.0,
            height: 0.0,
        })
    }

    /// Returns the measured width.
    pub fn width(&self) -> f32 {
        self.size().width
    }

    /// Returns the measured height.
    pub fn height(&self) -> f32 {
        self.size().height
    }

    /// Sets the measured size for this child.
    pub fn set_size(&mut self, size: Size) {
        self.measured_size = Some(size);
    }
}

impl PartialEq for SubcomposeChild {
    fn eq(&self, other: &Self) -> bool {
        self.node_id == other.node_id
    }
}

/// A measured child that is ready to be placed.
///
/// This is a type alias for the concrete `Placeable` struct from `cranpose_ui_layout`.
/// In subcompose layouts, placement is handled by returning a list of `Placement`s,
/// so the `place()` callback is not used.
pub type SubcomposePlaceable = cranpose_ui_layout::Placeable;

/// Base trait for measurement scopes.
pub trait SubcomposeLayoutScope {
    fn constraints(&self) -> Constraints;

    fn layout<I>(&mut self, width: f32, height: f32, placements: I) -> MeasureResult
    where
        I: IntoIterator<Item = Placement>,
    {
        MeasureResult::new(Size { width, height }, placements.into_iter().collect())
    }
}

/// Public trait exposed to measure policies for subcomposition.
pub trait SubcomposeMeasureScope: SubcomposeLayoutScope {
    fn subcompose<Content>(&mut self, slot_id: SlotId, content: Content) -> Vec<SubcomposeChild>
    where
        Content: FnMut() + 'static;

    /// Measures a subcomposed child with the given constraints.
    fn measure(&mut self, child: SubcomposeChild, constraints: Constraints) -> SubcomposePlaceable;

    /// Checks if a node has no parent (is a root node).
    /// Used to filter subcompose results to only include true root nodes.
    fn node_has_no_parent(&self, node_id: NodeId) -> bool;
}

/// Concrete implementation of [`SubcomposeMeasureScope`].
pub struct SubcomposeMeasureScopeImpl<'a> {
    composer: Composer,
    state: &'a mut SubcomposeState,
    constraints: Constraints,
    measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
    error: &'a RefCell<Option<NodeError>>,
    parent_handle: SubcomposeLayoutNodeHandle,
    root_id: NodeId,
}

impl<'a> SubcomposeMeasureScopeImpl<'a> {
    pub fn new(
        composer: Composer,
        state: &'a mut SubcomposeState,
        constraints: Constraints,
        measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
        error: &'a RefCell<Option<NodeError>>,

        parent_handle: SubcomposeLayoutNodeHandle,
        root_id: NodeId,
    ) -> Self {
        Self {
            composer,
            state,
            constraints,
            measurer,
            error,
            parent_handle,
            root_id,
        }
    }

    fn record_error(&self, err: NodeError) {
        let mut slot = self.error.borrow_mut();
        if slot.is_none() {
            eprintln!("[SubcomposeLayout] Error suppressed: {:?}", err);
            *slot = Some(err);
        }
    }

    fn perform_subcompose<Content>(&mut self, slot_id: SlotId, content: Content) -> Vec<NodeId>
    where
        Content: FnMut() + 'static,
    {
        let content_holder = self.state.callback_holder(slot_id);
        content_holder.update(content);
        let mut inner = self.parent_handle.inner.borrow_mut();

        // Reuse or create virtual node
        let (virtual_node_id, is_reused) =
            if let Some(node_id) = self.state.take_node_from_reusables(slot_id) {
                (node_id, true)
            } else {
                let id = allocate_virtual_node_id();
                let node = LayoutNode::new_virtual();
                // CRITICAL FIX: Register virtual node in Applier so that insert_child commands
                // can find it. Previously, virtual nodes were only stored in inner.virtual_nodes
                // which caused applier.get_mut(virtual_node_id) to fail, breaking child attachment.
                if let Err(e) = self
                    .composer
                    .register_virtual_node(id, Box::new(node.clone()))
                {
                    eprintln!(
                        "[Subcompose] Failed to register virtual node {}: {:?}",
                        id, e
                    );
                }
                register_layout_node(id, &node);

                inner.virtual_nodes.insert(id, Rc::new(node));
                inner.children.push(id);
                (id, false)
            };

        // Keep the slot root in the outer parent frame so SyncChildren preserves
        // the virtual subtree instead of deleting it after subcomposition.
        self.composer.record_subcompose_child(virtual_node_id);

        // Keep both the retained virtual-node clone and the applier copy wired to the
        // live subcompose root so bubbling can cross the virtual slot boundary.
        if let Some(v_node) = inner.virtual_nodes.get(&virtual_node_id) {
            v_node.set_parent(self.root_id);
        }

        drop(inner);

        let _ = self
            .composer
            .with_node_mut::<LayoutNode, _>(virtual_node_id, |node| {
                node.set_parent(self.root_id);
            });

        // CRITICAL FIX: Clear children of reused virtual nodes BEFORE subcomposing new content.
        // Without this, old children remain attached when the node is reused for different items,
        // causing items from different scroll positions to interleave (e.g., [1,16,31,2,17,32...]).
        if is_reused {
            self.composer.clear_node_children(virtual_node_id);
        }

        let slot_host = self.state.get_or_create_slots(slot_id);
        let holder_for_slot = content_holder.clone();
        let scopes = self
            .composer
            .subcompose_slot(&slot_host, Some(virtual_node_id), move |_| {
                compose_subcompose_slot_content(holder_for_slot.clone());
            })
            .map(|(_, scopes)| scopes)
            .unwrap_or_default();

        self.state
            .register_active(slot_id, &[virtual_node_id], &scopes);

        // CRITICAL FIX: Read children from the Applier's copy of the virtual node,
        // NOT from inner.virtual_nodes. The Applier's copy received insert_child calls
        // during subcomposition, while inner.virtual_nodes is an out-of-sync clone.
        self.composer.get_node_children(virtual_node_id).to_vec()
    }
}

impl<'a> SubcomposeLayoutScope for SubcomposeMeasureScopeImpl<'a> {
    fn constraints(&self) -> Constraints {
        self.constraints
    }
}

impl<'a> SubcomposeMeasureScope for SubcomposeMeasureScopeImpl<'a> {
    fn subcompose<Content>(&mut self, slot_id: SlotId, content: Content) -> Vec<SubcomposeChild>
    where
        Content: FnMut() + 'static,
    {
        let nodes = self.perform_subcompose(slot_id, content);
        nodes.into_iter().map(SubcomposeChild::new).collect()
    }

    fn measure(&mut self, child: SubcomposeChild, constraints: Constraints) -> SubcomposePlaceable {
        if self.error.borrow().is_some() {
            // Already in error state - return zero-size placeable
            return SubcomposePlaceable::value(0.0, 0.0, child.node_id);
        }

        if let Err(err) = self.composer.apply_pending_commands() {
            self.record_error(err);
            return SubcomposePlaceable::value(0.0, 0.0, child.node_id);
        }

        let size = (self.measurer)(child.node_id, constraints);
        SubcomposePlaceable::value(size.width, size.height, child.node_id)
    }

    fn node_has_no_parent(&self, node_id: NodeId) -> bool {
        self.composer.node_has_no_parent(node_id)
    }
}

impl<'a> SubcomposeMeasureScopeImpl<'a> {
    /// Subcomposes content and assigns estimated sizes to children.
    ///
    /// This is used by lazy layouts where true measurement happens later.
    /// The `estimate_size` function provides size estimates based on index.
    pub fn subcompose_with_size<Content, F>(
        &mut self,
        slot_id: SlotId,
        content: Content,
        estimate_size: F,
    ) -> Vec<SubcomposeChild>
    where
        Content: FnMut() + 'static,
        F: Fn(usize) -> Size,
    {
        let nodes = self.perform_subcompose(slot_id, content);
        nodes
            .into_iter()
            .enumerate()
            .map(|(i, node_id)| SubcomposeChild::with_size(node_id, estimate_size(i)))
            .collect()
    }

    /// Returns the number of active slots in the subcompose state.
    ///
    /// Used by lazy layouts to report statistics about slot usage.
    pub fn active_slots_count(&self) -> usize {
        self.state.active_slots_count()
    }

    /// Returns the number of reusable slots in the pool.
    ///
    /// Used by lazy layouts to report statistics about cached slots.
    pub fn reusable_slots_count(&self) -> usize {
        self.state.reusable_slots_count()
    }

    /// Registers the content type for a slot.
    ///
    /// Call this before `subcompose()` to enable content-type-aware slot reuse.
    /// If the policy supports content types (like `ContentTypeReusePolicy`),
    /// slots with matching content types can reuse each other's nodes.
    pub fn register_content_type(&mut self, slot_id: SlotId, content_type: u64) {
        self.state.register_content_type(slot_id, content_type);
    }

    /// Updates the content type for a slot, handling Some→None transitions.
    ///
    /// If `content_type` is `Some(type)`, registers the type for the slot.
    /// If `content_type` is `None`, removes any previously registered type.
    /// This ensures stale types don't drive incorrect reuse after transitions.
    pub fn update_content_type(&mut self, slot_id: SlotId, content_type: Option<u64>) {
        self.state.update_content_type(slot_id, content_type);
    }

    /// Returns whether the last subcomposed slot was reused.
    ///
    /// Returns `Some(true)` if the slot already existed (was reused from pool or
    /// was recomposed), `Some(false)` if it was newly created, or `None` if no
    /// slot has been subcomposed yet this pass.
    ///
    /// This is useful for tracking composition statistics in lazy layouts.
    pub fn was_last_slot_reused(&self) -> Option<bool> {
        self.state.was_last_slot_reused()
    }
}

fn compose_subcompose_slot_content(holder: cranpose_core::CallbackHolder) {
    cranpose_core::with_current_composer(|composer| {
        let holder_for_recompose = holder.clone();
        composer.set_recranpose_callback(move |_composer| {
            compose_subcompose_slot_content(holder_for_recompose.clone());
        });
    });

    let invoke = holder.clone_rc();
    invoke();
}

/// Trait object representing a reusable measure policy.
pub type MeasurePolicy =
    dyn for<'scope> Fn(&mut SubcomposeMeasureScopeImpl<'scope>, Constraints) -> MeasureResult;

/// Node responsible for orchestrating measure-time subcomposition.
pub struct SubcomposeLayoutNode {
    inner: Rc<RefCell<SubcomposeLayoutNodeInner>>,
    /// Parent tracking for dirty flag bubbling (P0.2 fix)
    parent: Cell<Option<NodeId>>,
    /// Node's own ID
    id: Cell<Option<NodeId>>,
    // Dirty flags for selective measure/layout/render
    needs_measure: Cell<bool>,
    needs_layout: Cell<bool>,
    needs_semantics: Cell<bool>,
    needs_redraw: Cell<bool>,
    needs_pointer_pass: Cell<bool>,
    needs_focus_sync: Cell<bool>,
    virtual_children_count: Cell<usize>,
    /// Retained layout state (size, position) for rendering.
    layout_state: RefCell<LayoutState>,
    // Caching for modifier slices to avoid repeated allocation
    modifier_slices_buffer: RefCell<ModifierNodeSlices>,
    modifier_slices_snapshot: RefCell<Rc<ModifierNodeSlices>>,
    modifier_slices_dirty: Cell<bool>,
}

impl SubcomposeLayoutNode {
    pub fn new(modifier: Modifier, measure_policy: Rc<MeasurePolicy>) -> Self {
        let inner = Rc::new(RefCell::new(SubcomposeLayoutNodeInner::new(measure_policy)));
        let node = Self {
            inner,
            parent: Cell::new(None),
            id: Cell::new(None),
            needs_measure: Cell::new(true),
            needs_layout: Cell::new(true),
            needs_semantics: Cell::new(true),
            needs_redraw: Cell::new(true),
            needs_pointer_pass: Cell::new(false),
            needs_focus_sync: Cell::new(false),
            virtual_children_count: Cell::new(0),
            layout_state: RefCell::new(LayoutState::default()),
            modifier_slices_buffer: RefCell::new(ModifierNodeSlices::default()),
            modifier_slices_snapshot: RefCell::new(Rc::default()),
            modifier_slices_dirty: Cell::new(true),
        };
        // Set modifier and dispatch invalidations after borrow is released
        // Pass empty prev_caps since this is initial construction
        let (invalidations, _) = node.inner.borrow_mut().set_modifier_collect(modifier);
        node.dispatch_modifier_invalidations(&invalidations, NodeCapabilities::empty());
        node.update_modifier_slices_cache();
        node
    }

    /// Creates a SubcomposeLayoutNode with ContentTypeReusePolicy.
    ///
    /// Use this for lazy lists to enable content-type-aware slot reuse.
    /// Slots with matching content types can reuse each other's nodes,
    /// improving efficiency when scrolling through items with different types.
    pub fn with_content_type_policy(modifier: Modifier, measure_policy: Rc<MeasurePolicy>) -> Self {
        let mut inner_data = SubcomposeLayoutNodeInner::new(measure_policy);
        inner_data
            .state
            .set_policy(Box::new(cranpose_core::ContentTypeReusePolicy::new()));
        let inner = Rc::new(RefCell::new(inner_data));
        let node = Self {
            inner,
            parent: Cell::new(None),
            id: Cell::new(None),
            needs_measure: Cell::new(true),
            needs_layout: Cell::new(true),
            needs_semantics: Cell::new(true),
            needs_redraw: Cell::new(true),
            needs_pointer_pass: Cell::new(false),
            needs_focus_sync: Cell::new(false),
            virtual_children_count: Cell::new(0),
            layout_state: RefCell::new(LayoutState::default()),
            modifier_slices_buffer: RefCell::new(ModifierNodeSlices::default()),
            modifier_slices_snapshot: RefCell::new(Rc::default()),
            modifier_slices_dirty: Cell::new(true),
        };
        // Set modifier and dispatch invalidations after borrow is released
        // Pass empty prev_caps since this is initial construction
        let (invalidations, _) = node.inner.borrow_mut().set_modifier_collect(modifier);
        node.dispatch_modifier_invalidations(&invalidations, NodeCapabilities::empty());
        node.update_modifier_slices_cache();
        node
    }

    pub fn handle(&self) -> SubcomposeLayoutNodeHandle {
        SubcomposeLayoutNodeHandle {
            inner: Rc::clone(&self.inner),
        }
    }

    #[doc(hidden)]
    pub fn debug_scope_ids_by_slot(&self) -> Vec<(u64, Vec<usize>)> {
        self.inner.borrow().state.debug_scope_ids_by_slot()
    }

    #[doc(hidden)]
    pub fn debug_slot_table_for_slot(
        &self,
        slot_id: cranpose_core::SlotId,
    ) -> Option<Vec<(usize, String)>> {
        self.inner.borrow().state.debug_slot_table_for_slot(slot_id)
    }

    #[doc(hidden)]
    pub fn debug_slot_table_groups_for_slot(
        &self,
        slot_id: cranpose_core::SlotId,
    ) -> Option<Vec<cranpose_core::subcompose::DebugSlotGroup>> {
        self.inner
            .borrow()
            .state
            .debug_slot_table_groups_for_slot(slot_id)
    }

    pub fn set_measure_policy(&mut self, policy: Rc<MeasurePolicy>) {
        let mut inner = self.inner.borrow_mut();
        if Rc::ptr_eq(&inner.measure_policy, &policy) {
            return;
        }
        inner.set_measure_policy(policy);
        drop(inner);
        self.invalidate_subcomposition();
    }

    pub fn set_modifier(&mut self, modifier: Modifier) {
        // Capture capabilities BEFORE updating to detect removed modifiers
        let prev_caps = self.modifier_capabilities();
        // Collect invalidations while inner is borrowed, then dispatch after release
        let (invalidations, modifier_changed) = {
            let mut inner = self.inner.borrow_mut();
            inner.set_modifier_collect(modifier)
        };
        // Now dispatch invalidations after the borrow is released
        // Pass both prev and curr caps so removed modifiers still trigger invalidation
        self.dispatch_modifier_invalidations(&invalidations, prev_caps);
        self.update_modifier_slices_cache();
        if modifier_changed {
            self.mark_needs_measure();
            self.request_semantics_update();
        }
    }

    /// Updates the cached modifier slices from the modifier chain.
    fn update_modifier_slices_cache(&self) {
        let inner = self.inner.borrow();
        let mut buffer = self.modifier_slices_buffer.borrow_mut();
        collect_modifier_slices_into(inner.modifier_chain.chain(), &mut buffer);
        *self.modifier_slices_snapshot.borrow_mut() = Rc::new(buffer.clone());
        self.modifier_slices_dirty.set(false);
    }

    pub fn set_debug_modifiers(&mut self, enabled: bool) {
        self.inner.borrow_mut().set_debug_modifiers(enabled);
    }

    pub fn modifier(&self) -> Modifier {
        self.handle().modifier()
    }

    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
        self.inner.borrow().resolved_modifiers
    }

    /// Returns a clone of the current layout state.
    pub fn layout_state(&self) -> LayoutState {
        self.layout_state.borrow().clone()
    }

    /// Updates the position of this node. Called during placement.
    pub fn set_position(&self, position: Point) {
        let mut state = self.layout_state.borrow_mut();
        state.position = position;
        state.is_placed = true;
    }

    /// Updates the measured size of this node. Called during measurement.
    pub fn set_measured_size(&self, size: Size) {
        let mut state = self.layout_state.borrow_mut();
        state.size = size;
    }

    /// Clears the is_placed flag. Called at the start of a layout pass.
    pub fn clear_placed(&self) {
        self.layout_state.borrow_mut().is_placed = false;
    }

    /// Returns the modifier slices snapshot for rendering.
    pub fn modifier_slices_snapshot(&self) -> Rc<ModifierNodeSlices> {
        if self.modifier_slices_dirty.get() {
            self.update_modifier_slices_cache();
        }
        self.modifier_slices_snapshot.borrow().clone()
    }

    pub fn state(&self) -> Ref<'_, SubcomposeState> {
        Ref::map(self.inner.borrow(), |inner| &inner.state)
    }

    pub fn state_mut(&self) -> RefMut<'_, SubcomposeState> {
        RefMut::map(self.inner.borrow_mut(), |inner| &mut inner.state)
    }

    pub fn invalidate_subcomposition(&self) {
        self.inner.borrow().state.invalidate_scopes();
        self.mark_needs_measure();
        if let Some(id) = self.id.get() {
            cranpose_core::bubble_measure_dirty_in_composer(id);
        }
    }

    pub fn request_measure_recompose(&self) {
        self.mark_needs_measure();
        if let Some(id) = self.id.get() {
            cranpose_core::bubble_measure_dirty_in_composer(id);
        }
    }

    pub fn active_children(&self) -> Vec<NodeId> {
        current_subcompose_children(&self.inner.borrow())
    }

    /// Mark this node as needing measure. Also marks it as needing layout.
    pub fn mark_needs_measure(&self) {
        self.needs_measure.set(true);
        self.needs_layout.set(true);
    }

    /// Mark this node as needing layout (but not necessarily measure).
    pub fn mark_needs_layout_flag(&self) {
        self.needs_layout.set(true);
    }

    /// Mark this node as needing redraw without forcing measure/layout.
    pub fn mark_needs_redraw(&self) {
        self.needs_redraw.set(true);
        if let Some(id) = self.id.get() {
            crate::schedule_draw_repass(id);
        }
        crate::request_render_invalidation();
    }

    /// Check if this node needs measure.
    pub fn needs_measure(&self) -> bool {
        self.needs_measure.get()
    }

    pub(crate) fn clear_needs_measure(&self) {
        self.needs_measure.set(false);
    }

    pub(crate) fn clear_needs_layout(&self) {
        self.needs_layout.set(false);
    }

    /// Mark this node as needing semantics recomputation.
    pub fn mark_needs_semantics(&self) {
        self.needs_semantics.set(true);
    }

    /// Returns true when semantics need to be recomputed.
    pub fn needs_semantics_flag(&self) -> bool {
        self.needs_semantics.get()
    }

    #[cfg(test)]
    pub(crate) fn clear_needs_semantics_for_tests(&self) {
        self.needs_semantics.set(false);
    }

    /// Returns true when this node requested a redraw since the last render pass.
    pub fn needs_redraw(&self) -> bool {
        self.needs_redraw.get()
    }

    pub fn clear_needs_redraw(&self) {
        self.needs_redraw.set(false);
    }

    /// Marks this node as needing a fresh pointer-input pass.
    pub fn mark_needs_pointer_pass(&self) {
        self.needs_pointer_pass.set(true);
    }

    /// Returns true when pointer-input state needs to be recomputed.
    pub fn needs_pointer_pass(&self) -> bool {
        self.needs_pointer_pass.get()
    }

    /// Clears the pointer-input dirty flag after hosts service it.
    pub fn clear_needs_pointer_pass(&self) {
        self.needs_pointer_pass.set(false);
    }

    /// Marks this node as needing a focus synchronization.
    pub fn mark_needs_focus_sync(&self) {
        self.needs_focus_sync.set(true);
    }

    /// Returns true when focus state needs to be synchronized.
    pub fn needs_focus_sync(&self) -> bool {
        self.needs_focus_sync.get()
    }

    /// Clears the focus dirty flag after the focus manager processes it.
    pub fn clear_needs_focus_sync(&self) {
        self.needs_focus_sync.set(false);
    }

    fn request_semantics_update(&self) {
        let already_dirty = self.needs_semantics.replace(true);
        if already_dirty {
            return;
        }

        if let Some(id) = self.id.get() {
            cranpose_core::queue_semantics_invalidation(id);
        }
    }

    /// Returns the modifier capabilities for this node.
    pub fn modifier_capabilities(&self) -> NodeCapabilities {
        self.inner.borrow().modifier_capabilities
    }

    pub fn has_layout_modifier_nodes(&self) -> bool {
        self.modifier_capabilities()
            .contains(NodeCapabilities::LAYOUT)
    }

    pub fn has_draw_modifier_nodes(&self) -> bool {
        self.modifier_capabilities()
            .contains(NodeCapabilities::DRAW)
    }

    pub fn has_pointer_input_modifier_nodes(&self) -> bool {
        self.modifier_capabilities()
            .contains(NodeCapabilities::POINTER_INPUT)
    }

    pub fn has_semantics_modifier_nodes(&self) -> bool {
        self.modifier_capabilities()
            .contains(NodeCapabilities::SEMANTICS)
    }

    pub fn has_focus_modifier_nodes(&self) -> bool {
        self.modifier_capabilities()
            .contains(NodeCapabilities::FOCUS)
    }

    /// Dispatches modifier invalidations to the appropriate subsystems.
    ///
    /// `prev_caps` contains the capabilities BEFORE the modifier update.
    /// Invalidations are dispatched if EITHER the previous OR current capabilities
    /// include the relevant type. This ensures that removing the last modifier
    /// of a type still triggers proper invalidation.
    fn dispatch_modifier_invalidations(
        &self,
        invalidations: &[ModifierInvalidation],
        prev_caps: NodeCapabilities,
    ) {
        let curr_caps = self.modifier_capabilities();
        for invalidation in invalidations {
            self.modifier_slices_dirty.set(true);
            match invalidation.kind() {
                InvalidationKind::Layout => {
                    if curr_caps.contains(NodeCapabilities::LAYOUT)
                        || prev_caps.contains(NodeCapabilities::LAYOUT)
                    {
                        self.mark_needs_measure();
                    }
                }
                InvalidationKind::Draw => {
                    if curr_caps.contains(NodeCapabilities::DRAW)
                        || prev_caps.contains(NodeCapabilities::DRAW)
                    {
                        self.mark_needs_redraw();
                    }
                }
                InvalidationKind::PointerInput => {
                    if curr_caps.contains(NodeCapabilities::POINTER_INPUT)
                        || prev_caps.contains(NodeCapabilities::POINTER_INPUT)
                    {
                        self.mark_needs_pointer_pass();
                        crate::request_pointer_invalidation();
                        // Schedule pointer repass for this node
                        if let Some(id) = self.id.get() {
                            crate::schedule_pointer_repass(id);
                        }
                    }
                }
                InvalidationKind::Semantics => {
                    self.request_semantics_update();
                }
                InvalidationKind::Focus => {
                    if curr_caps.contains(NodeCapabilities::FOCUS)
                        || prev_caps.contains(NodeCapabilities::FOCUS)
                    {
                        self.mark_needs_focus_sync();
                        crate::request_focus_invalidation();
                        // Schedule focus invalidation for this node
                        if let Some(id) = self.id.get() {
                            crate::schedule_focus_invalidation(id);
                        }
                    }
                }
            }
        }
    }
}

impl cranpose_core::Node for SubcomposeLayoutNode {
    fn mount(&mut self) {
        let mut inner = self.inner.borrow_mut();
        let (chain, mut context) = inner.modifier_chain.chain_and_context_mut();
        chain.repair_chain();
        chain.attach_nodes(&mut *context);
    }

    fn unmount(&mut self) {
        self.inner
            .borrow_mut()
            .modifier_chain
            .chain_mut()
            .detach_nodes();
    }

    fn insert_child(&mut self, child: NodeId) {
        let mut inner = self.inner.borrow_mut();
        if inner.children.contains(&child) {
            return;
        }
        if is_virtual_node(child) {
            let count = self.virtual_children_count.get();
            self.virtual_children_count.set(count + 1);
        }
        inner.children.push(child);
    }

    fn remove_child(&mut self, child: NodeId) {
        let mut inner = self.inner.borrow_mut();
        let before = inner.children.len();
        inner.children.retain(|&id| id != child);
        if inner.children.len() < before && is_virtual_node(child) {
            let count = self.virtual_children_count.get();
            if count > 0 {
                self.virtual_children_count.set(count - 1);
            }
        }
    }

    fn move_child(&mut self, from: usize, to: usize) {
        let mut inner = self.inner.borrow_mut();
        if from == to || from >= inner.children.len() {
            return;
        }
        let child = inner.children.remove(from);
        let target = to.min(inner.children.len());
        inner.children.insert(target, child);
    }

    fn update_children(&mut self, children: &[NodeId]) {
        let mut inner = self.inner.borrow_mut();
        inner.children.clear();
        inner.children.extend_from_slice(children);
    }

    fn children(&self) -> Vec<NodeId> {
        current_subcompose_children(&self.inner.borrow())
    }

    fn set_node_id(&mut self, id: NodeId) {
        self.id.set(Some(id));
        self.inner.borrow_mut().modifier_chain.set_node_id(Some(id));
    }

    fn on_attached_to_parent(&mut self, parent: NodeId) {
        self.parent.set(Some(parent));
    }

    fn on_removed_from_parent(&mut self) {
        self.parent.set(None);
    }

    fn parent(&self) -> Option<NodeId> {
        self.parent.get()
    }

    fn mark_needs_layout(&self) {
        self.needs_layout.set(true);
    }

    fn needs_layout(&self) -> bool {
        self.needs_layout.get()
    }

    fn mark_needs_measure(&self) {
        self.needs_measure.set(true);
        self.needs_layout.set(true); // Measure implies layout
    }

    fn needs_measure(&self) -> bool {
        self.needs_measure.get()
    }

    fn mark_needs_semantics(&self) {
        self.needs_semantics.set(true);
    }

    fn needs_semantics(&self) -> bool {
        self.needs_semantics.get()
    }

    /// Minimal parent setter for dirty flag bubbling.
    fn set_parent_for_bubbling(&mut self, parent: NodeId) {
        self.parent.set(Some(parent));
    }
}

#[derive(Clone)]
pub struct SubcomposeLayoutNodeHandle {
    inner: Rc<RefCell<SubcomposeLayoutNodeInner>>,
}

impl SubcomposeLayoutNodeHandle {
    pub fn modifier(&self) -> Modifier {
        self.inner.borrow().modifier.clone()
    }

    pub fn layout_properties(&self) -> crate::modifier::LayoutProperties {
        self.resolved_modifiers().layout_properties()
    }

    pub fn resolved_modifiers(&self) -> ResolvedModifiers {
        self.inner.borrow().resolved_modifiers
    }

    pub fn total_offset(&self) -> Point {
        self.resolved_modifiers().offset()
    }

    pub fn modifier_capabilities(&self) -> NodeCapabilities {
        self.inner.borrow().modifier_capabilities
    }

    pub fn has_layout_modifier_nodes(&self) -> bool {
        self.modifier_capabilities()
            .contains(NodeCapabilities::LAYOUT)
    }

    pub fn has_draw_modifier_nodes(&self) -> bool {
        self.modifier_capabilities()
            .contains(NodeCapabilities::DRAW)
    }

    pub fn has_pointer_input_modifier_nodes(&self) -> bool {
        self.modifier_capabilities()
            .contains(NodeCapabilities::POINTER_INPUT)
    }

    pub fn has_semantics_modifier_nodes(&self) -> bool {
        self.modifier_capabilities()
            .contains(NodeCapabilities::SEMANTICS)
    }

    pub fn has_focus_modifier_nodes(&self) -> bool {
        self.modifier_capabilities()
            .contains(NodeCapabilities::FOCUS)
    }

    pub fn set_debug_modifiers(&self, enabled: bool) {
        self.inner.borrow_mut().set_debug_modifiers(enabled);
    }

    pub fn measure<'a>(
        &self,
        composer: &Composer,
        node_id: NodeId,
        constraints: Constraints,
        measurer: Box<dyn FnMut(NodeId, Constraints) -> Size + 'a>,
        error: &'a RefCell<Option<NodeError>>,
    ) -> Result<MeasureResult, NodeError> {
        let (policy, mut state, slots_host) = {
            let mut inner = self.inner.borrow_mut();
            let policy = Rc::clone(&inner.measure_policy);
            let state = std::mem::take(&mut inner.state);
            let slots_host = Rc::clone(&inner.slots);
            (policy, state, slots_host)
        };
        state.begin_pass();

        let previous = composer.phase();
        if !matches!(previous, Phase::Measure | Phase::Layout) {
            composer.enter_phase(Phase::Measure);
        }

        let constraints_copy = constraints;
        // Architecture Note: Using subcompose_slot (not subcompose_in) to preserve the
        // SlotTable across measurement passes. This matches JC's SubcomposeLayout behavior
        // where `subcompose()` is called during measure and the slot table persists between
        // frames. Without this, lazy list item groups would be wiped and recreated on every
        // scroll frame, causing O(visible_items) recomposition overhead ("thrashing").
        //
        // Reference: LazyLayoutMeasureScope.subcompose() in JC reuses existing slots by key,
        // and SubcomposeLayoutState holds `slotIdToNode` map across measurements.
        let (result, _) =
            composer.subcompose_slot(&slots_host, Some(node_id), |inner_composer| {
                let mut scope = SubcomposeMeasureScopeImpl::new(
                    inner_composer.clone(),
                    &mut state,
                    constraints_copy,
                    measurer,
                    error,
                    self.clone(), // Pass handle
                    node_id,      // Pass root_id
                );
                (policy)(&mut scope, constraints_copy)
            })?;

        state.finish_pass();

        if previous != composer.phase() {
            composer.enter_phase(previous);
        }

        {
            let mut inner = self.inner.borrow_mut();
            inner.state = state;

            // Store placement children for children() traversal.
            // This avoids clearing/rebuilding the structural children set on every measure,
            // eliminating O(n) allocator churn. The structural children (virtual nodes) are
            // tracked via insert_child/remove_child, while last_placements tracks rendered nodes.
            inner.last_placements = result.placements.iter().map(|p| p.node_id).collect();
        }

        Ok(result)
    }

    pub fn set_active_children<I>(&self, children: I)
    where
        I: IntoIterator<Item = NodeId>,
    {
        let mut inner = self.inner.borrow_mut();
        inner.children.clear();
        inner.children.extend(children);
    }
}

fn current_subcompose_children(inner: &SubcomposeLayoutNodeInner) -> Vec<NodeId> {
    if !inner.last_placements.is_empty() {
        inner.last_placements.clone()
    } else {
        inner.children.clone()
    }
}

struct SubcomposeLayoutNodeInner {
    modifier: Modifier,
    modifier_chain: ModifierChainHandle,
    resolved_modifiers: ResolvedModifiers,
    modifier_capabilities: NodeCapabilities,
    state: SubcomposeState,
    measure_policy: Rc<MeasurePolicy>,
    children: Vec<NodeId>,
    slots: Rc<SlotsHost>,
    debug_modifiers: bool,
    // Owns virtual nodes created during subcomposition
    virtual_nodes: HashMap<NodeId, Rc<LayoutNode>>,
    // Cached placement children from the last measure pass.
    // Used by children() for semantic/render traversal without clearing structural children.
    last_placements: Vec<NodeId>,
}

impl SubcomposeLayoutNodeInner {
    fn new(measure_policy: Rc<MeasurePolicy>) -> Self {
        Self {
            modifier: Modifier::empty(),
            modifier_chain: ModifierChainHandle::new(),
            resolved_modifiers: ResolvedModifiers::default(),
            modifier_capabilities: NodeCapabilities::default(),
            state: SubcomposeState::default(),
            measure_policy,
            children: Vec::new(),
            slots: Rc::new(SlotsHost::new(SlotTable::default())),
            debug_modifiers: false,
            virtual_nodes: HashMap::new(),
            last_placements: Vec::new(),
        }
    }

    fn set_measure_policy(&mut self, policy: Rc<MeasurePolicy>) {
        self.measure_policy = policy;
        // The root measurement subcomposition caches its slot table separately
        // from per-item slot scopes. When a widget updates the data captured by
        // the measure lambda through shared cells, the next layout pass must not
        // reuse the previous root measure group wholesale.
        *self.slots.borrow_mut() = SlotTable::default();
    }

    /// Updates the modifier and collects invalidations without dispatching them.
    /// Returns the invalidations and whether the modifier changed.
    fn set_modifier_collect(&mut self, modifier: Modifier) -> (Vec<ModifierInvalidation>, bool) {
        let modifier_changed = !self.modifier.structural_eq(&modifier);
        self.modifier = modifier;
        self.modifier_chain.set_debug_logging(self.debug_modifiers);
        let modifier_local_invalidations = self.modifier_chain.update(&self.modifier);
        self.resolved_modifiers = self.modifier_chain.resolved_modifiers();
        self.modifier_capabilities = self.modifier_chain.capabilities();

        // Collect invalidations from modifier chain updates
        let mut invalidations = self.modifier_chain.take_invalidations();
        invalidations.extend(modifier_local_invalidations);

        (invalidations, modifier_changed)
    }

    fn set_debug_modifiers(&mut self, enabled: bool) {
        self.debug_modifiers = enabled;
        self.modifier_chain.set_debug_logging(enabled);
    }
}

#[cfg(test)]
#[path = "tests/subcompose_layout_tests.rs"]
mod tests;