Skip to main content

cranpose_ui/widgets/
animate_scroll.rs

1//! Animated scrolling of lazy lists, and of the grids and pagers built on
2//! them, and of scrolling columns: Compose's `animateScrollBy`,
3//! `animateScrollToItem` and `ScrollState.animateScrollTo`.
4
5use cranpose_foundation::{ScrollId, lazy::LazyListState};
6
7use crate::{
8    fling_animation::{SettleAnimation, SpringParams},
9    scroll::ScrollState,
10};
11
12/// Scrolls a lazy list with a spring. A press on the list, or another
13/// animation, stops it where it is.
14pub trait AnimateScroll {
15    /// Scrolls `distance` logical pixels, positive toward the end.
16    fn animate_scroll_by(&self, distance: f32);
17
18    /// Scrolls until item `index` starts `offset` past the start of the
19    /// viewport, as [`LazyListState::scroll_to_item`] would place it.
20    fn animate_scroll_to_item(&self, index: usize, offset: f32);
21}
22
23// A scroll state that a spring moves. It keeps one running scroll, which the
24// spring takes.
25trait SpringTarget: Copy + 'static {
26    // Where a spring that ends on its own puts the state, so that it rests
27    // exactly there.
28    type Landing: 'static;
29
30    // Moves the content by `delta` toward the end. Returns how far it moved.
31    fn move_by(self, delta: f32) -> f32;
32
33    fn land(self, landing: Self::Landing);
34
35    // `None` once the slot that held the state was released.
36    fn start_run(self, stop: impl FnOnce() + 'static) -> Option<ScrollId>;
37
38    fn end_run(self, id: ScrollId);
39}
40
41impl SpringTarget for LazyListState {
42    type Landing = (usize, f32);
43
44    fn move_by(self, delta: f32) -> f32 {
45        -self.dispatch_scroll_delta(-delta)
46    }
47
48    fn land(self, (index, offset): (usize, f32)) {
49        self.scroll_to_item(index, offset);
50    }
51
52    fn start_run(self, stop: impl FnOnce() + 'static) -> Option<ScrollId> {
53        self.start_scroll_animation(stop)
54    }
55
56    fn end_run(self, id: ScrollId) {
57        self.end_scroll_animation(id);
58    }
59}
60
61impl SpringTarget for ScrollState {
62    type Landing = f32;
63
64    // A column can leave the composition while the spring runs.
65    fn move_by(self, delta: f32) -> f32 {
66        if self.try_value().is_none() {
67            return 0.0;
68        }
69        self.dispatch_raw_delta(delta)
70    }
71
72    fn land(self, value: f32) {
73        if self.try_value().is_some() {
74            self.scroll_to(value);
75        }
76    }
77
78    fn start_run(self, stop: impl FnOnce() + 'static) -> Option<ScrollId> {
79        Some(self.start_scroll_animation(stop))
80    }
81
82    fn end_run(self, id: ScrollId) {
83        self.end_scroll_animation(id);
84    }
85}
86
87impl AnimateScroll for LazyListState {
88    fn animate_scroll_by(&self, distance: f32) {
89        animate(*self, distance, None);
90    }
91
92    fn animate_scroll_to_item(&self, index: usize, offset: f32) {
93        animate(
94            *self,
95            distance_to_item(self, index) + offset,
96            Some((index, offset)),
97        );
98    }
99}
100
101// Springs `state` to `value`, which lies within its range.
102pub(crate) fn animate_scroll_state_to(state: ScrollState, value: f32) {
103    animate(state, value - state.value_non_reactive(), Some(value));
104}
105
106/// How far item `index` starts past where `scroll_to_item(index, 0)` puts
107/// it: measured when the list shows it, estimated from the average item size
108/// when not. The animation lands on the item exactly either way.
109fn distance_to_item(state: &LazyListState, index: usize) -> f32 {
110    let shown = state.with_layout_info(|info| {
111        info.visible_items_info
112            .iter()
113            .find(|item| item.index == index)
114            .map(|item| item.offset)
115    });
116    if let Some(distance) = shown.flatten() {
117        return distance;
118    }
119    let first = state.first_visible_item_index_non_reactive();
120    let scrolled = state.first_visible_item_scroll_offset_non_reactive();
121    (index as f32 - first as f32) * state.average_item_size() - scrolled
122}
123
124/// Springs `state` through `distance`, then puts it at `land` when the
125/// animation ends on its own.
126fn animate<S: SpringTarget>(state: S, distance: f32, land: Option<S::Landing>) {
127    let Some(runtime) = cranpose_core::current_runtime_handle() else {
128        match land {
129            Some(landing) => state.land(landing),
130            None => {
131                state.move_by(distance);
132            }
133        }
134        return;
135    };
136    let settle = SettleAnimation::new(runtime, SpringParams::SETTLE_POLICY);
137    let stop = settle.clone();
138    let id = state.start_run(move || stop.cancel());
139    settle.start_settle(
140        0.0,
141        0.0,
142        distance,
143        move |delta| state.move_by(delta),
144        move |_| {
145            if let Some(id) = id {
146                state.end_run(id);
147            }
148            if let Some(landing) = land {
149                state.land(landing);
150            }
151        },
152    );
153}