gpui_material_components/
pull_to_refresh.rs1mod 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_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#[derive(IntoElement)]
28pub struct PullToRefresh {
29 id: ElementId,
30 state: Entity<PullToRefreshState>,
31 refreshing: bool,
32 enabled: bool,
33 refresh: Refresh,
34 label: 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 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: "Refresh".into(),
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 pub fn enabled(mut self, enabled: bool) -> Self {
69 self.enabled = enabled;
70 self
71 }
72
73 pub fn refresh_label(mut self, label: impl Into<SharedString>) -> Self {
75 self.label = label.into();
76 self
77 }
78
79 pub fn threshold(mut self, threshold: Pixels) -> Self {
81 if f32::from(threshold).is_finite() && threshold > px(0.) {
82 self.threshold = threshold;
83 }
84 self
85 }
86
87 pub fn indicator_distance(mut self, distance: Pixels) -> Self {
89 if f32::from(distance).is_finite() && distance >= px(0.) {
90 self.indicator_distance = distance;
91 }
92 self
93 }
94
95 pub fn track_scroll(mut self, handle: &ScrollHandle) -> Self {
97 self.binding = Some(ScrollBinding::Handle(handle.clone()));
98 self
99 }
100
101 pub fn scroll_position(mut self, position: impl Fn(&Window, &App) -> Pixels + 'static) -> Self {
103 self.binding = Some(ScrollBinding::Position(Rc::new(position)));
104 self
105 }
106
107 pub fn indicator<E: IntoElement>(
109 mut self,
110 indicator: impl FnOnce(PullToRefreshProgress, &mut Window, &mut App) -> E + 'static,
111 ) -> Self {
112 self.indicator = Some(Box::new(move |progress, window, cx| {
113 indicator(progress, window, cx).into_any_element()
114 }));
115 self
116 }
117}
118
119impl Styled for PullToRefresh {
120 fn style(&mut self) -> &mut StyleRefinement {
121 &mut self.style
122 }
123}
124
125impl ParentElement for PullToRefresh {
126 fn extend(&mut self, children: impl IntoIterator<Item = AnyElement>) {
127 self.children.extend(children);
128 }
129}
130
131impl RenderOnce for PullToRefresh {
132 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
133 let viewport = ViewportKey {
134 window: window.window_handle().window_id(),
135 id: self.id.clone(),
136 };
137 let (progress, can_request, scroll) = self.state.update(cx, |state, cx| {
138 state.configure(&viewport, self.refreshing, self.enabled, window, cx);
139 (
140 PullToRefreshProgress {
141 distance_fraction: state.fraction,
142 offset: (self.indicator_distance * state.fraction.min(2.))
143 .min(window.viewport_size().height),
144 refreshing: state.refreshing,
145 refresh_pending: state.pending,
146 animating: state.is_animating(),
147 },
148 state.can_request(),
149 state.scroll_handle(),
150 )
151 });
152 let rtl = current_material_theme(window, cx).layout.direction == Direction::Rtl;
153 let owned = self.binding.is_none();
154 let mut body = div()
155 .id("refresh-scroll")
156 .test_support()
157 .flex()
158 .flex_col()
159 .size_full()
160 .min_h_0()
161 .children(self.children);
162 if owned {
163 body = body.overflow_y_scroll().track_scroll(&scroll);
164 }
165 let driver = RefreshDriver {
166 state: self.state.downgrade(),
167 viewport,
168 refresh: self.refresh,
169 threshold: self.threshold,
170 binding: self.binding.unwrap_or(ScrollBinding::Handle(scroll)),
171 };
172 let command = driver.clone();
173 let indicator = (progress.distance_fraction > 0.).then(|| {
174 let element = match self.indicator {
175 Some(indicator) => indicator(progress, window, cx),
176 None => {
177 let loading = LoadingIndicator::new("refresh-progress", self.label.clone())
178 .contained(true);
179 if progress.refreshing {
180 loading.into_any_element()
181 } else {
182 loading.value(progress.distance_fraction).into_any_element()
183 }
184 }
185 };
186 div()
187 .absolute()
188 .left_0()
189 .right_0()
190 .top(progress.offset - px(48.))
191 .flex()
192 .justify_center()
193 .child(element)
194 });
195 div()
196 .id(self.id)
197 .flex()
198 .flex_col()
199 .size_full()
200 .min_h_0()
201 .refine_style(&self.style)
202 .child(
203 div()
204 .flex()
205 .flex_none()
206 .when(rtl, Styled::justify_start)
207 .when(!rtl, Styled::justify_end)
208 .child(
209 Button::new("refresh-action", self.label)
210 .variant(ButtonVariant::Text)
211 .disabled(!can_request)
212 .on_activate(move |window, cx| command.request(window, cx)),
213 ),
214 )
215 .child(
216 div()
217 .flex_1()
218 .min_h_0()
219 .relative()
220 .overflow_hidden()
221 .child(RefreshViewport {
222 driver,
223 body: body.into_any_element(),
224 })
225 .children(indicator),
226 )
227 }
228}