Skip to main content

gpui_component/
pagination.rs

1use std::{ops::Range, rc::Rc};
2
3use gpui::{
4    App, ElementId, IntoElement, ParentElement, RenderOnce, SharedString, StyleRefinement, Styled,
5    Window, prelude::FluentBuilder, px,
6};
7use rust_i18n::t;
8
9use gpui_base::{
10    LayoutDirection, LogicalStyledExt as _, Pagination as BasePagination,
11    PaginationItem as PageItem, PaginationState,
12};
13
14use crate::{
15    Disableable, Icon, Sizable, Size, StyledExt,
16    button::{Button, ButtonVariants},
17    h_flex,
18    icon::IconName,
19    menu::{DropdownMenu as _, PopupMenuItem},
20};
21
22/// The most pages an ellipsis menu lists.
23///
24/// The menu renders every item on each frame it is open, so listing every
25/// hidden page of a large set makes each hover repaint thousands of rows.
26const MAX_ELLIPSIS_MENU_PAGES: usize = 100;
27
28/// The pages an ellipsis menu lists: the hidden pages closest to the current
29/// page, at most [`MAX_ELLIPSIS_MENU_PAGES`] of them.
30fn ellipsis_menu_pages(hidden: Range<usize>, current_page: usize) -> Range<usize> {
31    if hidden.len() <= MAX_ELLIPSIS_MENU_PAGES {
32        hidden
33    } else if hidden.start > current_page {
34        hidden.start..hidden.start + MAX_ELLIPSIS_MENU_PAGES
35    } else {
36        hidden.end - MAX_ELLIPSIS_MENU_PAGES..hidden.end
37    }
38}
39
40/// Pagination with page navigation, next and previous links.
41#[derive(IntoElement)]
42pub struct Pagination {
43    id: ElementId,
44    style: StyleRefinement,
45    size: Size,
46    current_page: usize,
47    total_pages: usize,
48    disabled: bool,
49    compact: bool,
50    visible_pages: usize,
51    on_click: Option<Rc<dyn Fn(&usize, &mut Window, &mut App)>>,
52}
53
54impl Pagination {
55    /// Create a new Pagination component with the given ID.
56    pub fn new(id: impl Into<ElementId>) -> Self {
57        Self {
58            id: id.into(),
59            style: StyleRefinement::default(),
60            size: Size::default(),
61            current_page: 1,
62            total_pages: 1,
63            visible_pages: 5,
64            disabled: false,
65            compact: false,
66            on_click: None,
67        }
68    }
69
70    /// Set the current page number (1-based).
71    ///
72    /// The value will be clamped between 1 and total_pages when total_pages is set.
73    pub fn current_page(mut self, page: usize) -> Self {
74        self.current_page = page.max(1);
75        self
76    }
77
78    /// Set the total number of pages.
79    pub fn total_pages(mut self, pages: usize) -> Self {
80        self.total_pages = pages.max(1);
81        if self.current_page > self.total_pages {
82            self.current_page = self.total_pages;
83        }
84        self
85    }
86
87    /// Set the handler for page change (when clicking on page numbers, prev, or next).
88    ///
89    /// This handler receives the new page number to navigate to.
90    ///
91    /// # Examples
92    ///
93    /// ```ignore
94    /// Pagination::new("my-pagination")
95    ///     .current_page(current_page)
96    ///     .total_pages(total_pages)
97    ///     .on_click(|page, _, cx| {
98    ///         // Handle page change
99    ///     })
100    /// ```
101    pub fn on_click(mut self, handler: impl Fn(&usize, &mut Window, &mut App) + 'static) -> Self {
102        self.on_click = Some(Rc::new(handler));
103        self
104    }
105
106    /// Set to display as compact style.
107    ///
108    /// If true, only the prev, next buttons with only icon.
109    pub fn compact(mut self) -> Self {
110        self.compact = true;
111        self
112    }
113
114    /// Set viewable maximum number of page buttons, default
115    pub fn visible_pages(mut self, max: usize) -> Self {
116        self.visible_pages = max;
117        self
118    }
119
120    fn render_nav_button(&self, state: &PaginationState, is_prev: bool, rtl: bool) -> Button {
121        // Previous points back toward the start edge: the right in RTL.
122        let (id, label) = if is_prev {
123            ("prev", t!("Pagination.previous"))
124        } else {
125            ("next", t!("Pagination.next"))
126        };
127        let icon = if is_prev != rtl {
128            IconName::ChevronLeft
129        } else {
130            IconName::ChevronRight
131        };
132
133        let target_page = if is_prev {
134            state.previous_page()
135        } else {
136            state.next_page()
137        };
138
139        Button::new(id)
140            .ghost()
141            .compact()
142            .with_size(self.size)
143            .disabled(target_page.is_none())
144            .tooltip(label.clone())
145            .when(self.compact, |this| this.icon(icon.clone()))
146            .when(!self.compact, |this| {
147                this.child(
148                    h_flex()
149                        .w_full()
150                        .gap_2()
151                        .flex_nowrap()
152                        .when(is_prev != rtl, |this| this.flex_row_reverse())
153                        .child(SharedString::from(label))
154                        .child(Icon::new(icon)),
155                )
156            })
157            .when_some(
158                target_page.filter(|_| state.has_on_change()),
159                |this, target_page| {
160                    let state = state.clone();
161                    this.on_click(move |_, window, cx| {
162                        state.request_page(target_page, window, cx);
163                    })
164                },
165            )
166    }
167}
168
169impl Disableable for Pagination {
170    fn disabled(mut self, disabled: bool) -> Self {
171        self.disabled = disabled;
172        self
173    }
174}
175
176impl Sizable for Pagination {
177    fn with_size(mut self, size: impl Into<Size>) -> Self {
178        self.size = size.into();
179        self
180    }
181}
182
183impl Styled for Pagination {
184    fn style(&mut self) -> &mut StyleRefinement {
185        &mut self.style
186    }
187}
188
189impl RenderOnce for Pagination {
190    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
191        let rtl = LayoutDirection::global(cx).is_rtl();
192        let mut state = PaginationState::new(self.current_page, self.total_pages)
193            .visible_pages(self.visible_pages)
194            .disabled(self.disabled);
195        if let Some(on_click) = self.on_click.clone() {
196            state = state.on_change(move |page, window, cx| on_click(&page, window, cx));
197        }
198        let page_numbers = (!self.compact).then(|| state.items()).unwrap_or_default();
199
200        let current_page = state.current_page();
201        let is_disabled = self.disabled;
202        let item_state = state.clone();
203
204        BasePagination::new(self.id.clone(), state.clone())
205            .h_flex()
206            .flex_row_dir(cx)
207            .px_2()
208            .py_2()
209            .gap_1()
210            .items_center()
211            .refine_style(&self.style)
212            .child(self.render_nav_button(&state, true, rtl))
213            .children({
214                page_numbers.into_iter().map(|item| match item {
215                    PageItem::Page(page) => {
216                        let is_selected = page == current_page;
217
218                        Button::new(page)
219                            .with_size(self.size)
220                            .map(|this| {
221                                if is_selected {
222                                    this.outline()
223                                } else {
224                                    this.ghost()
225                                }
226                            })
227                            .label(page.to_string())
228                            .compact()
229                            .disabled(is_disabled)
230                            .when(!is_selected && item_state.has_on_change(), |this| {
231                                let state = item_state.clone();
232                                this.on_click(move |_, window, cx| {
233                                    state.request_page(page, window, cx);
234                                })
235                            })
236                            .into_any_element()
237                    }
238                    PageItem::Ellipsis(range) => Button::new(SharedString::from(format!(
239                        "ellipsis-{}-{}",
240                        range.start, range.end
241                    )))
242                    .ghost()
243                    .with_size(self.size)
244                    .compact()
245                    .disabled(self.disabled)
246                    .icon(IconName::Ellipsis)
247                    .dropdown_menu({
248                        let state = item_state.clone();
249                        move |mut menu, _, _| {
250                            for page in ellipsis_menu_pages(range.clone(), current_page) {
251                                menu = menu.item(
252                                    PopupMenuItem::new(format!("{}", page))
253                                        .checked(page == current_page)
254                                        .on_click({
255                                            let state = state.clone();
256                                            move |_, window, cx| {
257                                                state.request_page(page, window, cx);
258                                            }
259                                        }),
260                                )
261                            }
262
263                            menu.min_w(px(55.)).max_h(px(240.)).scrollable(true)
264                        }
265                    })
266                    .into_any_element(),
267                })
268            })
269            .child(self.render_nav_button(&state, false, rtl))
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use super::*;
276
277    #[test]
278    fn test_ellipsis_menu_pages() {
279        // Short gaps list every hidden page.
280        assert_eq!(ellipsis_menu_pages(2..8, 1), 2..8);
281        assert_eq!(ellipsis_menu_pages(2..8, 9), 2..8);
282
283        // Long gaps keep the pages next to the current page.
284        assert_eq!(ellipsis_menu_pages(4..10_000, 1), 4..104);
285        assert_eq!(ellipsis_menu_pages(2..9_997, 10_000), 9_897..9_997);
286        assert_eq!(ellipsis_menu_pages(5_003..10_000, 5_000), 5_003..5_103);
287        assert_eq!(ellipsis_menu_pages(2..4_998, 5_000), 4_898..4_998);
288    }
289}