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