Skip to main content

gpui_material_components/
pull_to_refresh.rs

1mod driver;
2mod state;
3
4use std::rc::Rc;
5
6use gpui::{
7    AnyElement, App, ElementId, Entity, InteractiveElement, IntoElement, ParentElement, Pixels,
8    RenderOnce, ScrollHandle, SharedString, StatefulInteractiveElement, StyleRefinement, Styled,
9    Window, div, prelude::FluentBuilder, px,
10};
11use gpui_base::{StyledExt, TestSupportExt};
12use gpui_material_foundation::{current_material_strings, current_material_theme};
13use gpui_material_theme::Direction;
14
15use crate::{Button, ButtonVariant, LoadingIndicator};
16
17use driver::{Refresh, RefreshDriver, RefreshViewport};
18use state::{ScrollBinding, ViewportKey};
19
20pub use state::{PullToRefreshProgress, PullToRefreshState};
21
22const DEFAULT_DISTANCE: Pixels = px(80.);
23
24type Indicator = Box<dyn FnOnce(PullToRefreshProgress, &mut Window, &mut App) -> AnyElement>;
25
26/// A vertical viewport with an Expressive refresh indicator and accessible action.
27#[derive(IntoElement)]
28pub struct PullToRefresh {
29    id: ElementId,
30    state: Entity<PullToRefreshState>,
31    refreshing: bool,
32    enabled: bool,
33    refresh: Refresh,
34    label: Option<SharedString>,
35    threshold: Pixels,
36    indicator_distance: Pixels,
37    binding: Option<ScrollBinding>,
38    indicator: Option<Indicator>,
39    children: Vec<AnyElement>,
40    style: StyleRefinement,
41}
42
43impl PullToRefresh {
44    /// Creates a pull-to-refresh container bound to `state`, caller-owned `refreshing` status, and refresh callback.
45    pub fn new(
46        id: impl Into<ElementId>,
47        state: &Entity<PullToRefreshState>,
48        refreshing: bool,
49        on_refresh: impl Fn(&mut Window, &mut App) + 'static,
50    ) -> Self {
51        Self {
52            id: id.into(),
53            state: state.clone(),
54            refreshing,
55            enabled: true,
56            refresh: Rc::new(on_refresh),
57            label: None,
58            threshold: DEFAULT_DISTANCE,
59            indicator_distance: DEFAULT_DISTANCE,
60            binding: None,
61            indicator: None,
62            children: Vec::new(),
63            style: StyleRefinement::default(),
64        }
65    }
66
67    /// Enables or disables pull gestures and the accessible refresh action button. Defaults to `true`.
68    pub fn enabled(mut self, enabled: bool) -> Self {
69        self.enabled = enabled;
70        self
71    }
72
73    /// Sets the label used for both the accessible refresh button and default loading indicator.
74    /// Defaults to [`gpui_material_theme::MaterialStrings::refresh`] (`"Refresh"`).
75    pub fn refresh_label(mut self, label: impl Into<SharedString>) -> Self {
76        self.label = Some(label.into());
77        self
78    }
79
80    /// Sets the pull threshold in logical pixels. Invalid values use the default.
81    pub fn threshold(mut self, threshold: Pixels) -> Self {
82        if f32::from(threshold).is_finite() && threshold > px(0.) {
83            self.threshold = threshold;
84        }
85        self
86    }
87
88    /// Sets indicator travel at the threshold in logical pixels.
89    pub fn indicator_distance(mut self, distance: Pixels) -> Self {
90        if f32::from(distance).is_finite() && distance >= px(0.) {
91            self.indicator_distance = distance;
92        }
93        self
94    }
95
96    /// Wraps a caller-owned viewport that tracks this scroll handle.
97    pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
98        self.binding = Some(ScrollBinding::Handle(handle.clone()));
99        self
100    }
101
102    /// Wraps a caller-owned viewport using a positive distance from its top edge.
103    pub fn scroll_position(mut self, position: impl Fn(&Window, &App) -> Pixels + 'static) -> Self {
104        self.binding = Some(ScrollBinding::Position(Rc::new(position)));
105        self
106    }
107
108    /// Replaces the loading indicator with decorative content using the same reveal.
109    pub fn indicator<E: IntoElement>(
110        mut self,
111        indicator: impl FnOnce(PullToRefreshProgress, &mut Window, &mut App) -> E + 'static,
112    ) -> Self {
113        self.indicator = Some(Box::new(move |progress, window, cx| {
114            indicator(progress, window, cx).into_any_element()
115        }));
116        self
117    }
118}
119
120impl Styled for PullToRefresh {
121    fn style(&mut self) -> &mut StyleRefinement {
122        &mut self.style
123    }
124}
125
126impl ParentElement for PullToRefresh {
127    fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
128        self.children.extend(children);
129    }
130}
131
132impl RenderOnce for PullToRefresh {
133    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
134        let viewport = ViewportKey {
135            window: window.window_handle().window_id(),
136            id: self.id.clone(),
137        };
138        let (progress, can_request, scroll) = self.state.update(cx, |state, cx| {
139            state.configure(&viewport, self.refreshing, self.enabled, window, cx);
140            (
141                PullToRefreshProgress {
142                    distance_fraction: state.fraction,
143                    offset: (self.indicator_distance * state.fraction.min(2.))
144                        .min(window.viewport_size().height),
145                    refreshing: state.refreshing,
146                    refresh_pending: state.pending,
147                    animating: state.is_animating(),
148                },
149                state.can_request(),
150                state.scroll_handle(),
151            )
152        });
153        let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
154        let owned = self.binding.is_none();
155        let mut body = div()
156            .id("refresh-scroll")
157            .test_support()
158            .flex()
159            .flex_col()
160            .size_full()
161            .min_h_0()
162            .children(self.children);
163        if owned {
164            body = body.overflow_y_scroll().track_scroll(&scroll);
165        }
166        let driver = RefreshDriver {
167            state: self.state.downgrade(),
168            viewport,
169            refresh: self.refresh,
170            threshold: self.threshold,
171            binding: self.binding.unwrap_or(ScrollBinding::Handle(scroll)),
172        };
173        let command = driver.clone();
174        let label = self.label.unwrap_or_else(|| {
175            SharedString::from(current_material_strings(window, cx).refresh.clone())
176        });
177        let indicator = (progress.distance_fraction > 0.).then(|| {
178            let element = match self.indicator {
179                Some(indicator) => indicator(progress, window, cx),
180                None => {
181                    let loading =
182                        LoadingIndicator::new("refresh-progress", label.clone()).contained(true);
183                    if progress.refreshing {
184                        loading.into_any_element()
185                    } else {
186                        loading.value(progress.distance_fraction).into_any_element()
187                    }
188                }
189            };
190            div()
191                .absolute()
192                .left_0()
193                .right_0()
194                .top(progress.offset - px(48.))
195                .flex()
196                .justify_center()
197                .child(element)
198        });
199        div()
200            .id(self.id)
201            .flex()
202            .flex_col()
203            .size_full()
204            .min_h_0()
205            .refine_style(&self.style)
206            .child(
207                div()
208                    .flex()
209                    .flex_none()
210                    .when(rtl, Styled::justify_start)
211                    .when(!rtl, Styled::justify_end)
212                    .child(
213                        Button::new("refresh-action", label)
214                            .variant(ButtonVariant::Text)
215                            .disabled(!can_request)
216                            .on_activate(move |window, cx| command.request(window, cx)),
217                    ),
218            )
219            .child(
220                div()
221                    .flex_1()
222                    .min_h_0()
223                    .relative()
224                    .overflow_hidden()
225                    .child(RefreshViewport {
226                        driver,
227                        body: body.into_any_element(),
228                    })
229                    .children(indicator),
230            )
231    }
232}