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