Skip to main content

lumen_dioxus/navigation/
pagination.rs

1//! `Pagination` and the page-window logic ported from `lumen-core/pagination`.
2
3use dioxus::prelude::*;
4
5use crate::class::compose;
6
7use super::util::{non_empty_or, resolve_safe_href};
8
9/// The most pages shown on each side of the current page, or pinned at each end.
10const MAX_WINDOW_RADIUS: u32 = 100;
11
12/// Which hidden run an ellipsis stands for.
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum PaginationEllipsis {
15    /// Pages hidden between the first pages and the current window.
16    Start,
17    /// Pages hidden between the current window and the last pages.
18    End,
19}
20
21impl PaginationEllipsis {
22    /// The `data-key` value: `ellipsis-start` or `ellipsis-end`.
23    pub fn as_str(self) -> &'static str {
24        match self {
25            Self::Start => "ellipsis-start",
26            Self::End => "ellipsis-end",
27        }
28    }
29}
30
31/// One rendered pagination entry: a page target or a collapsed run of hidden pages.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum PaginationItem {
35    /// A page link.
36    Page {
37        /// One-based page number.
38        page: u64,
39        /// Whether this is the current page.
40        current: bool,
41    },
42    /// A collapsed run of hidden pages.
43    Ellipsis(PaginationEllipsis),
44}
45
46/// Clamps a page number into `1..=total`, like `normalizeLumenPaginationPage`.
47pub fn pagination_page(current: u64, total: u64) -> u64 {
48    if total < 1 {
49        return 1;
50    }
51
52    current.clamp(1, total)
53}
54
55fn merge_ranges(mut candidates: Vec<(u64, u64)>) -> Vec<(u64, u64)> {
56    candidates.retain(|(start, end)| start <= end);
57    candidates.sort_by_key(|(start, _)| *start);
58
59    let mut ranges: Vec<(u64, u64)> = Vec::new();
60
61    for (start, end) in candidates {
62        match ranges.last_mut() {
63            // A gap of exactly one page is cheaper to show than to hide behind an ellipsis.
64            Some(previous) if start <= previous.1.saturating_add(2) => {
65                previous.1 = previous.1.max(end);
66            }
67            _ => ranges.push((start, end)),
68        }
69    }
70
71    ranges
72}
73
74/// The pagination entries to render: `boundaries` pages pinned at each end, `siblings` pages on
75/// each side of the current page, and an ellipsis for every hidden run longer than one page.
76///
77/// Ports `getLumenPaginationItems`: `current` is clamped into `1..=total`, `siblings` and
78/// `boundaries` are clamped to `0..=100`, and a `total` of 0 yields no items. Work is proportional
79/// to the visible window, so very large totals are safe.
80pub fn pagination_items(
81    current: u64,
82    total: u64,
83    siblings: u32,
84    boundaries: u32,
85) -> Vec<PaginationItem> {
86    if total == 0 {
87        return Vec::new();
88    }
89
90    let page = pagination_page(current, total);
91    let edge = u64::from(boundaries.min(MAX_WINDOW_RADIUS));
92    let radius = u64::from(siblings.min(MAX_WINDOW_RADIUS));
93    // With no boundary pages the end range is empty, as `[total + 1, total]` is in lumen-core.
94    let end_range = if edge == 0 {
95        (1, 0)
96    } else {
97        (total.saturating_sub(edge) + 1, total)
98    };
99    let ranges = merge_ranges(vec![
100        (1, edge.min(total)),
101        (
102            page.saturating_sub(radius).max(1),
103            page.saturating_add(radius).min(total),
104        ),
105        end_range,
106    ]);
107    let mut items = Vec::new();
108
109    for (index, (start, end)) in ranges.into_iter().enumerate() {
110        if index > 0 {
111            items.push(PaginationItem::Ellipsis(if start > page {
112                PaginationEllipsis::End
113            } else {
114                PaginationEllipsis::Start
115            }));
116        }
117
118        for value in start..=end {
119            items.push(PaginationItem::Page {
120                page: value,
121                current: value == page,
122            });
123        }
124    }
125
126    items
127}
128
129/// Localized names for a [`Pagination`]. Blank values fall back to the English defaults.
130#[derive(Clone, Debug, Default, PartialEq, Eq)]
131pub struct PaginationLabels {
132    /// Accessible name of the navigation landmark. Defaults to `Pagination`.
133    pub navigation: Option<String>,
134    /// Visible text of the next-page control. Defaults to `Next`.
135    pub next: Option<String>,
136    /// Visible text of the previous-page control. Defaults to `Previous`.
137    pub previous: Option<String>,
138    /// Accessible name of a page link; `{page}` is the page number. Defaults to `Page {page}`.
139    pub page: Option<String>,
140}
141
142struct ResolvedLabels {
143    navigation: String,
144    next: String,
145    previous: String,
146    page: String,
147}
148
149impl PaginationLabels {
150    fn resolve(&self) -> ResolvedLabels {
151        ResolvedLabels {
152            navigation: non_empty_or(self.navigation.as_deref(), "Pagination"),
153            next: non_empty_or(self.next.as_deref(), "Next"),
154            previous: non_empty_or(self.previous.as_deref(), "Previous"),
155            page: non_empty_or(self.page.as_deref(), "Page {page}"),
156        }
157    }
158}
159
160fn page_label(template: &str, page: u64) -> String {
161    let label = template.replace("{page}", &page.to_string());
162
163    if label.trim().is_empty() {
164        format!("Page {page}")
165    } else {
166        label
167    }
168}
169
170/// Props for [`Pagination`].
171#[derive(Props, Clone, PartialEq)]
172pub struct PaginationProps {
173    /// One-based current page. Set it with `total` to render the page list (data mode);
174    /// otherwise the component renders `children` (slot mode).
175    pub current: Option<u64>,
176    /// Total page count.
177    pub total: Option<u64>,
178    /// Builds each page destination. Unsafe results (executable schemes, credentials,
179    /// protocol-relative URLs) render as disabled entries. Defaults to `?page={page}`.
180    pub href: Option<Callback<u64, String>>,
181    /// Called with the chosen page. When set, activating a link calls it instead of following
182    /// `href`, for apps that keep the page in state or a router.
183    pub on_page_change: Option<EventHandler<u64>>,
184    /// Pages shown on each side of the current page. Defaults to 1.
185    #[props(default = 1)]
186    pub siblings: u32,
187    /// Pages pinned at each end. Defaults to 1.
188    #[props(default = 1)]
189    pub boundaries: u32,
190    /// Localized names for the landmark, steps, and page links.
191    #[props(default)]
192    pub labels: PaginationLabels,
193    /// Accessible name of the landmark. Overrides `labels.navigation`.
194    #[props(into)]
195    pub aria_label: Option<String>,
196    /// Extra classes appended after the Lumen class.
197    #[props(into)]
198    pub class: Option<String>,
199    /// Any other `<nav>` or global attribute.
200    #[props(extends = GlobalAttributes, extends = nav)]
201    pub attributes: Vec<Attribute>,
202    /// Slot-mode content, used when `current` or `total` is unset.
203    pub children: Element,
204}
205
206fn page_href(href: Option<Callback<u64, String>>, page: u64) -> Option<String> {
207    let value = href.map_or_else(|| format!("?page={page}"), |builder| builder.call(page));
208
209    resolve_safe_href(&value)
210}
211
212/// Page navigation for paged content.
213///
214/// In data mode it renders previous and next steps, boundary pages, a window around the current
215/// page, and ellipses for hidden runs, with the same markup as lumen-react.
216#[component]
217pub fn Pagination(props: PaginationProps) -> Element {
218    let class = compose([Some("ui-pagination"), props.class.as_deref()]);
219
220    let (Some(current), Some(total)) = (props.current, props.total) else {
221        return rsx! {
222            nav {
223                aria_label: props.aria_label.unwrap_or_else(|| "Pagination".to_string()),
224                class,
225                ..props.attributes,
226                {props.children}
227            }
228        };
229    };
230
231    let labels = props.labels.resolve();
232    let current = pagination_page(current, total);
233    let items = pagination_items(current, total, props.siblings, props.boundaries);
234    let previous = (current > 1).then(|| current - 1);
235    let next = (current < total).then(|| current + 1);
236    let href = props.href;
237    let on_page_change = props.on_page_change;
238    let aria_label = props.aria_label.unwrap_or(labels.navigation);
239    let page_template = labels.page;
240
241    let step = move |page: Option<u64>, label: String, rel: &'static str| {
242        let destination = page.and_then(|page| page_href(href, page));
243        let data_step = if rel == "prev" { "previous" } else { "next" };
244
245        rsx! {
246            li { class: "ui-pagination__item",
247                match (page, destination) {
248                    (Some(page), Some(destination)) => rsx! {
249                        a {
250                            class: "ui-pagination__link ui-pagination__step",
251                            "data-step": data_step,
252                            href: destination,
253                            rel,
254                            onclick: move |event: MouseEvent| {
255                                if let Some(handler) = on_page_change {
256                                    event.prevent_default();
257                                    handler.call(page);
258                                }
259                            },
260                            "{label}"
261                        }
262                    },
263                    _ => rsx! {
264                        span {
265                            aria_disabled: "true",
266                            class: "ui-pagination__link ui-pagination__step",
267                            "data-step": data_step,
268                            "{label}"
269                        }
270                    },
271                }
272            }
273        }
274    };
275
276    rsx! {
277        nav {
278            aria_label,
279            class,
280            "data-ui-pagination-mode": "data",
281            ..props.attributes,
282            ul { class: "ui-pagination__list", role: "list",
283                {step(previous, labels.previous, "prev")}
284                for item in items {
285                    match item {
286                        PaginationItem::Ellipsis(ellipsis) => rsx! {
287                            li {
288                                key: "{ellipsis.as_str()}",
289                                aria_hidden: "true",
290                                class: "ui-pagination__item",
291                                "data-key": ellipsis.as_str(),
292                                span { class: "ui-pagination__ellipsis", "…" }
293                            }
294                        },
295                        PaginationItem::Page { page, current } => {
296                            let label = page_label(&page_template, page);
297                            let aria_current = current.then_some("page");
298
299                            rsx! {
300                                li { key: "{page}", class: "ui-pagination__item",
301                                    if let Some(destination) = page_href(href, page) {
302                                        a {
303                                            aria_current,
304                                            aria_label: label,
305                                            class: "ui-pagination__link",
306                                            href: destination,
307                                            onclick: move |event: MouseEvent| {
308                                                if let Some(handler) = on_page_change {
309                                                    event.prevent_default();
310                                                    handler.call(page);
311                                                }
312                                            },
313                                            "{page}"
314                                        }
315                                    } else {
316                                        span {
317                                            aria_current,
318                                            aria_disabled: (!current).then_some("true"),
319                                            class: "ui-pagination__link",
320                                            span { class: "ui-sr-only", "{label}" }
321                                            span { aria_hidden: "true", "{page}" }
322                                        }
323                                    }
324                                }
325                            }
326                        }
327                    }
328                }
329                {step(next, labels.next, "next")}
330            }
331        }
332    }
333}
334
335#[cfg(test)]
336mod tests {
337    use super::{
338        PaginationEllipsis, PaginationItem, page_label, pagination_items, pagination_page,
339    };
340
341    fn render(items: &[PaginationItem]) -> String {
342        items
343            .iter()
344            .map(|item| match item {
345                PaginationItem::Page {
346                    page,
347                    current: true,
348                } => format!("[{page}]"),
349                PaginationItem::Page { page, .. } => page.to_string(),
350                PaginationItem::Ellipsis(PaginationEllipsis::Start) => "<".to_string(),
351                PaginationItem::Ellipsis(PaginationEllipsis::End) => ">".to_string(),
352            })
353            .collect::<Vec<_>>()
354            .join(" ")
355    }
356
357    #[test]
358    fn windows_match_lumen_core() {
359        assert_eq!(render(&pagination_items(5, 10, 1, 1)), "1 < 4 [5] 6 > 10");
360        assert_eq!(render(&pagination_items(1, 10, 1, 1)), "[1] 2 > 10");
361        assert_eq!(render(&pagination_items(10, 10, 1, 1)), "1 < 9 [10]");
362        // A one-page gap is shown instead of hidden.
363        assert_eq!(render(&pagination_items(4, 10, 1, 1)), "1 2 3 [4] 5 > 10");
364        assert_eq!(render(&pagination_items(3, 5, 1, 1)), "1 2 [3] 4 5");
365        assert_eq!(render(&pagination_items(5, 10, 0, 0)), "[5]");
366        assert_eq!(
367            render(&pagination_items(5, 10, 1, 2)),
368            "1 2 3 4 [5] 6 > 9 10"
369        );
370        assert_eq!(
371            render(&pagination_items(6, 12, 1, 2)),
372            "1 2 < 5 [6] 7 > 11 12"
373        );
374        assert_eq!(render(&pagination_items(1, 1, 1, 1)), "[1]");
375    }
376
377    #[test]
378    fn inputs_clamp() {
379        assert_eq!(pagination_items(1, 0, 1, 1), Vec::new());
380        assert_eq!(render(&pagination_items(0, 3, 1, 1)), "[1] 2 3");
381        assert_eq!(render(&pagination_items(99, 3, 1, 1)), "1 2 [3]");
382        assert_eq!(pagination_page(0, 0), 1);
383        assert_eq!(pagination_page(7, 4), 4);
384    }
385
386    #[test]
387    fn huge_totals_stay_proportional_to_the_window() {
388        let items = pagination_items(u64::MAX / 2, u64::MAX, 2, 1);
389        assert_eq!(items.len(), 9);
390        let items = pagination_items(1, u64::MAX, u32::MAX, u32::MAX);
391        assert!(items.len() <= 203);
392    }
393
394    #[test]
395    fn page_labels_fill_the_template() {
396        assert_eq!(page_label("Page {page}", 3), "Page 3");
397        assert_eq!(page_label("Página {page} de {page}", 2), "Página 2 de 2");
398    }
399}