cranpose-ui 0.0.59

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
//! LazyColumn and LazyRow widget implementations.
//!
//! Provides virtualized scrolling lists that only compose visible items,
//! matching Jetpack Compose's `LazyColumn` and `LazyRow` APIs.

#![allow(non_snake_case)]
#![allow(dead_code)] // Widget API is WIP

use std::cell::RefCell;
use std::rc::Rc;

use crate::composable;
use crate::modifier::Modifier;
use crate::subcompose_layout::{
    MeasurePolicy, Placement, SubcomposeLayoutNode, SubcomposeLayoutScope, SubcomposeMeasureScope,
    SubcomposeMeasureScopeImpl,
};
use cranpose_core::{NodeId, SlotId};
use cranpose_foundation::lazy::{
    measure_lazy_list, LazyListIntervalContent, LazyListMeasureConfig, LazyListMeasuredItem,
    LazyListState, SmallNodeVec, SmallOffsetVec, DEFAULT_ITEM_SIZE_ESTIMATE,
};
use cranpose_ui_layout::{Constraints, LinearArrangement, MeasureResult};
use smallvec::SmallVec;

// Re-export from foundation - single source of truth
pub use cranpose_foundation::lazy::{LazyListItemInfo, LazyListLayoutInfo};

/// Specification for LazyColumn layout behavior.
#[derive(Clone, Debug, PartialEq)]
pub struct LazyColumnSpec {
    /// Vertical arrangement for spacing between items.
    pub vertical_arrangement: LinearArrangement,
    /// Content padding before the first item.
    pub content_padding_top: f32,
    /// Content padding after the last item.
    pub content_padding_bottom: f32,
    /// Number of items to compose beyond the visible bounds.
    /// Higher values reduce jank during fast scrolling but use more memory.
    pub beyond_bounds_item_count: usize,
    /// Whether to reverse the layout direction (bottom-to-top).
    pub reverse_layout: bool,
}

impl Default for LazyColumnSpec {
    fn default() -> Self {
        Self {
            vertical_arrangement: LinearArrangement::Start,
            content_padding_top: 0.0,
            content_padding_bottom: 0.0,
            beyond_bounds_item_count: 2,
            reverse_layout: false,
        }
    }
}

impl LazyColumnSpec {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn vertical_arrangement(mut self, arrangement: LinearArrangement) -> Self {
        self.vertical_arrangement = arrangement;
        self
    }

    pub fn content_padding(mut self, top: f32, bottom: f32) -> Self {
        self.content_padding_top = top;
        self.content_padding_bottom = bottom;
        self
    }

    /// Sets uniform content padding for top and bottom.
    pub fn content_padding_all(mut self, padding: f32) -> Self {
        self.content_padding_top = padding;
        self.content_padding_bottom = padding;
        self
    }

    pub fn reverse_layout(mut self, reverse: bool) -> Self {
        self.reverse_layout = reverse;
        self
    }
}

/// Specification for LazyRow layout behavior.
#[derive(Clone, Debug, PartialEq)]
pub struct LazyRowSpec {
    /// Horizontal arrangement for spacing between items.
    pub horizontal_arrangement: LinearArrangement,
    /// Content padding before the first item.
    pub content_padding_start: f32,
    /// Content padding after the last item.
    pub content_padding_end: f32,
    /// Number of items to compose beyond the visible bounds.
    pub beyond_bounds_item_count: usize,
    /// Whether to reverse the layout direction (end-to-start).
    pub reverse_layout: bool,
}

impl Default for LazyRowSpec {
    fn default() -> Self {
        Self {
            horizontal_arrangement: LinearArrangement::Start,
            content_padding_start: 0.0,
            content_padding_end: 0.0,
            beyond_bounds_item_count: 2,
            reverse_layout: false,
        }
    }
}

impl LazyRowSpec {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn horizontal_arrangement(mut self, arrangement: LinearArrangement) -> Self {
        self.horizontal_arrangement = arrangement;
        self
    }

    pub fn content_padding(mut self, start: f32, end: f32) -> Self {
        self.content_padding_start = start;
        self.content_padding_end = end;
        self
    }

    /// Sets uniform content padding for start and end.
    pub fn content_padding_all(mut self, padding: f32) -> Self {
        self.content_padding_start = padding;
        self.content_padding_end = padding;
        self
    }

    pub fn reverse_layout(mut self, reverse: bool) -> Self {
        self.reverse_layout = reverse;
        self
    }
}

/// Internal helper to create a lazy list measure policy.
fn measure_lazy_list_internal(
    scope: &mut SubcomposeMeasureScopeImpl<'_>,
    constraints: Constraints,
    is_vertical: bool,
    content: &LazyListIntervalContent,
    state: &LazyListState,
    config: &LazyListMeasureConfig,
) -> MeasureResult {
    let raw_viewport_size = if is_vertical {
        constraints.max_height
    } else {
        constraints.max_width
    };
    let cross_axis_size = if is_vertical {
        constraints.max_width
    } else {
        constraints.max_height
    };

    let items_count = content.item_count();
    // Scroll position stability: if items were added/removed before the first visible,
    // find the item by key and adjust scroll position (JC's updateScrollPositionIfTheFirstItemWasMoved)
    if items_count > 0 {
        // Scroll position stability: try O(1) range search first, fall back to O(N) global search
        // This matches the performance-optimal pattern: most items are found within the range
        let range = state.nearest_range();
        state.update_scroll_position_if_item_moved(items_count, |slot_id| {
            content
                .get_index_by_slot_id_in_range(slot_id, range.clone())
                .or_else(|| content.get_index_by_slot_id(slot_id))
        });
        // Note: nearest range is automatically updated by scroll_position when index changes
    }

    // Measure function that subcomposes and measures each item
    let measure_item = |index: usize| -> LazyListMeasuredItem {
        let key = content.get_key(index);
        let key_slot_id = key.to_slot_id();
        let content_type = content.get_content_type(index);

        // Subcompose the item content with its own slot ID
        // The Composer handles node reuse internally via slot ID matching
        let slot_id = SlotId(key_slot_id);

        // Update content type for policy-based reuse matching
        // Uses update_content_type to handle both Some and None cases,
        // ensuring stale types don't drive incorrect reuse after transitions
        scope.update_content_type(slot_id, content_type);

        let item_content = content
            .with_interval(index, |local_index, interval| {
                let content = Rc::clone(&interval.content);
                move || (content)(local_index)
            })
            .expect("lazy list interval content must exist for measured item");
        let children = scope.subcompose(slot_id, item_content);

        // Record composition statistics for diagnostics
        let was_reused = scope.was_last_slot_reused().unwrap_or(false);
        state.record_composition(was_reused);

        // NOTE: Composer::subcompose_measurement now returns only root nodes directly,
        // so we no longer need the O(N) filter here.
        let root_children = children;

        // Measure the children using constraints
        // For LazyColumn (vertical): width is constrained (max = cross_axis_size), height is unbounded (INFINITY)
        // For LazyRow (horizontal): height is constrained, width is unbounded
        let child_constraints = if is_vertical {
            Constraints {
                min_width: 0.0,
                max_width: cross_axis_size,
                min_height: 0.0,
                max_height: f32::INFINITY,
            }
        } else {
            Constraints {
                min_width: 0.0,
                max_width: f32::INFINITY,
                min_height: 0.0,
                max_height: cross_axis_size,
            }
        };

        // Measure only ROOT nodes returned by subcompose.
        // Each root node handles its children's layout internally - we should NOT
        // iterate over all descendants or they'll be placed separately in the list.
        //
        // subcompose() returns only direct children (root nodes) of the slot composition.
        // If you compose `Row { Text(...); Text(...); }`, subcompose returns just [Row],
        // not [Row, Text, Text]. The Row measures its own children during its layout.
        let mut total_main_size: f32 = 0.0;
        let mut max_cross_size: f32 = 0.0;
        let mut node_ids: SmallNodeVec = SmallVec::new();
        let mut child_offsets: SmallOffsetVec = SmallVec::new();

        // Measure each ROOT node (typically just one per item)
        for child in root_children {
            let placeable = scope.measure(child, child_constraints);
            let (main, cross) = if is_vertical {
                (placeable.height(), placeable.width())
            } else {
                (placeable.width(), placeable.height())
            };

            // Track offset of this root node within the item
            child_offsets.push(total_main_size);
            node_ids.push(child.node_id() as u64);

            total_main_size += main;
            max_cross_size = max_cross_size.max(cross);
        }

        // Zero/near-zero measured items can cause extremely expensive measure loops
        // (thousands of items scanned to fill one viewport). Clamp to 1px minimum.
        let main_axis_size = total_main_size.max(1.0);
        let mut item = LazyListMeasuredItem::new(
            index,
            key_slot_id,
            content_type,
            main_axis_size,
            max_cross_size,
        );

        item.node_ids = node_ids;
        item.child_offsets = child_offsets;

        item
    };

    // Capture scroll delta for direction inference BEFORE measurement consumes it.
    // This is more accurate than comparing first visible index, especially for:
    // - Scrolling within the same item (partial scroll)
    // - Variable height items where scroll offset changes without index change
    let scroll_delta_for_direction = state.peek_scroll_delta();

    // Run the lazy list measurement algorithm
    let result = measure_lazy_list(
        items_count,
        state,
        raw_viewport_size,
        cross_axis_size,
        config,
        measure_item,
    );
    let effective_viewport_size = result.viewport_size;

    // Cache measured item sizes for better scroll estimation
    for item in &result.visible_items {
        state.cache_item_size(item.index, item.main_axis_size);
    }

    // Update stats: count only items WITHIN viewport, not beyond-bounds buffer
    let truly_visible_count = result
        .visible_items
        .iter()
        .filter(|item| {
            // Item is visible if any part of it is within viewport bounds
            let item_end = item.offset + item.main_axis_size;
            item.offset < effective_viewport_size && item_end > 0.0
        })
        .count();
    // Get reusable slot count from SubcomposeState (the single source of truth)
    let in_pool = scope.reusable_slots_count();
    state.update_stats(truly_visible_count, in_pool);

    // Prefetching: pre-compose items before they become visible
    // Direction is inferred from actual scroll delta (more accurate than index comparison)

    // Update prefetch queue based on visible items
    if !result.visible_items.is_empty() {
        let first_visible = result.visible_items.first().map(|i| i.index).unwrap_or(0);
        let last_visible = result.visible_items.last().map(|i| i.index).unwrap_or(0);

        // Use the raw Cranpose scroll delta for direction.
        // Negative delta = scrolling forward (content moves up/left),
        // positive delta = scrolling backward (content moves down/right).
        state.record_scroll_direction(scroll_delta_for_direction);

        state.update_prefetch_queue(first_visible, last_visible, items_count);

        // 3. Pre-compose prefetched items (compose but don't place)
        // Uses cached item sizes when available for better size estimation
        let prefetch_indices = state.take_prefetch_indices();
        let average_size = state.average_item_size();
        for idx in prefetch_indices {
            if idx < items_count {
                // Subcompose without placing - just to have it ready
                // SubcomposeState automatically tracks these as precomposed
                let key = content.get_key(idx);
                let key_slot_id = key.to_slot_id();
                let content_type_prefetch = content.get_content_type(idx);
                let slot_id = SlotId(key_slot_id);

                // Update content type for prefetched items too
                scope.update_content_type(slot_id, content_type_prefetch);

                // Use cached size if available, otherwise use average
                let estimated_size = state
                    .get_cached_size(idx)
                    .unwrap_or(average_size.max(DEFAULT_ITEM_SIZE_ESTIMATE));

                let prefetch_idx = idx;
                let is_vertical = config.is_vertical;
                let item_content = content
                    .with_interval(prefetch_idx, |local_index, interval| {
                        let content = Rc::clone(&interval.content);
                        move || (content)(local_index)
                    })
                    .expect("lazy list interval content must exist for prefetched item");
                let _ = scope.subcompose_with_size(slot_id, item_content, move |_| {
                    // Use correct axis based on orientation:
                    // Vertical list: width = cross_axis, height = main_axis (estimated)
                    // Horizontal list: width = main_axis (estimated), height = cross_axis
                    if is_vertical {
                        crate::modifier::Size {
                            width: cross_axis_size,
                            height: estimated_size + config.spacing,
                        }
                    } else {
                        crate::modifier::Size {
                            width: estimated_size + config.spacing,
                            height: cross_axis_size,
                        }
                    }
                });
            }
        }
    }

    // Create placements from measured items - place only ROOT nodes
    // JC Pattern (LazyListMeasure.kt:calculateItemsOffsets)
    let placements = create_lazy_list_placements(
        &result.visible_items,
        items_count,
        is_vertical,
        effective_viewport_size,
        config,
    );

    let resolve_main_axis = |content_size: f32, min: f32, max: f32| {
        if max.is_finite() {
            content_size.clamp(min, max)
        } else {
            content_size.min(effective_viewport_size).max(min)
        }
    };

    // Report size that respects BOTH min and max constraints.
    // - If content < min: expand to min (e.g., fillMaxSize)
    // - If content > max: clamp to max (enables scrolling)
    // - Otherwise: use content size (shrink-wrap)
    let width = if is_vertical {
        cross_axis_size
    } else {
        resolve_main_axis(
            result.total_content_size,
            constraints.min_width,
            constraints.max_width,
        )
    };
    let height = if is_vertical {
        resolve_main_axis(
            result.total_content_size,
            constraints.min_height,
            constraints.max_height,
        )
    } else {
        cross_axis_size
    };

    scope.layout(width, height, placements)
}

fn get_spacing(arrangement: LinearArrangement) -> f32 {
    match arrangement {
        LinearArrangement::SpacedBy(spacing) => spacing,
        _ => 0.0,
    }
}

fn bind_layout_invalidation_callback(state: LazyListState, list_state_id: usize, node_id: NodeId) {
    let callback_owner =
        cranpose_core::remember(|| Rc::new(RefCell::new(None::<u64>))).with(|cell| cell.clone());
    let callback_id = state.try_register_layout_callback(
        node_id,
        Rc::new(move || {
            crate::schedule_layout_repass(node_id);
        }),
    );

    if let Some(previous_id) = callback_owner.replace(callback_id) {
        if Some(previous_id) != callback_id {
            state.remove_invalidate_callback(previous_id);
        }
    }

    cranpose_core::DisposableEffect!((list_state_id, node_id, callback_id), move |scope| {
        scope.on_dispose(move || {
            if let Some(callback_id) = callback_id {
                state.remove_invalidate_callback(callback_id);
            }
        })
    });
}

#[derive(Clone)]
struct LazyListContentHandle(Rc<LazyListIntervalContent>);

impl LazyListContentHandle {
    fn new(content: LazyListIntervalContent) -> Self {
        Self(Rc::new(content))
    }

    fn empty() -> Self {
        Self::new(LazyListIntervalContent::new())
    }

    fn content(&self) -> &LazyListIntervalContent {
        self.0.as_ref()
    }
}

impl PartialEq for LazyListContentHandle {
    fn eq(&self, other: &Self) -> bool {
        Rc::ptr_eq(&self.0, &other.0)
    }
}

/// Creates placements for measured lazy list items.
///
/// This helper encapsulates the logic for:
/// - Applying arrangement when all items fit (hasSpareSpace in JC)
/// - Using sequential positioning during scrolling
fn create_lazy_list_placements(
    visible_items: &[LazyListMeasuredItem],
    items_count: usize,
    is_vertical: bool,
    viewport_size: f32,
    config: &LazyListMeasureConfig,
) -> Vec<Placement> {
    use cranpose_ui_layout::Arrangement;

    let arrangement = if is_vertical {
        config
            .vertical_arrangement
            .unwrap_or(LinearArrangement::Start)
    } else {
        config
            .horizontal_arrangement
            .unwrap_or(LinearArrangement::Start)
    };

    // Check if we should apply arrangement:
    // 1. All items are visible (visible_items.len() == total items)
    // 2. Content is smaller than viewport (hasSpareSpace)
    // 3. Arrangement is not sequential (Start or SpacedBy)
    let spacing = get_spacing(arrangement);
    let total_item_size: f32 = visible_items.iter().map(|i| i.main_axis_size).sum::<f32>()
        + (items_count.saturating_sub(1) as f32) * spacing;
    // Account for content padding when checking spare space (JC pattern)
    // Clamp to 0.0 to handle edge case where padding exceeds viewport
    let available_main_axis =
        (viewport_size - config.before_content_padding - config.after_content_padding).max(0.0);
    let has_spare_space =
        total_item_size < available_main_axis && visible_items.len() == items_count;
    let should_apply_arrangement = has_spare_space
        && !matches!(
            arrangement,
            LinearArrangement::Start | LinearArrangement::SpacedBy(_)
        );

    if should_apply_arrangement {
        // Apply arrangement to compute final positions
        // JC: density.arrange(mainAxisLayoutSize, sizes, offsets)
        let content_offset = config.before_content_padding;

        let sizes: Vec<f32> = visible_items.iter().map(|i| i.main_axis_size).collect();
        let mut positions = vec![0.0; sizes.len()];
        arrangement.arrange(available_main_axis, &sizes, &mut positions);

        visible_items
            .iter()
            .zip(positions.iter())
            .flat_map(|(item, &pos)| {
                item.node_ids.iter().zip(item.child_offsets.iter()).map(
                    move |(&nid, &child_offset)| {
                        let node_id: NodeId = nid as NodeId;
                        let item_size = item.main_axis_size;

                        if is_vertical {
                            let y = if config.reverse_layout {
                                viewport_size - (content_offset + pos) - item_size + child_offset
                            } else {
                                content_offset + pos + child_offset
                            };
                            Placement::new(node_id, 0.0, y, 0)
                        } else {
                            let x = if config.reverse_layout {
                                viewport_size - (content_offset + pos) - item_size + child_offset
                            } else {
                                content_offset + pos + child_offset
                            };
                            Placement::new(node_id, x, 0.0, 0)
                        }
                    },
                )
            })
            .collect()
    } else {
        // Use sequential offsets from measurement (scrolling case)
        visible_items
            .iter()
            .flat_map(|item| {
                item.node_ids.iter().zip(item.child_offsets.iter()).map(
                    move |(&nid, &child_offset)| {
                        let node_id: NodeId = nid as NodeId;
                        let item_size = item.main_axis_size;

                        if is_vertical {
                            let y = if config.reverse_layout {
                                viewport_size - item.offset - item_size + child_offset
                            } else {
                                item.offset + child_offset
                            };
                            Placement::new(node_id, 0.0, y, 0)
                        } else {
                            let x = if config.reverse_layout {
                                viewport_size - item.offset - item_size + child_offset
                            } else {
                                item.offset + child_offset
                            };
                            Placement::new(node_id, x, 0.0, 0)
                        }
                    },
                )
            })
            .collect()
    }
}

fn lazy_list_state_identity(state: &LazyListState) -> usize {
    // The remembered state stores its inner payload behind an `Rc`, so this allocation address
    // remains stable for the lifetime of the live state handle and is safe to use as a list key.
    let state_ptr = state.inner_ptr();
    debug_assert!(
        !state_ptr.is_null(),
        "lazy list identity requires a live LazyListState"
    );
    state_ptr as usize
}

/// Internal implementation for LazyColumn that takes pre-built content.
///
/// Users should prefer the DSL-based [`LazyColumn`] function instead.
fn LazyColumnImpl(
    modifier: Modifier,
    state: LazyListState,
    spec: LazyColumnSpec,
    content: LazyListContentHandle,
) -> NodeId {
    use std::cell::RefCell;

    // Use remember to keep a shared RefCell for content that persists across recompositions
    // This allows updating the content on each recomposition while reusing the same node/policy
    let content_cell =
        cranpose_core::remember(|| Rc::new(RefCell::new(LazyListContentHandle::empty())))
            .with(|cell| cell.clone());

    // Update the content on each recomposition
    *content_cell.borrow_mut() = content;

    // Configure measurement - wrapped in rememberUpdatedState for stable reference
    let config = LazyListMeasureConfig {
        is_vertical: true,
        reverse_layout: spec.reverse_layout,
        before_content_padding: spec.content_padding_top,
        after_content_padding: spec.content_padding_bottom,
        spacing: get_spacing(spec.vertical_arrangement),
        beyond_bounds_item_count: spec.beyond_bounds_item_count,
        vertical_arrangement: Some(spec.vertical_arrangement),
        horizontal_arrangement: None,
    };
    let config_cell =
        cranpose_core::remember(|| Rc::new(RefCell::new(config.clone()))).with(|cell| cell.clone());
    *config_cell.borrow_mut() = config;

    // Create measure policy with stable identity using remember.
    // The policy reads latest values via state references, so it can be memoized.
    let content_for_policy = content_cell.clone();
    let policy: Rc<MeasurePolicy> = cranpose_core::remember(move || {
        let config_ref = config_cell.clone();
        let content_ref = content_for_policy.clone();
        let policy: Rc<MeasurePolicy> = Rc::new(
            move |scope: &mut SubcomposeMeasureScopeImpl<'_>, constraints: Constraints| {
                let content = content_ref.borrow();
                let config = config_ref.borrow().clone();
                measure_lazy_list_internal(
                    scope,
                    constraints,
                    true,
                    content.content(),
                    &state,
                    &config,
                )
            },
        );
        policy
    })
    .with(|p| p.clone());
    let list_state_id = lazy_list_state_identity(&state);

    // Apply clipping and scroll gesture handling to modifier
    let scroll_modifier = modifier
        .clip_to_bounds()
        .lazy_vertical_scroll(state, spec.reverse_layout);

    // Create and register the subcompose layout node with the composer
    let node_id = cranpose_core::with_current_composer(|composer| {
        composer.with_key(&(list_state_id, "LazyColumnNode"), |composer| {
            composer.emit_node({
                let scroll_modifier = scroll_modifier.clone();
                let policy = Rc::clone(&policy);
                move || SubcomposeLayoutNode::with_content_type_policy(scroll_modifier, policy)
            })
        })
    });
    if let Err(err) = cranpose_core::with_node_mut(node_id, |node: &mut SubcomposeLayoutNode| {
        node.set_modifier(scroll_modifier.clone());
        node.set_measure_policy(Rc::clone(&policy));
        node.mark_needs_measure();
    }) {
        debug_assert!(false, "failed to update LazyColumn node: {err}");
    }
    cranpose_core::bubble_measure_dirty_in_composer(node_id);
    bind_layout_invalidation_callback(state, list_state_id, node_id);

    node_id
}

/// Internal implementation for LazyRow that takes pre-built content.
///
/// Users should prefer the DSL-based [`LazyRow`] function instead.
fn LazyRowImpl(
    modifier: Modifier,
    state: LazyListState,
    spec: LazyRowSpec,
    content: LazyListContentHandle,
) -> NodeId {
    use std::cell::RefCell;

    // Use remember to keep a shared RefCell for content that persists across recompositions
    let content_cell =
        cranpose_core::remember(|| Rc::new(RefCell::new(LazyListContentHandle::empty())))
            .with(|cell| cell.clone());

    // Update the content on each recomposition
    *content_cell.borrow_mut() = content;

    let config = LazyListMeasureConfig {
        is_vertical: false,
        reverse_layout: spec.reverse_layout,
        before_content_padding: spec.content_padding_start,
        after_content_padding: spec.content_padding_end,
        spacing: get_spacing(spec.horizontal_arrangement),
        beyond_bounds_item_count: spec.beyond_bounds_item_count,
        vertical_arrangement: None,
        horizontal_arrangement: Some(spec.horizontal_arrangement),
    };
    let config_cell =
        cranpose_core::remember(|| Rc::new(RefCell::new(config.clone()))).with(|cell| cell.clone());
    *config_cell.borrow_mut() = config;

    // Create measure policy with stable identity using remember.
    let content_for_policy = content_cell.clone();
    let policy: Rc<MeasurePolicy> = cranpose_core::remember(move || {
        let config_ref = config_cell.clone();
        let content_ref = content_for_policy.clone();
        let policy: Rc<MeasurePolicy> = Rc::new(
            move |scope: &mut SubcomposeMeasureScopeImpl<'_>, constraints: Constraints| {
                let content = content_ref.borrow();
                let config = config_ref.borrow().clone();
                measure_lazy_list_internal(
                    scope,
                    constraints,
                    false,
                    content.content(),
                    &state,
                    &config,
                )
            },
        );
        policy
    })
    .with(|p| p.clone());
    let list_state_id = lazy_list_state_identity(&state);

    // Apply clipping and scroll gesture handling to modifier
    let scroll_modifier = modifier
        .clip_to_bounds()
        .lazy_horizontal_scroll(state, spec.reverse_layout);

    // Create and register the subcompose layout node with the composer
    let node_id = cranpose_core::with_current_composer(|composer| {
        composer.with_key(&(list_state_id, "LazyRowNode"), |composer| {
            composer.emit_node({
                let scroll_modifier = scroll_modifier.clone();
                let policy = Rc::clone(&policy);
                move || SubcomposeLayoutNode::with_content_type_policy(scroll_modifier, policy)
            })
        })
    });
    if let Err(err) = cranpose_core::with_node_mut(node_id, |node: &mut SubcomposeLayoutNode| {
        node.set_modifier(scroll_modifier.clone());
        node.set_measure_policy(Rc::clone(&policy));
        node.mark_needs_measure();
    }) {
        debug_assert!(false, "failed to update LazyRow node: {err}");
    }
    cranpose_core::bubble_measure_dirty_in_composer(node_id);
    bind_layout_invalidation_callback(state, list_state_id, node_id);

    node_id
}

#[composable]
fn LazyColumnNode(
    modifier: Modifier,
    state: LazyListState,
    spec: LazyColumnSpec,
    content: LazyListContentHandle,
) -> NodeId {
    cranpose_core::debug_label_current_scope("LazyColumnNode");
    LazyColumnImpl(modifier, state, spec, content)
}

#[composable]
fn LazyRowNode(
    modifier: Modifier,
    state: LazyListState,
    spec: LazyRowSpec,
    content: LazyListContentHandle,
) -> NodeId {
    cranpose_core::debug_label_current_scope("LazyRowNode");
    LazyRowImpl(modifier, state, spec, content)
}

/// A vertically scrolling list that only composes visible items.
///
/// Matches Jetpack Compose's `LazyColumn` API. The closure receives
/// a [`LazyListIntervalContent`] which implements [`LazyListScope`] for defining items.
///
/// # Example
///
/// ```rust,ignore
/// let state = remember_lazy_list_state();
/// LazyColumn(Modifier::empty(), state, LazyColumnSpec::default(), |scope| {
///     // Single header item
///     scope.item(Some(0), None, || {
///         Text("Header", Modifier::empty());
///     });
///
///     // Multiple items from data
///     scope.items(data.len(), Some(|i| data[i].id), None, |i| {
///         Text(data[i].name.clone(), Modifier::empty());
///     });
/// });
/// ```
///
/// For convenience with slices, use the [`LazyListScopeExt`] extension methods:
///
/// ```rust,ignore
/// use cranpose_foundation::lazy::LazyListScopeExt;
///
/// LazyColumn(Modifier::empty(), state, LazyColumnSpec::default(), |scope| {
///     scope.items_slice(&my_data, |item| {
///         Text(item.name.clone(), Modifier::empty());
///     });
/// });
/// ```
/// A vertically scrolling list that only composes and lays out visible items.
///
/// # When to use
/// Use `LazyColumn` for lists with many items (100+) or unknown length.
/// It is much more efficient than using a `Column` with `vertical_scroll` modifier
/// because it recycles nodes and only keeps visible items in memory (virtualization).
///
/// # Arguments
///
/// * `modifier` - Modifiers to apply to the list container.
/// * `state` - The scroll state, used to control scroll position or observe changes.
/// * `spec` - Configuration for content padding, item spacing, and reverse layout.
/// * `content` - A closure that defines the list content using `LazyListScope`.
///
/// # Example
///
/// ```rust,ignore
/// let state = remember_lazy_list_state();
/// LazyColumn(
///     Modifier::fill_max_size(),
///     state,
///     LazyColumnSpec::default(),
///     |scope| {
///         scope.items(1000, None, None, |i| {
///             Text(format!("Item {}", i), Modifier::padding(16.0));
///         });
///     }
/// );
/// ```
pub fn LazyColumn<F>(
    modifier: Modifier,
    state: LazyListState,
    spec: LazyColumnSpec,
    content: F,
) -> NodeId
where
    F: FnOnce(&mut LazyListIntervalContent),
{
    let mut interval_content = LazyListIntervalContent::new();
    content(&mut interval_content);
    LazyColumnNode(
        modifier,
        state,
        spec,
        LazyListContentHandle::new(interval_content),
    )
}

/// A horizontally scrolling list that only composes visible items.
///
/// Matches Jetpack Compose's `LazyRow` API. The closure receives
/// a [`LazyListIntervalContent`] which implements [`LazyListScope`] for defining items.
///
/// # Example
///
/// ```rust,ignore
/// let state = remember_lazy_list_state();
/// LazyRow(Modifier::empty(), state, LazyRowSpec::default(), |scope| {
///     scope.items(10, None::<fn(usize)->u64>, None::<fn(usize)->u64>, |i| {
///         Text(format!("Item {}", i), Modifier::empty());
///     });
/// });
/// ```
pub fn LazyRow<F>(modifier: Modifier, state: LazyListState, spec: LazyRowSpec, content: F) -> NodeId
where
    F: FnOnce(&mut LazyListIntervalContent),
{
    let mut interval_content = LazyListIntervalContent::new();
    content(&mut interval_content);
    LazyRowNode(
        modifier,
        state,
        spec,
        LazyListContentHandle::new(interval_content),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use cranpose_core::{location_key, Composition, MemoryApplier};

    #[test]
    fn test_lazy_column_spec_default() {
        let spec = LazyColumnSpec::default();
        assert_eq!(spec.vertical_arrangement, LinearArrangement::Start);
        assert_eq!(spec.beyond_bounds_item_count, 2);
    }

    #[test]
    fn test_lazy_column_spec_builder() {
        let spec = LazyColumnSpec::new()
            .vertical_arrangement(LinearArrangement::SpacedBy(8.0))
            .content_padding(16.0, 16.0);

        assert_eq!(spec.vertical_arrangement, LinearArrangement::SpacedBy(8.0));
        assert_eq!(spec.content_padding_top, 16.0);
    }

    #[test]
    fn test_lazy_row_spec_default() {
        let spec = LazyRowSpec::default();
        assert_eq!(spec.horizontal_arrangement, LinearArrangement::Start);
        assert_eq!(spec.beyond_bounds_item_count, 2);
    }

    #[test]
    fn test_get_spacing() {
        assert_eq!(get_spacing(LinearArrangement::Start), 0.0);
        assert_eq!(get_spacing(LinearArrangement::SpacedBy(12.0)), 12.0);
    }

    #[test]
    fn test_content_padding_all() {
        let spec = LazyColumnSpec::new().content_padding_all(24.0);
        assert_eq!(spec.content_padding_top, 24.0);
        assert_eq!(spec.content_padding_bottom, 24.0);
    }

    #[test]
    fn lazy_list_state_identity_is_stable_for_copied_state() {
        let mut composition = Composition::new(MemoryApplier::new());
        let key = location_key(file!(), line!(), column!());
        let mut state = None;
        composition
            .render(key, || {
                state = Some(cranpose_foundation::lazy::remember_lazy_list_state());
            })
            .expect("lazy list state render should succeed");
        let state = state.expect("lazy list state should be captured");
        let copied_state = state;

        assert_ne!(state.inner_ptr(), std::ptr::null());
        assert_eq!(
            lazy_list_state_identity(&state),
            lazy_list_state_identity(&copied_state)
        );
    }
}