Skip to main content

gpui_material_components/pull_to_refresh/
state.rs

1use std::{rc::Rc, time::Duration};
2
3use gpui::{
4    App, Context, ElementId, Pixels, ScrollHandle, ScrollSource, Window, WindowId, point, px,
5};
6use gpui_base::motion::Easing;
7use gpui_material_foundation::RetargetTransition;
8
9const DRAG_MULTIPLIER: f32 = 0.5;
10const SETTLE: Duration = Duration::from_millis(180);
11
12pub(super) type ScrollPosition = Rc<dyn Fn(&Window, &App) -> Pixels>;
13
14/// Readback supplied to a caller's indicator.
15#[derive(Clone, Copy, Debug, PartialEq)]
16pub struct PullToRefreshProgress {
17    /// Pull progress relative to the refresh threshold (`0.0` hidden, `1.0` threshold, >`1.0` overshoot).
18    pub distance_fraction: f32,
19    /// Current downward translation of the indicator in logical pixels.
20    pub offset: Pixels,
21    /// Whether the caller-owned refreshing state is currently active.
22    pub refreshing: bool,
23    /// Whether a refresh request has been emitted and is awaiting caller confirmation or rejection.
24    pub refresh_pending: bool,
25    /// Whether the indicator is currently animating toward its resting or threshold position.
26    pub animating: bool,
27}
28
29#[derive(Clone, Eq, PartialEq)]
30pub(super) struct ViewportKey {
31    pub(super) window: WindowId,
32    pub(super) id: ElementId,
33}
34
35pub(super) struct PullGesture {
36    pub(super) source: ScrollSource,
37    pub(super) distance: Pixels,
38    pub(super) before_scroll: Pixels,
39}
40
41/// Retained gesture and indicator state. The application owns refreshing.
42pub struct PullToRefreshState {
43    scroll: ScrollHandle,
44    pub(super) viewport: Option<ViewportKey>,
45    pub(super) gesture: Option<PullGesture>,
46    pub(super) fraction: f32,
47    motion: RetargetTransition,
48    pub(super) refreshing: bool,
49    pub(super) pending: bool,
50    enabled: bool,
51    pub(super) visible: bool,
52}
53
54impl Default for PullToRefreshState {
55    fn default() -> Self {
56        Self {
57            scroll: ScrollHandle::new(),
58            viewport: None,
59            gesture: None,
60            fraction: 0.,
61            motion: RetargetTransition::settled(0.),
62            refreshing: false,
63            pending: false,
64            enabled: true,
65            visible: true,
66        }
67    }
68}
69
70impl PullToRefreshState {
71    /// Creates an idle pull-to-refresh state with its own internal scroll handle.
72    pub fn new() -> Self {
73        Self::default()
74    }
75
76    /// The scroll handle used when the container owns its viewport.
77    pub fn scroll_handle(&self) -> ScrollHandle {
78        self.scroll.clone()
79    }
80
81    /// Zero is hidden and one is the refresh threshold. Pull overshoot can exceed one.
82    pub fn distance_fraction(&self) -> f32 {
83        self.fraction
84    }
85
86    /// Returns `true` while the indicator is transitioning between positions.
87    pub fn is_animating(&self) -> bool {
88        self.motion.is_animating()
89    }
90
91    /// Returns `true` when a refresh callback has been triggered and awaits a state update or [`Self::reject_refresh`].
92    pub fn is_refresh_pending(&self) -> bool {
93        self.pending
94    }
95
96    /// Sets the displayed distance immediately and cancels an active gesture.
97    pub fn snap_to(&mut self, fraction: f32, cx: &mut Context<Self>) {
98        let target = if fraction.is_finite() {
99            fraction.max(0.)
100        } else {
101            0.
102        };
103        let had_gesture = self.gesture.take().is_some();
104        let was_animating = self.motion.is_animating();
105        let changed = had_gesture || self.fraction != target || was_animating;
106        self.fraction = target;
107        self.motion.snap_to(self.fraction);
108        if changed {
109            cx.notify();
110        }
111    }
112
113    /// Cancels any active gesture and animates the indicator to the refresh threshold (`1.0`).
114    pub fn animate_to_threshold(&mut self, cx: &mut Context<Self>) {
115        self.animate_to_fraction(1., cx);
116    }
117
118    /// Cancels any active gesture and animates the indicator back to hidden (`0.0`).
119    pub fn animate_to_hidden(&mut self, cx: &mut Context<Self>) {
120        self.animate_to_fraction(0., cx);
121    }
122
123    fn animate_to_fraction(&mut self, target: f32, cx: &mut Context<Self>) {
124        let had_gesture = self.gesture.take().is_some();
125        let was_animating = self.motion.is_animating();
126        let before = self.fraction;
127        self.settle_to(target, cx);
128        if had_gesture || was_animating || before != self.fraction || self.motion.is_animating() {
129            cx.notify();
130        }
131    }
132
133    /// Clears the current pull and any unanswered request, keeping the controlled busy value.
134    pub fn reset(&mut self, cx: &mut Context<Self>) {
135        self.pending = false;
136        self.snap_to(if self.refreshing { 1. } else { 0. }, cx);
137    }
138
139    /// Rearms refresh after the owner declines a pending request.
140    pub fn reject_refresh(&mut self, cx: &mut Context<Self>) {
141        if self.pending {
142            self.pending = false;
143            self.animate_to_hidden(cx);
144        }
145    }
146
147    pub(super) fn can_request(&self) -> bool {
148        self.enabled && !self.refreshing && !self.pending
149    }
150
151    pub(super) fn configure(
152        &mut self,
153        viewport: &ViewportKey,
154        refreshing: bool,
155        enabled: bool,
156        window: &mut Window,
157        cx: &App,
158    ) {
159        let retargeted = self.viewport.as_ref() != Some(viewport);
160        if retargeted && self.viewport.replace(viewport.clone()).is_some() {
161            self.gesture = None;
162            self.fraction = f32::from(refreshing || self.pending);
163            self.motion.snap_to(self.fraction);
164        }
165        if refreshing != self.refreshing {
166            self.refreshing = refreshing;
167            self.pending = false;
168            self.gesture = None;
169            self.settle_to(f32::from(refreshing), cx);
170        } else if self.enabled && !enabled && self.gesture.take().is_some() {
171            self.settle_to(0., cx);
172        }
173        self.enabled = enabled;
174        self.sample_motion(window, cx);
175    }
176
177    pub(super) fn settle_to(&mut self, target: f32, cx: &App) {
178        let now = cx.background_executor().now();
179        self.motion
180            .animate_to(target, SETTLE, Easing::EaseOut, now, cx.reduce_motion());
181        self.fraction = self.motion.value();
182    }
183
184    fn sample_motion(&mut self, window: &mut Window, cx: &App) {
185        if self.motion.is_animating() {
186            let now = cx.background_executor().now();
187            let (value, running) = self.motion.sample(now, cx.reduce_motion());
188            self.fraction = value;
189            if running && window.is_visible() && self.visible {
190                window.request_animation_frame();
191            }
192        }
193    }
194
195    pub(super) fn set_visible(&mut self, visible: bool, window: &mut Window) {
196        let resumed = !self.visible && visible;
197        self.visible = visible;
198        if resumed && self.motion.is_animating() && window.is_visible() {
199            window.request_animation_frame();
200        }
201    }
202
203    pub(super) fn pull_by(&mut self, amount: Pixels, threshold: Pixels, cx: &mut Context<Self>) {
204        if let Some(gesture) = &mut self.gesture {
205            let next_distance = (gesture.distance + amount).max(px(0.));
206            let next_fraction = pull_fraction(next_distance, threshold);
207            if next_distance != gesture.distance
208                || next_fraction != self.fraction
209                || self.motion.is_animating()
210            {
211                gesture.distance = next_distance;
212                self.fraction = next_fraction;
213                self.motion.snap_to(self.fraction);
214                cx.notify();
215            }
216        }
217    }
218}
219
220pub(super) fn pull_fraction(distance: Pixels, threshold: Pixels) -> f32 {
221    if !f32::from(distance).is_finite()
222        || !f32::from(threshold).is_finite()
223        || threshold <= px(0.)
224        || distance <= px(0.)
225    {
226        return 0.;
227    }
228    let progress = (distance / threshold) * DRAG_MULTIPLIER;
229    let overshoot = (progress - 1.).clamp(0., 2.);
230    progress.min(1.) + overshoot - overshoot.powi(2) * 0.25
231}
232
233pub(super) fn meets_refresh_threshold(fraction: f32) -> bool {
234    fraction.is_finite() && fraction >= 1.
235}
236
237#[derive(Clone)]
238pub(super) enum ScrollBinding {
239    Handle(ScrollHandle),
240    Position(ScrollPosition),
241}
242
243impl ScrollBinding {
244    pub(super) fn distance_from_top(&self, window: &Window, cx: &App) -> Pixels {
245        let distance = match self {
246            Self::Handle(handle) => -handle.offset().y,
247            Self::Position(position) => position(window, cx),
248        };
249        if f32::from(distance).is_finite() {
250            distance.max(px(0.))
251        } else {
252            px(f32::MAX)
253        }
254    }
255
256    pub(super) fn remove_overscroll(&self) {
257        if let Self::Handle(handle) = self {
258            let offset = handle.offset();
259            if offset.y > px(0.) {
260                handle.set_offset(point(offset.x, px(0.)));
261            }
262        }
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    #[test]
271    fn pull_fraction_reaches_threshold_and_dampens_overshoot() {
272        assert_eq!(pull_fraction(px(0.), px(80.)), 0.);
273        assert_eq!(pull_fraction(px(-10.), px(80.)), 0.);
274        assert_eq!(pull_fraction(px(f32::NAN), px(80.)), 0.);
275        assert_eq!(pull_fraction(px(80.), px(80.)), 0.5);
276        assert_eq!(pull_fraction(px(160.), px(80.)), 1.0);
277        assert!(meets_refresh_threshold(pull_fraction(px(160.), px(80.))));
278        assert!(!meets_refresh_threshold(pull_fraction(px(159.), px(80.))));
279        assert!(!meets_refresh_threshold(f32::NAN));
280        assert_eq!(pull_fraction(px(320.), px(80.)), 1.75);
281        assert_eq!(pull_fraction(px(640.), px(80.)), 2.0);
282    }
283}