Skip to main content

gpui_material_components/
pull_to_refresh.rs

1use std::{rc::Rc, time::Duration};
2
3use gpui::{
4    AnyElement, App, Bounds, Context, ElementId, Entity, GlobalElementId, Hitbox, HitboxBehavior,
5    InspectorElementId, InteractiveElement, IntoElement, LayoutId, ParentElement, Pixels,
6    RenderOnce, ScrollEvent, ScrollHandle, ScrollSource, SharedString, StatefulInteractiveElement,
7    StyleRefinement, Styled, TouchPhase, WeakEntity, Window, WindowId, div, point,
8    prelude::FluentBuilder, px,
9};
10use gpui_base::{StyledExt, TestSupportExt, motion::Easing};
11use gpui_material_foundation::{RetargetTransition, current_material_theme};
12use gpui_material_theme::Direction;
13
14use crate::{Button, ButtonVariant, LoadingIndicator};
15
16const DEFAULT_DISTANCE: Pixels = px(80.);
17const DRAG_MULTIPLIER: f32 = 0.5;
18const SETTLE: Duration = Duration::from_millis(180);
19
20type Refresh = Rc<dyn Fn(&mut Window, &mut App)>;
21type ScrollPosition = Rc<dyn Fn(&Window, &App) -> Pixels>;
22type Indicator = Box<dyn FnOnce(PullToRefreshProgress, &mut Window, &mut App) -> AnyElement>;
23
24/// Readback supplied to a caller's indicator.
25#[derive(Clone, Copy, Debug, PartialEq)]
26pub struct PullToRefreshProgress {
27    /// Pull progress relative to the refresh threshold (`0.0` hidden, `1.0` threshold, >`1.0` overshoot).
28    pub distance_fraction: f32,
29    /// Current downward translation of the indicator in logical pixels.
30    pub offset: Pixels,
31    /// Whether the caller-owned refreshing state is currently active.
32    pub refreshing: bool,
33    /// Whether a refresh request has been emitted and is awaiting caller confirmation or rejection.
34    pub refresh_pending: bool,
35    /// Whether the indicator is currently animating toward its resting or threshold position.
36    pub animating: bool,
37}
38
39#[derive(Clone, Eq, PartialEq)]
40struct ViewportKey {
41    window: WindowId,
42    id: ElementId,
43}
44
45struct PullGesture {
46    source: ScrollSource,
47    distance: Pixels,
48    before_scroll: Pixels,
49}
50
51/// Retained gesture and indicator state. The application owns refreshing.
52pub struct PullToRefreshState {
53    scroll: ScrollHandle,
54    viewport: Option<ViewportKey>,
55    gesture: Option<PullGesture>,
56    fraction: f32,
57    motion: RetargetTransition,
58    refreshing: bool,
59    pending: bool,
60    enabled: bool,
61}
62
63impl Default for PullToRefreshState {
64    fn default() -> Self {
65        Self {
66            scroll: ScrollHandle::new(),
67            viewport: None,
68            gesture: None,
69            fraction: 0.,
70            motion: RetargetTransition::settled(0.),
71            refreshing: false,
72            pending: false,
73            enabled: true,
74        }
75    }
76}
77
78impl PullToRefreshState {
79    /// Creates an idle pull-to-refresh state with its own internal scroll handle.
80    pub fn new() -> Self {
81        Self::default()
82    }
83
84    /// The scroll handle used when the container owns its viewport.
85    pub fn scroll_handle(&self) -> ScrollHandle {
86        self.scroll.clone()
87    }
88
89    /// Zero is hidden and one is the refresh threshold. Pull overshoot can exceed one.
90    pub fn distance_fraction(&self) -> f32 {
91        self.fraction
92    }
93
94    /// Returns `true` while the indicator is transitioning between positions.
95    pub fn is_animating(&self) -> bool {
96        self.motion.is_animating()
97    }
98
99    /// Returns `true` when a refresh callback has been triggered and awaits a state update or [`Self::reject_refresh`].
100    pub fn is_refresh_pending(&self) -> bool {
101        self.pending
102    }
103
104    /// Sets the displayed distance immediately and cancels an active gesture.
105    pub fn snap_to(&mut self, fraction: f32, cx: &mut Context<Self>) {
106        let target = if fraction.is_finite() {
107            fraction.max(0.)
108        } else {
109            0.
110        };
111        let had_gesture = self.gesture.take().is_some();
112        let was_animating = self.motion.is_animating();
113        let changed = had_gesture || self.fraction != target || was_animating;
114        self.fraction = target;
115        self.motion.snap_to(self.fraction);
116        if changed {
117            cx.notify();
118        }
119    }
120
121    /// Cancels any active gesture and animates the indicator to the refresh threshold (`1.0`).
122    pub fn animate_to_threshold(&mut self, cx: &mut Context<Self>) {
123        self.animate_to_fraction(1., cx);
124    }
125
126    /// Cancels any active gesture and animates the indicator back to hidden (`0.0`).
127    pub fn animate_to_hidden(&mut self, cx: &mut Context<Self>) {
128        self.animate_to_fraction(0., cx);
129    }
130
131    fn animate_to_fraction(&mut self, target: f32, cx: &mut Context<Self>) {
132        let had_gesture = self.gesture.take().is_some();
133        let was_animating = self.motion.is_animating();
134        let before = self.fraction;
135        self.settle_to(target, cx);
136        if had_gesture || was_animating || before != self.fraction || self.motion.is_animating() {
137            cx.notify();
138        }
139    }
140
141    /// Clears the current pull and any unanswered request, keeping the controlled busy value.
142    pub fn reset(&mut self, cx: &mut Context<Self>) {
143        self.pending = false;
144        self.snap_to(if self.refreshing { 1. } else { 0. }, cx);
145    }
146
147    /// Rearms refresh after the owner declines a pending request.
148    pub fn reject_refresh(&mut self, cx: &mut Context<Self>) {
149        if self.pending {
150            self.pending = false;
151            self.animate_to_hidden(cx);
152        }
153    }
154
155    fn can_request(&self) -> bool {
156        self.enabled && !self.refreshing && !self.pending
157    }
158
159    fn configure(
160        &mut self,
161        viewport: &ViewportKey,
162        refreshing: bool,
163        enabled: bool,
164        window: &mut Window,
165        cx: &App,
166    ) {
167        let retargeted = self.viewport.as_ref() != Some(viewport);
168        if retargeted && self.viewport.replace(viewport.clone()).is_some() {
169            self.gesture = None;
170            self.fraction = f32::from(refreshing || self.pending);
171            self.motion.snap_to(self.fraction);
172        }
173        if refreshing != self.refreshing {
174            self.refreshing = refreshing;
175            self.pending = false;
176            self.gesture = None;
177            self.settle_to(f32::from(refreshing), cx);
178        } else if self.enabled && !enabled && self.gesture.take().is_some() {
179            self.settle_to(0., cx);
180        }
181        self.enabled = enabled;
182        self.sample_motion(window, cx);
183    }
184
185    fn settle_to(&mut self, target: f32, cx: &App) {
186        let now = cx.background_executor().now();
187        self.motion
188            .animate_to(target, SETTLE, Easing::EaseOut, now, cx.reduce_motion());
189        self.fraction = self.motion.value();
190    }
191
192    fn sample_motion(&mut self, window: &mut Window, cx: &App) {
193        if self.motion.is_animating() {
194            let now = cx.background_executor().now();
195            let (value, running) = self.motion.sample(now, cx.reduce_motion());
196            self.fraction = value;
197            if running && window.is_visible() {
198                window.request_animation_frame();
199            }
200        }
201    }
202
203    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 progress = (next_distance / threshold) * DRAG_MULTIPLIER;
207            let overshoot = (progress - 1.).clamp(0., 2.);
208            let next_fraction = progress.min(1.) + overshoot - overshoot.powi(2) * 0.25;
209            if next_distance != gesture.distance
210                || next_fraction != self.fraction
211                || self.motion.is_animating()
212            {
213                gesture.distance = next_distance;
214                self.fraction = next_fraction;
215                self.motion.snap_to(self.fraction);
216                cx.notify();
217            }
218        }
219    }
220}
221
222#[derive(Clone)]
223enum ScrollBinding {
224    Handle(ScrollHandle),
225    Position(ScrollPosition),
226}
227
228impl ScrollBinding {
229    fn distance_from_top(&self, window: &Window, cx: &App) -> Pixels {
230        let distance = match self {
231            Self::Handle(handle) => -handle.offset().y,
232            Self::Position(position) => position(window, cx),
233        };
234        if f32::from(distance).is_finite() {
235            distance.max(px(0.))
236        } else {
237            px(f32::MAX)
238        }
239    }
240
241    fn remove_overscroll(&self) {
242        if let Self::Handle(handle) = self {
243            let offset = handle.offset();
244            if offset.y > px(0.) {
245                handle.set_offset(point(offset.x, px(0.)));
246            }
247        }
248    }
249}
250
251/// A vertical viewport with an Expressive refresh indicator and accessible action.
252#[derive(IntoElement)]
253pub struct PullToRefresh {
254    id: ElementId,
255    state: Entity<PullToRefreshState>,
256    refreshing: bool,
257    enabled: bool,
258    refresh: Refresh,
259    label: SharedString,
260    threshold: Pixels,
261    indicator_distance: Pixels,
262    binding: Option<ScrollBinding>,
263    indicator: Option<Indicator>,
264    children: Vec<AnyElement>,
265    style: StyleRefinement,
266}
267
268impl PullToRefresh {
269    /// Creates a pull-to-refresh container bound to `state`, caller-owned `refreshing` status, and refresh callback.
270    pub fn new(
271        id: impl Into<ElementId>,
272        state: &Entity<PullToRefreshState>,
273        refreshing: bool,
274        on_refresh: impl Fn(&mut Window, &mut App) + 'static,
275    ) -> Self {
276        Self {
277            id: id.into(),
278            state: state.clone(),
279            refreshing,
280            enabled: true,
281            refresh: Rc::new(on_refresh),
282            label: "Refresh".into(),
283            threshold: DEFAULT_DISTANCE,
284            indicator_distance: DEFAULT_DISTANCE,
285            binding: None,
286            indicator: None,
287            children: Vec::new(),
288            style: StyleRefinement::default(),
289        }
290    }
291
292    /// Enables or disables pull gestures and the accessible refresh action button. Defaults to `true`.
293    pub fn enabled(mut self, enabled: bool) -> Self {
294        self.enabled = enabled;
295        self
296    }
297
298    /// Sets the label used for both the accessible refresh button and default loading indicator. Defaults to `"Refresh"`.
299    pub fn refresh_label(mut self, label: impl Into<SharedString>) -> Self {
300        self.label = label.into();
301        self
302    }
303
304    /// Sets the pull threshold in logical pixels. Invalid values use the default.
305    pub fn threshold(mut self, threshold: Pixels) -> Self {
306        if f32::from(threshold).is_finite() && threshold > px(0.) {
307            self.threshold = threshold;
308        }
309        self
310    }
311
312    /// Sets indicator travel at the threshold in logical pixels.
313    pub fn indicator_distance(mut self, distance: Pixels) -> Self {
314        if f32::from(distance).is_finite() && distance >= px(0.) {
315            self.indicator_distance = distance;
316        }
317        self
318    }
319
320    /// Wraps a caller-owned viewport that tracks this scroll handle.
321    pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
322        self.binding = Some(ScrollBinding::Handle(handle.clone()));
323        self
324    }
325
326    /// Wraps a caller-owned viewport using a positive distance from its top edge.
327    pub fn scroll_position(mut self, position: impl Fn(&Window, &App) -> Pixels + 'static) -> Self {
328        self.binding = Some(ScrollBinding::Position(Rc::new(position)));
329        self
330    }
331
332    /// Replaces the loading indicator with decorative content using the same reveal.
333    pub fn indicator<E: IntoElement>(
334        mut self,
335        indicator: impl FnOnce(PullToRefreshProgress, &mut Window, &mut App) -> E + 'static,
336    ) -> Self {
337        self.indicator = Some(Box::new(move |progress, window, cx| {
338            indicator(progress, window, cx).into_any_element()
339        }));
340        self
341    }
342}
343
344impl Styled for PullToRefresh {
345    fn style(&mut self) -> &mut StyleRefinement {
346        &mut self.style
347    }
348}
349
350impl ParentElement for PullToRefresh {
351    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
352        self.children.extend(children);
353    }
354}
355
356impl RenderOnce for PullToRefresh {
357    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
358        let viewport = ViewportKey {
359            window: window.window_handle().window_id(),
360            id: self.id.clone(),
361        };
362        let (progress, can_request, scroll) = self.state.update(cx, |state, cx| {
363            state.configure(&viewport, self.refreshing, self.enabled, window, cx);
364            (
365                PullToRefreshProgress {
366                    distance_fraction: state.fraction,
367                    offset: (self.indicator_distance * state.fraction.min(2.))
368                        .min(window.viewport_size().height),
369                    refreshing: state.refreshing,
370                    refresh_pending: state.pending,
371                    animating: state.is_animating(),
372                },
373                state.can_request(),
374                state.scroll_handle(),
375            )
376        });
377        let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
378        let owned = self.binding.is_none();
379        let mut body = div()
380            .id("refresh-scroll")
381            .test_support()
382            .flex()
383            .flex_col()
384            .size_full()
385            .min_h_0()
386            .children(self.children);
387        if owned {
388            body = body.overflow_y_scroll().track_scroll(&scroll);
389        }
390        let driver = RefreshDriver {
391            state: self.state.downgrade(),
392            viewport,
393            refresh: self.refresh,
394            threshold: self.threshold,
395            binding: self.binding.unwrap_or(ScrollBinding::Handle(scroll)),
396        };
397        let command = driver.clone();
398        let indicator = (progress.distance_fraction > 0.).then(|| {
399            let element = match self.indicator {
400                Some(indicator) => indicator(progress, window, cx),
401                None => {
402                    let loading = LoadingIndicator::new("refresh-progress", self.label.clone())
403                        .contained(true);
404                    if progress.refreshing {
405                        loading.into_any_element()
406                    } else {
407                        loading.value(progress.distance_fraction).into_any_element()
408                    }
409                }
410            };
411            div()
412                .absolute()
413                .left_0()
414                .right_0()
415                .top(progress.offset - px(48.))
416                .flex()
417                .justify_center()
418                .child(element)
419        });
420        div()
421            .id(self.id)
422            .flex()
423            .flex_col()
424            .size_full()
425            .min_h_0()
426            .refine_style(&self.style)
427            .child(
428                div()
429                    .flex()
430                    .flex_none()
431                    .when(rtl, Styled::justify_start)
432                    .when(!rtl, Styled::justify_end)
433                    .child(
434                        Button::new("refresh-action", self.label)
435                            .variant(ButtonVariant::Text)
436                            .disabled(!can_request)
437                            .on_activate(move |window, cx| command.request(window, cx)),
438                    ),
439            )
440            .child(
441                div()
442                    .flex_1()
443                    .min_h_0()
444                    .relative()
445                    .overflow_hidden()
446                    .child(RefreshViewport {
447                        driver,
448                        body: body.into_any_element(),
449                    })
450                    .children(indicator),
451            )
452    }
453}
454
455#[derive(Clone)]
456struct RefreshDriver {
457    state: WeakEntity<PullToRefreshState>,
458    viewport: ViewportKey,
459    refresh: Refresh,
460    threshold: Pixels,
461    binding: ScrollBinding,
462}
463
464impl RefreshDriver {
465    fn request(&self, window: &mut Window, cx: &mut App) {
466        let accepted = self.state.update(cx, |state, cx| {
467            if state.viewport.as_ref() != Some(&self.viewport) || !state.can_request() {
468                return false;
469            }
470            state.pending = true;
471            state.gesture = None;
472            state.settle_to(1., cx);
473            cx.notify();
474            true
475        });
476        if accepted.unwrap_or(false) {
477            window.refresh();
478            (self.refresh)(window, cx);
479        }
480    }
481
482    fn listen(self, hitbox: Hitbox, window: &mut Window) {
483        window.on_mouse_event(move |event: &ScrollEvent, phase, window, cx| {
484            if !event.delta.precise() {
485                return;
486            }
487            let hits = hitbox.should_handle_scroll(window);
488            let delta = event.delta.pixel_delta(px(1.));
489            let vertical = delta.y != px(0.)
490                && delta.y.abs() >= delta.x.abs()
491                && f32::from(delta.y).is_finite();
492            let before = self.binding.distance_from_top(window, cx);
493            let (consumed, request) = self
494                .state
495                .update(cx, |state, cx| {
496                    if state.viewport.as_ref() != Some(&self.viewport) || !state.can_request() {
497                        return (false, false);
498                    }
499                    if phase.capture() {
500                        if event.touch_phase == TouchPhase::Started && hits {
501                            if state
502                                .gesture
503                                .as_ref()
504                                .is_some_and(|gesture| gesture.distance > px(0.))
505                            {
506                                state.settle_to(0., cx);
507                                cx.notify();
508                            }
509                            state.gesture = Some(PullGesture {
510                                source: event.source,
511                                distance: px(0.),
512                                before_scroll: before,
513                            });
514                        }
515                        let Some(gesture) = state
516                            .gesture
517                            .as_mut()
518                            .filter(|gesture| gesture.source == event.source)
519                        else {
520                            return (false, false);
521                        };
522                        let pulling = gesture.distance > px(0.);
523                        if matches!(event.touch_phase, TouchPhase::Ended | TouchPhase::Cancelled)
524                            || !hits
525                        {
526                            let request = hits
527                                && event.touch_phase == TouchPhase::Ended
528                                && pulling
529                                && state.fraction > 1.;
530                            state.gesture = None;
531                            if pulling && !request {
532                                state.settle_to(0., cx);
533                                cx.notify();
534                            }
535                            return (pulling && hits, request);
536                        }
537                        gesture.before_scroll = before;
538                        if pulling && vertical {
539                            state.pull_by(delta.y, self.threshold, cx);
540                            return (true, false);
541                        }
542                    } else if hits
543                        && vertical
544                        && delta.y > px(0.)
545                        && let Some(gesture) = state
546                            .gesture
547                            .as_ref()
548                            .filter(|gesture| gesture.source == event.source)
549                    {
550                        // The scroll owner has handled as much of the delta as fits above its top.
551                        let remainder = delta.y - gesture.before_scroll;
552                        if remainder > px(0.) && before <= px(0.) {
553                            self.binding.remove_overscroll();
554                            state.pull_by(remainder, self.threshold, cx);
555                            return (true, false);
556                        }
557                    }
558                    (false, false)
559                })
560                .unwrap_or_default();
561            if consumed {
562                window.refresh();
563                cx.stop_propagation();
564            }
565            if request {
566                self.request(window, cx);
567            }
568        });
569    }
570}
571
572/// Registers before the scroll child in paint order so the child receives the bubble first.
573struct RefreshViewport {
574    driver: RefreshDriver,
575    body: AnyElement,
576}
577
578impl IntoElement for RefreshViewport {
579    type Element = Self;
580
581    fn into_element(self) -> Self {
582        self
583    }
584}
585
586impl gpui::Element for RefreshViewport {
587    type RequestLayoutState = ();
588    type PrepaintState = Hitbox;
589
590    fn id(&self) -> Option<ElementId> {
591        None
592    }
593
594    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
595        None
596    }
597
598    fn request_layout(
599        &mut self,
600        _: Option<&GlobalElementId>,
601        _: Option<&InspectorElementId>,
602        window: &mut Window,
603        cx: &mut App,
604    ) -> (LayoutId, ()) {
605        (self.body.request_layout(window, cx), ())
606    }
607
608    fn prepaint(
609        &mut self,
610        _: Option<&GlobalElementId>,
611        _: Option<&InspectorElementId>,
612        bounds: Bounds<Pixels>,
613        _: &mut (),
614        window: &mut Window,
615        cx: &mut App,
616    ) -> Hitbox {
617        self.body.prepaint(window, cx);
618        window.insert_hitbox(bounds, HitboxBehavior::Normal)
619    }
620
621    fn paint(
622        &mut self,
623        _: Option<&GlobalElementId>,
624        _: Option<&InspectorElementId>,
625        _: Bounds<Pixels>,
626        _: &mut (),
627        hitbox: &mut Hitbox,
628        window: &mut Window,
629        cx: &mut App,
630    ) {
631        self.driver.clone().listen(hitbox.clone(), window);
632        self.body.paint(window, cx);
633    }
634}