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