Skip to main content

fc_ui/capabilities/scroll/
infinite_scroll.rs

1use gpui::{prelude::FluentBuilder as _, *};
2use std::rc::Rc;
3use std::sync::atomic::{AtomicUsize, Ordering};
4
5use crate::capabilities::foundation::theme::use_theme;
6use crate::capabilities::primitives::spinner::Spinner;
7
8static INFINITE_SCROLL_COUNTER: AtomicUsize = AtomicUsize::new(0);
9
10#[derive(Clone, Debug, PartialEq)]
11pub enum LoadingState {
12    Idle,
13    Loading,
14    Loaded,
15    Error(SharedString),
16    EndReached,
17}
18
19pub struct InfiniteScrollState {
20    loading_state: LoadingState,
21    page: usize,
22    has_more: bool,
23    scroll_handle: ScrollHandle,
24}
25
26impl InfiniteScrollState {
27    pub fn new(cx: &mut App) -> Entity<Self> {
28        cx.new(|_| Self {
29            loading_state: LoadingState::Idle,
30            page: 0,
31            has_more: true,
32            scroll_handle: ScrollHandle::new(),
33        })
34    }
35
36    pub fn loading_state(&self) -> &LoadingState {
37        &self.loading_state
38    }
39
40    pub fn page(&self) -> usize {
41        self.page
42    }
43
44    pub fn set_loading(&mut self) {
45        self.loading_state = LoadingState::Loading;
46    }
47
48    pub fn set_loaded(&mut self) {
49        self.page += 1;
50        self.has_more = true;
51        self.loading_state = LoadingState::Idle;
52    }
53
54    pub fn set_error(&mut self, msg: impl Into<SharedString>) {
55        self.loading_state = LoadingState::Error(msg.into());
56    }
57
58    pub fn set_end_reached(&mut self) {
59        self.has_more = false;
60        self.loading_state = LoadingState::EndReached;
61    }
62
63    pub fn reset(&mut self) {
64        self.page = 0;
65        self.has_more = true;
66        self.loading_state = LoadingState::Idle;
67    }
68
69    pub fn scroll_handle(&self) -> &ScrollHandle {
70        &self.scroll_handle
71    }
72}
73
74#[derive(IntoElement)]
75pub struct InfiniteScroll {
76    id: ElementId,
77    state: Entity<InfiniteScrollState>,
78    threshold: f32,
79    on_load_more: Option<Rc<dyn Fn(usize, &mut Window, &mut App)>>,
80    loading_indicator: Option<AnyElement>,
81    end_indicator: Option<AnyElement>,
82    children: Vec<AnyElement>,
83    style: StyleRefinement,
84}
85
86impl InfiniteScroll {
87    #[track_caller]
88    pub fn new(state: Entity<InfiniteScrollState>) -> Self {
89        let location = std::panic::Location::caller();
90        Self {
91            id: ElementId::Name(
92                format!(
93                    "infinite-scroll:{}:{}:{}:{}",
94                    location.file(),
95                    location.line(),
96                    location.column(),
97                    INFINITE_SCROLL_COUNTER.fetch_add(1, Ordering::Relaxed)
98                )
99                .into(),
100            ),
101            state,
102            threshold: 0.8,
103            on_load_more: None,
104            loading_indicator: None,
105            end_indicator: None,
106            children: Vec::new(),
107            style: StyleRefinement::default(),
108        }
109    }
110
111    pub fn threshold(mut self, threshold: f32) -> Self {
112        self.threshold = threshold.clamp(0.0, 1.0);
113        self
114    }
115
116    pub fn on_load_more(
117        mut self,
118        callback: impl Fn(usize, &mut Window, &mut App) + 'static,
119    ) -> Self {
120        self.on_load_more = Some(Rc::new(callback));
121        self
122    }
123
124    pub fn loading_indicator(mut self, indicator: impl IntoElement) -> Self {
125        self.loading_indicator = Some(indicator.into_any_element());
126        self
127    }
128
129    pub fn end_indicator(mut self, indicator: impl IntoElement) -> Self {
130        self.end_indicator = Some(indicator.into_any_element());
131        self
132    }
133}
134
135impl ParentElement for InfiniteScroll {
136    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
137        self.children.extend(elements);
138    }
139}
140
141impl Styled for InfiniteScroll {
142    fn style(&mut self) -> &mut StyleRefinement {
143        &mut self.style
144    }
145}
146
147impl RenderOnce for InfiniteScroll {
148    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
149        let theme = use_theme(cx);
150        let user_style = self.style;
151        let (loading_state, scroll_handle) = {
152            let s = self.state.read(cx);
153            (s.loading_state.clone(), s.scroll_handle.clone())
154        };
155
156        let mut container = div()
157            .id(self.id)
158            .overflow_y_scroll()
159            .track_scroll(&scroll_handle)
160            .flex()
161            .flex_col()
162            .size_full();
163
164        if let Some(callback) = self.on_load_more {
165            let state_c = self.state.clone();
166            let threshold = self.threshold;
167            container = container.on_scroll_wheel(move |_event, window, cx| {
168                let (should_load, page) = {
169                    let s = state_c.read(cx);
170                    if s.loading_state != LoadingState::Idle || !s.has_more {
171                        return;
172                    }
173                    let handle = &s.scroll_handle;
174                    let offset_y = (-handle.offset().y).max(px(0.0));
175                    let max_y = handle.max_offset().height;
176                    if max_y > px(0.0) && offset_y >= max_y * threshold {
177                        (true, s.page)
178                    } else {
179                        return;
180                    }
181                };
182                if should_load {
183                    callback(page, window, cx);
184                }
185            });
186        }
187
188        container = container.children(self.children);
189
190        match loading_state {
191            LoadingState::Loading => {
192                let indicator = self.loading_indicator.unwrap_or_else(|| {
193                    div()
194                        .flex()
195                        .justify_center()
196                        .py(px(16.0))
197                        .child(Spinner::new())
198                        .into_any_element()
199                });
200                container = container.child(indicator);
201            }
202            LoadingState::EndReached => {
203                let indicator = self.end_indicator.unwrap_or_else(|| {
204                    div()
205                        .flex()
206                        .justify_center()
207                        .py(px(16.0))
208                        .child(
209                            div()
210                                .text_size(px(14.0))
211                                .text_color(theme.tokens.muted_foreground)
212                                .font_family(theme.tokens.font_family.clone())
213                                .child("No more items"),
214                        )
215                        .into_any_element()
216                });
217                container = container.child(indicator);
218            }
219            LoadingState::Error(ref msg) => {
220                container = container.child(
221                    div().flex().justify_center().py(px(16.0)).child(
222                        div()
223                            .text_size(px(14.0))
224                            .text_color(theme.tokens.destructive)
225                            .font_family(theme.tokens.font_family.clone())
226                            .child(msg.clone()),
227                    ),
228                );
229            }
230            _ => {}
231        }
232
233        container.map(|mut this| {
234            this.style().refine(&user_style);
235            this
236        })
237    }
238}