Skip to main content

cranpose_foundation/lazy/
lazy_list_state.rs

1//! Lazy list state management.
2//!
3//! Provides [`LazyListState`] for controlling and observing lazy list scroll position.
4//!
5//! Design follows Jetpack Compose's LazyListState/LazyListScrollPosition pattern:
6//! - Reactive properties are backed by `MutableState<T>`:
7//!   - `first_visible_item_index`, `first_visible_item_scroll_offset`
8//!   - `can_scroll_forward`, `can_scroll_backward`
9//!   - `stats` (items_in_use, items_in_pool)
10//! - Non-reactive internals (caches, callbacks, scroll window, diagnostic counters) are in inner state
11
12use std::{cell::RefCell, rc::Rc};
13
14use cranpose_core::{MutableState, NodeId, RuntimeCell, StateId, collections::map::HashMap};
15use cranpose_macros::composable;
16
17use super::diagnostics;
18use crate::{RunningScroll, ScrollId, ScrollStop};
19
20mod scroll_position;
21
22pub use scroll_position::LazyListScrollPosition;
23
24const MAX_PENDING_SCROLL_DELTA: f32 = 2000.0;
25const ITEM_SIZE_CACHE_CAPACITY: usize = 8192;
26
27#[derive(Clone, Copy, Debug, PartialEq)]
28pub(crate) struct LazyListMeasureStateSnapshot {
29    pub(crate) first_visible_item_index: usize,
30    pub(crate) first_visible_item_scroll_offset: f32,
31    pub(crate) pending_scroll_delta: f32,
32    pub(crate) window_scroll_delta: f32,
33    pub(crate) pending_scroll_to: Option<(usize, f32)>,
34    pub(crate) average_item_size: f32,
35}
36
37/// Statistics about lazy layout item lifecycle.
38///
39/// Used for testing and debugging virtualization behavior.
40#[derive(Clone, Debug, Default, PartialEq)]
41pub struct LazyLayoutStats {
42    /// Number of items currently composed and visible.
43    pub items_in_use: usize,
44
45    /// Number of items in the recycle pool (available for reuse).
46    pub items_in_pool: usize,
47
48    /// Total number of items that have been composed.
49    pub total_composed: usize,
50
51    /// Number of items that were reused instead of newly composed.
52    pub reuse_count: usize,
53}
54
55/// State object for lazy list scroll position tracking.
56///
57/// Holds the current scroll position and provides methods to programmatically
58/// control scrolling. Create with [`rememberLazyListState()`] in composition.
59///
60/// This type is `Copy`, so it can be passed to multiple closures without explicit `.clone()` calls.
61///
62/// # Reactive Properties (read during composition triggers recomposition)
63/// - `first_visible_item_index()` - index of first visible item
64/// - `first_visible_item_scroll_offset()` - scroll offset within first item
65/// - `can_scroll_forward()` - whether more items exist below/right
66/// - `can_scroll_backward()` - whether more items exist above/left
67/// - `stats()` - lifecycle statistics (`items_in_use`, `items_in_pool`)
68///
69/// # Non-Reactive Properties
70/// - `stats().total_composed` - total items composed (diagnostic)
71/// - `stats().reuse_count` - items reused from pool (diagnostic)
72/// - `layout_info()` - detailed layout information
73///
74/// # Example
75///
76/// ```rust,ignore
77/// let state = rememberLazyListState();
78///
79/// // Scroll to item 50
80/// state.scroll_to_item(50, 0.0);
81///
82/// // Get current visible item (reactive read)
83/// println!("First visible: {}", state.first_visible_item_index());
84/// ```
85#[derive(Clone, Copy)]
86pub struct LazyListState {
87    scroll_position: LazyListScrollPosition,
88    can_scroll_forward_state: MutableState<bool>,
89    can_scroll_backward_state: MutableState<bool>,
90    stats_state: MutableState<LazyLayoutStats>,
91    scroll_in_progress_state: MutableState<bool>,
92    dragged_state: MutableState<bool>,
93    inner: RuntimeCell<RefCell<LazyListStateInner>>,
94}
95
96impl PartialEq for LazyListState {
97    fn eq(&self, other: &Self) -> bool {
98        self.inner == other.inner
99    }
100}
101
102#[derive(Clone, Copy)]
103struct CachedItemSize {
104    key: u64,
105    size: f32,
106    last_used: u64,
107}
108
109/// Non-reactive internal state for LazyListState.
110/// Where a scroll that the user let go of comes to rest: given the rest
111/// offset the release would reach, within the first visible item, and the
112/// release velocity, the offset to settle at instead.
113pub type LazySettlePolicy = Rc<dyn Fn(f32, f32) -> f32>;
114
115struct LazyListStateInner {
116    scroll_to_be_consumed: f32,
117    settle_policy: Option<LazySettlePolicy>,
118    /// The scroll that moves the list now and how to stop it.
119    running_scroll: RunningScroll,
120    /// Whether the scroll modifier's drag, fling or settle moves the list.
121    gesture_scrolling: bool,
122    /// The first visible item and its offset where the scroll in progress
123    /// began.
124    scroll_start: Option<(usize, f32)>,
125
126    pending_scroll_to_index: Option<(usize, f32)>,
127
128    layout_info: LazyListLayoutInfo,
129    /// The visible items of the layout info before the last, cleared, which
130    /// the next measure pass fills.
131    spare_items_info: Vec<LazyListItemInfo>,
132    current_can_scroll_forward: bool,
133    current_can_scroll_backward: bool,
134
135    invalidate_callbacks: Vec<(u64, Rc<dyn Fn()>)>,
136    next_callback_id: u64,
137
138    layout_invalidation_callback_id: Option<u64>,
139    layout_invalidation_node_id: Option<NodeId>,
140
141    total_composed: usize,
142    reuse_count: usize,
143
144    item_size_cache: HashMap<usize, CachedItemSize>,
145    item_size_clock: u64,
146
147    average_item_size: f32,
148    total_measured_items: usize,
149    next_measure_cycle_id: u64,
150    next_item_measure_pass_id: u64,
151
152    last_scroll_delta: f32,
153
154    hold_scroll_window: bool,
155}
156
157/// Creates a remembered [`LazyListState`] with default initial position.
158///
159/// This is the recommended way to create a `LazyListState` in composition.
160/// The returned state is `Copy` and can be passed to multiple closures without `.clone()`.
161///
162/// # Example
163///
164/// ```rust,ignore
165/// let list_state = rememberLazyListState();
166///
167/// // Pass to multiple closures - no .clone() needed!
168/// LazyColumn(modifier, list_state, spec, content);
169/// Button(move || list_state.scroll_to_item(0, 0.0));
170/// ```
171#[composable]
172#[track_caller]
173pub fn rememberLazyListState() -> LazyListState {
174    rememberLazyListStateWithPosition(0, 0.0)
175}
176
177/// Creates a remembered [`LazyListState`] with the specified initial position.
178///
179/// The returned state is `Copy` and can be passed to multiple closures without `.clone()`.
180#[composable]
181pub fn rememberLazyListStateWithPosition(
182    initial_first_visible_item_index: usize,
183    initial_first_visible_item_scroll_offset: f32,
184) -> LazyListState {
185    cranpose_core::remember(move || {
186        LazyListState::new(
187            initial_first_visible_item_index,
188            initial_first_visible_item_scroll_offset,
189        )
190    })
191    .with(|state| *state)
192}
193
194impl LazyListState {
195    /// A list's scroll states, for code that remembers the list state itself.
196    ///
197    /// Call it inside a `remember` -- [`rememberLazyListState`] is this plus
198    /// the slot -- so that the states belong to that slot and are released
199    /// with it.
200    pub fn new(
201        initial_first_visible_item_index: usize,
202        initial_first_visible_item_scroll_offset: f32,
203    ) -> Self {
204        Self {
205            scroll_position: LazyListScrollPosition::new(
206                initial_first_visible_item_index,
207                initial_first_visible_item_scroll_offset,
208            ),
209            can_scroll_forward_state: cranpose_core::mutableStateOf(false),
210            can_scroll_backward_state: cranpose_core::mutableStateOf(false),
211            stats_state: cranpose_core::mutableStateOf(LazyLayoutStats::default()),
212            scroll_in_progress_state: cranpose_core::mutableStateOf(false),
213            dragged_state: cranpose_core::mutableStateOf(false),
214            inner: RuntimeCell::new(RefCell::new(LazyListStateInner {
215                scroll_to_be_consumed: 0.0,
216                settle_policy: None,
217                running_scroll: RunningScroll::default(),
218                gesture_scrolling: false,
219                scroll_start: None,
220                pending_scroll_to_index: None,
221                layout_info: LazyListLayoutInfo::default(),
222                spare_items_info: Vec::new(),
223                current_can_scroll_forward: false,
224                current_can_scroll_backward: false,
225                invalidate_callbacks: Vec::new(),
226                next_callback_id: 1,
227                layout_invalidation_callback_id: None,
228                layout_invalidation_node_id: None,
229                total_composed: 0,
230                reuse_count: 0,
231                item_size_cache: HashMap::default(),
232                item_size_clock: 0,
233                average_item_size: super::DEFAULT_ITEM_SIZE_ESTIMATE,
234                total_measured_items: 0,
235                next_measure_cycle_id: 1,
236                next_item_measure_pass_id: 1,
237                last_scroll_delta: 0.0,
238                hold_scroll_window: false,
239            })),
240        }
241    }
242
243    /// The first visible item and how far it is scrolled, or `None` once the
244    /// slot that held this state was released. A saver reads it when the
245    /// list leaves the composition.
246    pub fn try_position(&self) -> Option<(usize, f32)> {
247        self.scroll_position.current()
248    }
249
250    /// Returns a stable identity pointer for the live inner state allocation.
251    ///
252    /// The pointer is the address of the value `inner` keeps in the runtime, so it remains
253    /// stable for the lifetime of a live `LazyListState` and can be used as a composition
254    /// identity key.
255    pub fn inner_ptr(&self) -> *const () {
256        self.inner
257            .try_with(|inner| std::ptr::from_ref(inner).cast::<()>())
258            .unwrap_or(std::ptr::null())
259    }
260
261    /// The index of the first visible item: the first to end past the edge
262    /// of the start content padding, as in Compose.
263    /// When called during composition, this creates a reactive subscription
264    /// so that changes to the index will trigger recomposition.
265    pub fn first_visible_item_index(&self) -> usize {
266        self.scroll_position.index()
267    }
268
269    /// How many items the list holds, as of its last measure.
270    pub fn total_items_count(&self) -> usize {
271        self.inner
272            .with(|cell| cell.borrow().layout_info.total_items_count)
273    }
274
275    /// Returns the first visible item index without subscribing the current composition scope.
276    ///
277    /// Use this from draw/input/diagnostic code that needs the latest position but must not
278    /// recompose when the scroll position changes.
279    pub fn first_visible_item_index_non_reactive(&self) -> usize {
280        self.scroll_position.current_index()
281    }
282
283    /// Returns the scroll offset of the first visible item.
284    ///
285    /// This is how far the first item is scrolled past the start padding's edge (positive = up/left).
286    /// When called during composition, this creates a reactive subscription
287    /// so that changes to the offset will trigger recomposition.
288    pub fn first_visible_item_scroll_offset(&self) -> f32 {
289        self.scroll_position.scroll_offset()
290    }
291
292    /// Returns the first visible item scroll offset without subscribing the current composition scope.
293    ///
294    /// Use this from draw/input/diagnostic code that needs the latest position but must not
295    /// recompose when the scroll position changes.
296    pub fn first_visible_item_scroll_offset_non_reactive(&self) -> f32 {
297        self.scroll_position.current_scroll_offset()
298    }
299
300    #[doc(hidden)]
301    pub fn reactive_state_ids(&self) -> [StateId; 5] {
302        [
303            self.scroll_position.index.runtime_state_id(),
304            self.scroll_position.scroll_offset.runtime_state_id(),
305            self.can_scroll_forward_state.runtime_state_id(),
306            self.can_scroll_backward_state.runtime_state_id(),
307            self.stats_state.runtime_state_id(),
308        ]
309    }
310
311    /// Returns the layout info from the last measure pass.
312    pub fn layout_info(&self) -> LazyListLayoutInfo {
313        self.with_layout_info(LazyListLayoutInfo::clone)
314            .unwrap_or_default()
315    }
316
317    /// Reads the layout info from the last measure pass in place, without
318    /// the copy of the visible items that [`Self::layout_info`] makes.
319    /// `None` once the state is gone.
320    pub fn with_layout_info<R>(&self, read: impl FnOnce(&LazyListLayoutInfo) -> R) -> Option<R> {
321        self.inner.try_with(|cell| read(&cell.borrow().layout_info))
322    }
323
324    /// Returns the current item lifecycle statistics.
325    ///
326    /// When called during composition, this creates a reactive subscription
327    /// so that changes to `items_in_use` or `items_in_pool` will trigger recomposition.
328    /// The `total_composed` and `reuse_count` fields are diagnostic and non-reactive.
329    pub fn stats(&self) -> LazyLayoutStats {
330        if !self.stats_state.is_alive() || !self.inner.is_alive() {
331            return LazyLayoutStats::default();
332        }
333        let reactive = self.stats_state.get();
334        let (total_composed, reuse_count) = self.inner.with(|cell| {
335            let inner = cell.borrow();
336            (inner.total_composed, inner.reuse_count)
337        });
338        LazyLayoutStats {
339            items_in_use: reactive.items_in_use,
340            items_in_pool: reactive.items_in_pool,
341            total_composed,
342            reuse_count,
343        }
344    }
345
346    /// Updates the item lifecycle statistics.
347    ///
348    /// Called by the layout measurement after updating slot pools.
349    /// Triggers recomposition if `items_in_use` or `items_in_pool` changed.
350    pub fn update_stats(&self, items_in_use: usize, items_in_pool: usize) {
351        if !self.stats_state.is_alive() || !self.inner.is_alive() {
352            return;
353        }
354
355        let current = self.stats_state.get_non_reactive();
356
357        let should_update_reactive = if items_in_use > current.items_in_use {
358            true
359        } else if items_in_use < current.items_in_use {
360            current.items_in_use - items_in_use > 1
361        } else {
362            false
363        };
364
365        if should_update_reactive {
366            self.stats_state.set(LazyLayoutStats {
367                items_in_use,
368                items_in_pool,
369                ..current
370            });
371        }
372    }
373
374    /// Records that an item was composed (either new or reused).
375    ///
376    /// This updates diagnostic counters in non-reactive state.
377    /// Does NOT trigger recomposition.
378    pub fn record_composition(&self, was_reused: bool) {
379        self.inner.try_with(|cell| {
380            let mut inner = cell.borrow_mut();
381            inner.total_composed += 1;
382            if was_reused {
383                inner.reuse_count += 1;
384            }
385        });
386    }
387
388    /// Makes the next measure pass size its beyond-bounds window by the last
389    /// scroll delta a pass consumed when it has none of its own, so a pass
390    /// between frames keeps the window the scroll gave the frame before it.
391    pub fn hold_scroll_window(&self) {
392        self.inner
393            .try_with(|cell| cell.borrow_mut().hold_scroll_window = true);
394    }
395
396    /// Installs, or clears, where a drag or a fling the user let go of comes
397    /// to rest: a pager settles on its pages.
398    pub fn set_settle_policy(&self, policy: Option<LazySettlePolicy>) {
399        self.inner
400            .try_with(|cell| cell.borrow_mut().settle_policy = policy);
401    }
402
403    /// The installed settle policy, if any.
404    pub fn settle_policy(&self) -> Option<LazySettlePolicy> {
405        self.inner
406            .try_with(|cell| cell.borrow().settle_policy.clone())
407            .flatten()
408    }
409
410    /// Makes the scroll that `stop` stops the running scroll of the list.
411    /// The scroll that ran before stops. The running scroll is an animation
412    /// that the app starts or a motion after a drag. A press on the list
413    /// stops it. [`Self::scroll_to_item`] and [`Self::stop_scroll_animation`]
414    /// stop it too. Returns its id, or `None` once the slot that held this
415    /// state was released.
416    pub fn start_scroll_animation(&self, stop: impl FnOnce() + 'static) -> Option<ScrollId> {
417        let (id, previous) = self
418            .inner
419            .try_with(|cell| cell.borrow_mut().running_scroll.start(stop))?;
420        if let Some(previous) = previous {
421            previous.run();
422        }
423        self.refresh_scroll_in_progress();
424        Some(id)
425    }
426
427    /// Forgets the scroll `id` once it ended on its own.
428    pub fn end_scroll_animation(&self, id: ScrollId) {
429        let _ = self
430            .inner
431            .try_with(|cell| cell.borrow_mut().running_scroll.end(id));
432        self.refresh_scroll_in_progress();
433    }
434
435    /// Stops the running scroll and returns whether one ran. The running
436    /// scroll is an animation or a motion after a drag.
437    pub fn stop_scroll_animation(&self) -> bool {
438        let running = self
439            .inner
440            .try_with(|cell| cell.borrow_mut().running_scroll.take())
441            .flatten();
442        let stopped = running.map(ScrollStop::run).is_some();
443        self.refresh_scroll_in_progress();
444        stopped
445    }
446
447    /// Whether a drag, a fling, a settle or a scroll animation moves the list
448    /// now: Compose's `isScrollInProgress`. A composable that reads it
449    /// recomposes when a scroll starts and when it ends.
450    pub fn is_scroll_in_progress(&self) -> bool {
451        self.scroll_in_progress_state.is_alive() && self.scroll_in_progress_state.get()
452    }
453
454    /// Whether a finger or a pointer drags the list now: Compose's
455    /// `interactionSource.collectIsDraggedAsState()`. A composable that reads
456    /// it recomposes when a drag starts and when it ends.
457    pub fn is_dragged(&self) -> bool {
458        self.dragged_state.is_alive() && self.dragged_state.get()
459    }
460
461    /// Marks whether the scroll modifier's drag moves the list, for
462    /// [`Self::is_dragged`]. The scroll modifier calls it.
463    pub fn set_dragged(&self, dragged: bool) {
464        if self.dragged_state.is_alive() && self.dragged_state.get_non_reactive() != dragged {
465            self.dragged_state.set(dragged);
466        }
467    }
468
469    /// Marks whether a drag, a fling or a settle of the scroll modifier moves
470    /// the list, for [`Self::is_scroll_in_progress`]. The scroll modifier
471    /// calls it; scroll animations mark themselves.
472    pub fn set_gesture_scroll_active(&self, active: bool) {
473        let changed = self.inner.try_with(|cell| {
474            std::mem::replace(&mut cell.borrow_mut().gesture_scrolling, active) != active
475        });
476        if changed == Some(true) {
477            self.refresh_scroll_in_progress();
478        }
479    }
480
481    /// The first visible item and its offset where the scroll in progress
482    /// began, or `None` while no scroll is in progress. A pager keeps its
483    /// settled page from it.
484    pub fn position_before_scroll(&self) -> Option<(usize, f32)> {
485        self.inner
486            .try_with(|cell| cell.borrow().scroll_start)
487            .flatten()
488    }
489
490    fn refresh_scroll_in_progress(&self) {
491        if !self.scroll_in_progress_state.is_alive() {
492            return;
493        }
494        let Some(moving) = self.inner.try_with(|cell| {
495            let inner = cell.borrow();
496            inner.gesture_scrolling || inner.running_scroll.is_running()
497        }) else {
498            return;
499        };
500        if self.scroll_in_progress_state.get_non_reactive() == moving {
501            return;
502        }
503        let start = if moving { self.try_position() } else { None };
504        let _ = self
505            .inner
506            .try_with(|cell| cell.borrow_mut().scroll_start = start);
507        self.scroll_in_progress_state.set(moving);
508    }
509
510    /// Puts the item at `index` at the edge of the start content padding.
511    /// It stops the running scroll first, as Compose's `scrollToItem` does.
512    ///
513    /// # Arguments
514    /// * `index` - The index of the item to scroll to
515    /// * `scroll_offset` - How far past that edge the item is scrolled (default 0)
516    pub fn scroll_to_item(&self, index: usize, scroll_offset: f32) {
517        if !self.inner.is_alive() {
518            return;
519        }
520        self.stop_scroll_animation();
521        if diagnostics::telemetry_enabled() {
522            log::warn!(
523                "[lazy-measure-telemetry] scroll_to_item request index={index} offset={scroll_offset:.2}"
524            );
525        }
526        self.inner.with(|cell| {
527            let mut inner = cell.borrow_mut();
528            inner.pending_scroll_to_index = Some((index, scroll_offset));
529            // The jump replaces the scroll deltas that have not been applied.
530            inner.scroll_to_be_consumed = 0.0;
531        });
532
533        self.scroll_position
534            .request_position_and_forget_last_known_key(index, scroll_offset);
535
536        self.invalidate();
537    }
538
539    /// Dispatches a raw scroll delta.
540    ///
541    /// Returns the amount of scroll actually consumed.
542    ///
543    /// This triggers layout invalidation via registered callbacks. The callbacks
544    /// are registered by LazyColumnImpl/LazyRowImpl with
545    /// `schedule_measure_repass(node_id)` — the list's own item sizes are what
546    /// changes, so the repass has to bubble measure dirtiness, not just
547    /// placement. The node id carries through to the scene phase, which scopes
548    /// its graph update to that subtree: O(subtree) instead of O(entire app).
549    pub fn dispatch_scroll_delta(&self, delta: f32) -> f32 {
550        let Some(cell) = self.inner.try_get() else {
551            return 0.0;
552        };
553        let has_scroll_bounds = cell.borrow().layout_info.total_items_count > 0;
554        let pushing_forward = delta < -0.001;
555        let pushing_backward = delta > 0.001;
556        let can_scroll_forward =
557            self.can_scroll_forward_state.is_alive() && self.can_scroll_forward_non_reactive();
558        let can_scroll_backward =
559            self.can_scroll_backward_state.is_alive() && self.can_scroll_backward_non_reactive();
560        let blocked_by_bounds = has_scroll_bounds
561            && ((pushing_forward && !can_scroll_forward)
562                || (pushing_backward && !can_scroll_backward));
563
564        if blocked_by_bounds {
565            let should_invalidate = {
566                let mut inner = cell.borrow_mut();
567                let pending_before = inner.scroll_to_be_consumed;
568                if pending_before.abs() > 0.001 && pending_before.signum() == delta.signum() {
569                    inner.scroll_to_be_consumed = 0.0;
570                }
571                if diagnostics::telemetry_enabled() {
572                    log::warn!(
573                        "[lazy-measure-telemetry] dispatch_scroll_delta blocked_by_bounds delta={:.2} pending_before={:.2} pending_after={:.2}",
574                        delta,
575                        pending_before,
576                        inner.scroll_to_be_consumed
577                    );
578                }
579                (inner.scroll_to_be_consumed - pending_before).abs() > 0.001
580            };
581            if should_invalidate {
582                Self::run_invalidate_callbacks(&cell);
583            }
584            return 0.0;
585        }
586
587        let should_invalidate = {
588            let mut inner = cell.borrow_mut();
589            let pending_before = inner.scroll_to_be_consumed;
590            let pending = inner.scroll_to_be_consumed;
591            let reverse_input =
592                pending.abs() > 0.001 && delta.abs() > 0.001 && pending.signum() != delta.signum();
593            if reverse_input {
594                if diagnostics::telemetry_enabled() {
595                    log::warn!(
596                        "[lazy-measure-telemetry] dispatch_scroll_delta direction_change pending={pending:.2} new_delta={delta:.2}"
597                    );
598                }
599                inner.scroll_to_be_consumed = delta;
600            } else {
601                inner.scroll_to_be_consumed += delta;
602            }
603            inner.scroll_to_be_consumed = inner
604                .scroll_to_be_consumed
605                .clamp(-MAX_PENDING_SCROLL_DELTA, MAX_PENDING_SCROLL_DELTA);
606            if diagnostics::telemetry_enabled() {
607                log::warn!(
608                    "[lazy-measure-telemetry] dispatch_scroll_delta delta={:.2} pending={:.2}",
609                    delta,
610                    inner.scroll_to_be_consumed
611                );
612            }
613            (inner.scroll_to_be_consumed - pending_before).abs() > 0.001
614        };
615        if should_invalidate {
616            Self::run_invalidate_callbacks(&cell);
617        }
618        delta
619    }
620
621    /// Peeks at the pending scroll delta without consuming it.
622    ///
623    /// Used for direction inference before measurement consumes the delta.
624    /// This is more accurate than comparing first visible index, especially for:
625    /// - Scrolling within the same item (partial scroll)
626    /// - Variable height items where scroll offset changes without index change
627    pub fn peek_scroll_delta(&self) -> f32 {
628        self.inner
629            .try_with(|cell| cell.borrow().scroll_to_be_consumed)
630            .unwrap_or(0.0)
631    }
632
633    pub(crate) fn begin_measure_pass(&self) -> LazyListMeasureStateSnapshot {
634        let snapshot = self.measure_pass_snapshot();
635        self.consume_measure_pass();
636        snapshot
637    }
638
639    // What a measure pass starts from. The state keeps the scroll it holds
640    // until `consume_measure_pass`, for a pass that may give up.
641    pub(crate) fn measure_pass_snapshot(&self) -> LazyListMeasureStateSnapshot {
642        let (pending_scroll_delta, window_scroll_delta, pending_scroll_to, average_item_size) =
643            self.inner
644                .try_with(|cell| {
645                    let inner = cell.borrow();
646                    let pending_scroll_delta = inner.scroll_to_be_consumed;
647                    let window_scroll_delta = if pending_scroll_delta.abs() > 0.001 {
648                        pending_scroll_delta
649                    } else if inner.hold_scroll_window {
650                        inner.last_scroll_delta
651                    } else {
652                        0.0
653                    };
654                    (
655                        pending_scroll_delta,
656                        window_scroll_delta,
657                        inner.pending_scroll_to_index,
658                        inner.average_item_size,
659                    )
660                })
661                .unwrap_or((0.0, 0.0, None, super::DEFAULT_ITEM_SIZE_ESTIMATE));
662
663        let (first_visible_item_index, first_visible_item_scroll_offset) =
664            self.try_position().unwrap_or((0, 0.0));
665        LazyListMeasureStateSnapshot {
666            first_visible_item_index,
667            first_visible_item_scroll_offset,
668            pending_scroll_delta,
669            window_scroll_delta,
670            pending_scroll_to,
671            average_item_size,
672        }
673    }
674
675    // Takes the scroll a measure pass applied: the pending delta, the item
676    // asked for and the held scroll window.
677    pub(crate) fn consume_measure_pass(&self) {
678        self.inner.try_with(|cell| {
679            let mut inner = cell.borrow_mut();
680            inner.pending_scroll_to_index = None;
681            inner.hold_scroll_window = false;
682            let pending_scroll_delta = std::mem::take(&mut inner.scroll_to_be_consumed);
683            if pending_scroll_delta.abs() > 0.001 {
684                inner.last_scroll_delta = pending_scroll_delta;
685            }
686        });
687    }
688
689    pub(crate) fn next_measure_cycle_id(&self) -> u64 {
690        self.inner
691            .try_with(|cell| {
692                let mut inner = cell.borrow_mut();
693                let id = inner.next_measure_cycle_id;
694                inner.next_measure_cycle_id = inner.next_measure_cycle_id.saturating_add(1);
695                id
696            })
697            .unwrap_or(0)
698    }
699
700    pub(crate) fn next_item_measure_pass_id(&self) -> u64 {
701        self.inner
702            .try_with(|cell| {
703                let mut inner = cell.borrow_mut();
704                let id = inner.next_item_measure_pass_id;
705                inner.next_item_measure_pass_id = inner.next_item_measure_pass_id.saturating_add(1);
706                id
707            })
708            .unwrap_or(0)
709    }
710
711    fn record_item_size_sample(inner: &mut LazyListStateInner, size: f32) {
712        inner.total_measured_items += 1;
713        let n = inner.total_measured_items as f32;
714        inner.average_item_size = inner.average_item_size * ((n - 1.0) / n) + size / n;
715    }
716
717    fn next_item_size_cache_tick(inner: &mut LazyListStateInner) -> u64 {
718        inner.item_size_clock = inner.item_size_clock.saturating_add(1);
719        inner.item_size_clock
720    }
721
722    fn insert_item_size(inner: &mut LazyListStateInner, index: usize, key: u64, size: f32) -> bool {
723        let tick = Self::next_item_size_cache_tick(inner);
724        let item = CachedItemSize {
725            key,
726            size,
727            last_used: tick,
728        };
729        if let Some(cached) = inner.item_size_cache.get_mut(&index) {
730            *cached = item;
731            return false;
732        }
733        if inner.item_size_cache.len() >= ITEM_SIZE_CACHE_CAPACITY {
734            Self::evict_stale_item_sizes(inner, tick);
735        }
736        inner.item_size_cache.insert(index, item);
737        true
738    }
739
740    /// Forgets the sizes that no read or write used in the last half of the
741    /// cache's capacity of uses. Every use takes the next tick, so at most
742    /// half the entries were used that recently: a full cache frees half its
743    /// room in one pass, and the oldest sizes go first.
744    fn evict_stale_item_sizes(inner: &mut LazyListStateInner, tick: u64) {
745        let oldest_kept = tick.saturating_sub((ITEM_SIZE_CACHE_CAPACITY / 2) as u64);
746        inner
747            .item_size_cache
748            .retain(|_, item| item.last_used > oldest_kept);
749    }
750
751    /// Caches measured `(index, key, size)` item sizes and returns the updated average.
752    pub fn cache_item_sizes<I>(&self, sizes: I) -> f32
753    where
754        I: IntoIterator<Item = (usize, u64, f32)>,
755    {
756        self.inner
757            .try_with(|cell| {
758                let mut inner = cell.borrow_mut();
759                for (index, key, size) in sizes {
760                    if Self::insert_item_size(&mut inner, index, key, size) {
761                        Self::record_item_size_sample(&mut inner, size);
762                    }
763                }
764                inner.average_item_size
765            })
766            .unwrap_or(super::DEFAULT_ITEM_SIZE_ESTIMATE)
767    }
768
769    /// The size cached for `index`, when it was measured for the item with
770    /// `key`: once items move, an index holds another item, whose size the
771    /// list does not know.
772    pub fn cached_item_size(&self, index: usize, key: u64) -> Option<f32> {
773        self.inner
774            .try_with(|cell| {
775                let mut inner = cell.borrow_mut();
776                let tick = Self::next_item_size_cache_tick(&mut inner);
777                let item = inner
778                    .item_size_cache
779                    .get_mut(&index)
780                    .filter(|item| item.key == key)?;
781                item.last_used = tick;
782                Some(item.size)
783            })
784            .flatten()
785    }
786
787    /// Returns the running average of measured item sizes.
788    pub fn average_item_size(&self) -> f32 {
789        self.inner
790            .try_with(|cell| cell.borrow().average_item_size)
791            .unwrap_or(super::DEFAULT_ITEM_SIZE_ESTIMATE)
792    }
793
794    /// Returns the current nearest range for optimized key lookup.
795    pub fn nearest_range(&self) -> std::ops::Range<usize> {
796        self.scroll_position.nearest_range()
797    }
798
799    pub(crate) fn update_scroll_position(
800        &self,
801        first_visible_item_index: usize,
802        first_visible_item_scroll_offset: f32,
803    ) {
804        self.scroll_position.update_from_measure_result(
805            first_visible_item_index,
806            first_visible_item_scroll_offset,
807            None,
808        );
809    }
810
811    pub(crate) fn update_scroll_position_with_key(
812        &self,
813        first_visible_item_index: usize,
814        first_visible_item_scroll_offset: f32,
815        first_visible_item_key: u64,
816    ) {
817        self.scroll_position.update_from_measure_result(
818            first_visible_item_index,
819            first_visible_item_scroll_offset,
820            Some(first_visible_item_key),
821        );
822    }
823
824    /// Adjusts scroll position if the first visible item was moved due to data changes.
825    ///
826    /// Matches JC's `updateScrollPositionIfTheFirstItemWasMoved`.
827    /// If items were inserted/removed before the current scroll position,
828    /// this finds the item by its key and updates the index accordingly.
829    ///
830    /// Returns the adjusted first visible item index.
831    pub fn update_scroll_position_if_item_moved<F>(
832        &self,
833        new_item_count: usize,
834        get_index_by_key: F,
835    ) -> usize
836    where
837        F: Fn(u64) -> Option<usize>,
838    {
839        self.scroll_position
840            .update_if_first_item_moved(new_item_count, get_index_by_key)
841    }
842
843    /// Whether [`Self::update_scroll_position_if_item_moved`] would move the
844    /// scroll position.
845    pub fn first_visible_item_moved<F>(&self, new_item_count: usize, get_index_by_key: F) -> bool
846    where
847        F: Fn(u64) -> Option<usize>,
848    {
849        self.scroll_position
850            .first_item_moved(new_item_count, get_index_by_key)
851    }
852
853    pub(crate) fn update_layout_info(&self, mut info: LazyListLayoutInfo) {
854        self.inner.try_with(|cell| {
855            let mut inner = cell.borrow_mut();
856            info.snap_anchor_offset = continuous_snap_anchor_offset(&inner.layout_info, &info);
857            let mut spare = std::mem::replace(&mut inner.layout_info, info).visible_items_info;
858            spare.clear();
859            inner.spare_items_info = spare;
860        });
861    }
862
863    /// An empty list for the next layout info's visible items, which keeps
864    /// the storage of the one before.
865    pub(crate) fn spare_items_info(&self) -> Vec<LazyListItemInfo> {
866        self.inner
867            .try_with(|cell| std::mem::take(&mut cell.borrow_mut().spare_items_info))
868            .unwrap_or_default()
869    }
870
871    /// Returns whether we can scroll forward (more items below/right).
872    ///
873    /// When called during composition, this creates a reactive subscription
874    /// so that changes will trigger recomposition.
875    pub fn can_scroll_forward(&self) -> bool {
876        if !self.can_scroll_forward_state.is_alive() {
877            return false;
878        }
879        self.can_scroll_forward_state.subscribe_current_scope_only();
880        self.can_scroll_forward_non_reactive()
881    }
882
883    /// Returns whether the list can scroll forward without subscribing the current composition scope.
884    pub fn can_scroll_forward_non_reactive(&self) -> bool {
885        if !self.can_scroll_forward_state.is_alive() {
886            return false;
887        }
888        self.inner
889            .try_with(|cell| cell.borrow().current_can_scroll_forward)
890            .unwrap_or(false)
891    }
892
893    /// Returns whether we can scroll backward (more items above/left).
894    ///
895    /// When called during composition, this creates a reactive subscription
896    /// so that changes will trigger recomposition.
897    pub fn can_scroll_backward(&self) -> bool {
898        if !self.can_scroll_backward_state.is_alive() {
899            return false;
900        }
901        self.can_scroll_backward_state
902            .subscribe_current_scope_only();
903        self.can_scroll_backward_non_reactive()
904    }
905
906    /// Returns whether the list can scroll backward without subscribing the current composition scope.
907    pub fn can_scroll_backward_non_reactive(&self) -> bool {
908        if !self.can_scroll_backward_state.is_alive() {
909            return false;
910        }
911        self.inner
912            .try_with(|cell| cell.borrow().current_can_scroll_backward)
913            .unwrap_or(false)
914    }
915
916    pub(crate) fn update_scroll_bounds(&self) {
917        if !self.can_scroll_forward_state.is_alive() || !self.can_scroll_backward_state.is_alive() {
918            return;
919        }
920        let Some(cell) = self.inner.try_get() else {
921            return;
922        };
923        let can_forward = {
924            let inner = cell.borrow();
925            let info = &inner.layout_info;
926            let viewport_end = info.viewport_end_offset - info.after_content_padding;
927            // A staggered grid's last item by index need not be the one
928            // that reaches furthest.
929            if let Some(last_visible) = info.visible_items_info.last() {
930                last_visible.index < info.total_items_count.saturating_sub(1)
931                    || info
932                        .visible_items_info
933                        .iter()
934                        .rev()
935                        .any(|item| item.offset + item.size > viewport_end)
936            } else {
937                false
938            }
939        };
940
941        let (first_index, first_offset) = self.try_position().unwrap_or((0, 0.0));
942        let can_backward = first_index > 0 || first_offset > 0.0;
943
944        {
945            let mut inner = cell.borrow_mut();
946            inner.current_can_scroll_forward = can_forward;
947            inner.current_can_scroll_backward = can_backward;
948        }
949
950        if self.can_scroll_forward_state.get_non_reactive() != can_forward {
951            self.can_scroll_forward_state.set(can_forward);
952        }
953        if self.can_scroll_backward_state.get_non_reactive() != can_backward {
954            self.can_scroll_backward_state.set(can_backward);
955        }
956    }
957
958    /// Adds an invalidation callback.
959    pub fn add_invalidate_callback(&self, callback: Rc<dyn Fn()>) -> u64 {
960        self.inner
961            .try_with(|cell| {
962                let mut inner = cell.borrow_mut();
963                let id = inner.next_callback_id;
964                inner.next_callback_id += 1;
965                inner.invalidate_callbacks.push((id, callback));
966                id
967            })
968            .unwrap_or(0)
969    }
970
971    /// Tries to register a layout invalidation callback for the specified node.
972    ///
973    /// Returns the callback id for the active layout callback.
974    ///
975    /// Registering again always replaces the previous active layout callback, even when
976    /// the node id stays the same. This keeps ownership tied to the latest effect
977    /// instance so disposing an older scope cannot unregister the live callback.
978    pub fn try_register_layout_callback(
979        &self,
980        node_id: NodeId,
981        callback: Rc<dyn Fn()>,
982    ) -> Option<u64> {
983        if !self.inner.is_alive() {
984            return None;
985        }
986        self.inner.with(|cell| {
987            let mut inner = cell.borrow_mut();
988            if let Some(existing_id) = inner.layout_invalidation_callback_id {
989                inner
990                    .invalidate_callbacks
991                    .retain(|(cb_id, _)| *cb_id != existing_id);
992            }
993            let id = inner.next_callback_id;
994            inner.next_callback_id += 1;
995            inner.invalidate_callbacks.push((id, callback));
996            inner.layout_invalidation_callback_id = Some(id);
997            inner.layout_invalidation_node_id = Some(node_id);
998            Some(id)
999        })
1000    }
1001
1002    /// Removes an invalidation callback.
1003    pub fn remove_invalidate_callback(&self, id: u64) {
1004        self.inner.try_with(|cell| {
1005            let mut inner = cell.borrow_mut();
1006            inner.invalidate_callbacks.retain(|(cb_id, _)| *cb_id != id);
1007            if inner.layout_invalidation_callback_id == Some(id) {
1008                inner.layout_invalidation_callback_id = None;
1009                inner.layout_invalidation_node_id = None;
1010            }
1011        });
1012    }
1013
1014    fn invalidate(&self) {
1015        if let Some(cell) = self.inner.try_get() {
1016            Self::run_invalidate_callbacks(&cell);
1017        }
1018    }
1019
1020    /// Runs the invalidation callbacks `cell` holds, from a copy of the
1021    /// list: a callback may register or remove callbacks. A list has one or two.
1022    fn run_invalidate_callbacks(cell: &RefCell<LazyListStateInner>) {
1023        let callbacks: smallvec::SmallVec<[_; 2]> = cell
1024            .borrow()
1025            .invalidate_callbacks
1026            .iter()
1027            .map(|(_, cb)| Rc::clone(cb))
1028            .collect();
1029
1030        for callback in callbacks {
1031            callback();
1032        }
1033    }
1034}
1035
1036/// Information about the currently visible items in a lazy list.
1037#[derive(Clone, Default, Debug)]
1038pub struct LazyListLayoutInfo {
1039    /// Information about each visible item.
1040    pub visible_items_info: Vec<LazyListItemInfo>,
1041
1042    /// Total number of items in the list.
1043    pub total_items_count: usize,
1044
1045    /// Raw viewport size reported by parent constraints (before infinite fallback).
1046    pub raw_viewport_size: f32,
1047
1048    /// Whether the viewport was treated as infinite/unbounded.
1049    pub is_infinite_viewport: bool,
1050
1051    /// Size of the viewport in the main axis.
1052    pub viewport_size: f32,
1053
1054    /// Where the viewport starts from the start padding's edge: Compose's `viewportStartOffset`.
1055    pub viewport_start_offset: f32,
1056
1057    /// Where the viewport ends from the start padding's edge: Compose's `viewportEndOffset`.
1058    pub viewport_end_offset: f32,
1059
1060    /// Content padding before the first item.
1061    pub before_content_padding: f32,
1062
1063    /// Content padding after the last item.
1064    pub after_content_padding: f32,
1065
1066    /// The space between two items — Compose's `mainAxisItemSpacing`.
1067    pub main_axis_item_spacing: f32,
1068
1069    /// Continuous main-axis visual offset used to snap translated lazy-list content.
1070    pub snap_anchor_offset: f32,
1071
1072    /// Whether item offsets are placed from the end edge of the viewport.
1073    pub reverse_layout: bool,
1074}
1075
1076/// Information about a single visible item in a lazy list.
1077#[derive(Clone, Debug)]
1078pub struct LazyListItemInfo {
1079    /// Index of the item in the data source.
1080    pub index: usize,
1081
1082    /// Key of the item.
1083    pub key: u64,
1084
1085    /// Offset of the item from the start padding's edge, negative in it.
1086    pub offset: f32,
1087
1088    /// Size of the item in the main axis.
1089    pub size: f32,
1090}
1091
1092fn continuous_snap_anchor_offset(
1093    previous: &LazyListLayoutInfo,
1094    current: &LazyListLayoutInfo,
1095) -> f32 {
1096    let Some(first_current) = current.visible_items_info.first() else {
1097        return 0.0;
1098    };
1099
1100    for current_item in &current.visible_items_info {
1101        if let Some(previous_item) = previous
1102            .visible_items_info
1103            .iter()
1104            .find(|item| item.key == current_item.key)
1105        {
1106            let previous_offset = snap_anchor_item_offset(previous, previous_item);
1107            let current_offset = snap_anchor_item_offset(current, current_item);
1108            return previous.snap_anchor_offset + current_offset - previous_offset;
1109        }
1110    }
1111
1112    snap_anchor_item_offset(current, first_current)
1113}
1114
1115fn snap_anchor_item_offset(info: &LazyListLayoutInfo, item: &LazyListItemInfo) -> f32 {
1116    if info.reverse_layout {
1117        info.viewport_size + info.viewport_start_offset - item.offset - item.size
1118    } else {
1119        item.offset - info.viewport_start_offset
1120    }
1121}
1122
1123#[cfg(test)]
1124#[path = "tests/lazy_list_state_test_helpers.rs"]
1125pub(crate) mod test_helpers;
1126
1127#[cfg(test)]
1128#[path = "tests/lazy_list_state_tests.rs"]
1129mod tests;