lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `Pagination` and the page-window logic ported from `lumen-core/pagination`.

use dioxus::prelude::*;

use crate::class::compose;

use super::util::{non_empty_or, resolve_safe_href};

/// The most pages shown on each side of the current page, or pinned at each end.
const MAX_WINDOW_RADIUS: u32 = 100;

/// Which hidden run an ellipsis stands for.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PaginationEllipsis {
    /// Pages hidden between the first pages and the current window.
    Start,
    /// Pages hidden between the current window and the last pages.
    End,
}

impl PaginationEllipsis {
    /// The `data-key` value: `ellipsis-start` or `ellipsis-end`.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Start => "ellipsis-start",
            Self::End => "ellipsis-end",
        }
    }
}

/// One rendered pagination entry: a page target or a collapsed run of hidden pages.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PaginationItem {
    /// A page link.
    Page {
        /// One-based page number.
        page: u64,
        /// Whether this is the current page.
        current: bool,
    },
    /// A collapsed run of hidden pages.
    Ellipsis(PaginationEllipsis),
}

/// Clamps a page number into `1..=total`, like `normalizeLumenPaginationPage`.
pub fn pagination_page(current: u64, total: u64) -> u64 {
    if total < 1 {
        return 1;
    }

    current.clamp(1, total)
}

fn merge_ranges(mut candidates: Vec<(u64, u64)>) -> Vec<(u64, u64)> {
    candidates.retain(|(start, end)| start <= end);
    candidates.sort_by_key(|(start, _)| *start);

    let mut ranges: Vec<(u64, u64)> = Vec::new();

    for (start, end) in candidates {
        match ranges.last_mut() {
            // A gap of exactly one page is cheaper to show than to hide behind an ellipsis.
            Some(previous) if start <= previous.1.saturating_add(2) => {
                previous.1 = previous.1.max(end);
            }
            _ => ranges.push((start, end)),
        }
    }

    ranges
}

/// The pagination entries to render: `boundaries` pages pinned at each end, `siblings` pages on
/// each side of the current page, and an ellipsis for every hidden run longer than one page.
///
/// Ports `getLumenPaginationItems`: `current` is clamped into `1..=total`, `siblings` and
/// `boundaries` are clamped to `0..=100`, and a `total` of 0 yields no items. Work is proportional
/// to the visible window, so very large totals are safe.
pub fn pagination_items(
    current: u64,
    total: u64,
    siblings: u32,
    boundaries: u32,
) -> Vec<PaginationItem> {
    if total == 0 {
        return Vec::new();
    }

    let page = pagination_page(current, total);
    let edge = u64::from(boundaries.min(MAX_WINDOW_RADIUS));
    let radius = u64::from(siblings.min(MAX_WINDOW_RADIUS));
    // With no boundary pages the end range is empty, as `[total + 1, total]` is in lumen-core.
    let end_range = if edge == 0 {
        (1, 0)
    } else {
        (total.saturating_sub(edge) + 1, total)
    };
    let ranges = merge_ranges(vec![
        (1, edge.min(total)),
        (
            page.saturating_sub(radius).max(1),
            page.saturating_add(radius).min(total),
        ),
        end_range,
    ]);
    let mut items = Vec::new();

    for (index, (start, end)) in ranges.into_iter().enumerate() {
        if index > 0 {
            items.push(PaginationItem::Ellipsis(if start > page {
                PaginationEllipsis::End
            } else {
                PaginationEllipsis::Start
            }));
        }

        for value in start..=end {
            items.push(PaginationItem::Page {
                page: value,
                current: value == page,
            });
        }
    }

    items
}

/// Localized names for a [`Pagination`]. Blank values fall back to the English defaults.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PaginationLabels {
    /// Accessible name of the navigation landmark. Defaults to `Pagination`.
    pub navigation: Option<String>,
    /// Visible text of the next-page control. Defaults to `Next`.
    pub next: Option<String>,
    /// Visible text of the previous-page control. Defaults to `Previous`.
    pub previous: Option<String>,
    /// Accessible name of a page link; `{page}` is the page number. Defaults to `Page {page}`.
    pub page: Option<String>,
}

struct ResolvedLabels {
    navigation: String,
    next: String,
    previous: String,
    page: String,
}

impl PaginationLabels {
    fn resolve(&self) -> ResolvedLabels {
        ResolvedLabels {
            navigation: non_empty_or(self.navigation.as_deref(), "Pagination"),
            next: non_empty_or(self.next.as_deref(), "Next"),
            previous: non_empty_or(self.previous.as_deref(), "Previous"),
            page: non_empty_or(self.page.as_deref(), "Page {page}"),
        }
    }
}

fn page_label(template: &str, page: u64) -> String {
    let label = template.replace("{page}", &page.to_string());

    if label.trim().is_empty() {
        format!("Page {page}")
    } else {
        label
    }
}

/// Props for [`Pagination`].
#[derive(Props, Clone, PartialEq)]
pub struct PaginationProps {
    /// One-based current page. Set it with `total` to render the page list (data mode);
    /// otherwise the component renders `children` (slot mode).
    pub current: Option<u64>,
    /// Total page count.
    pub total: Option<u64>,
    /// Builds each page destination. Unsafe results (executable schemes, credentials,
    /// protocol-relative URLs) render as disabled entries. Defaults to `?page={page}`.
    pub href: Option<Callback<u64, String>>,
    /// Called with the chosen page. When set, activating a link calls it instead of following
    /// `href`, for apps that keep the page in state or a router.
    pub on_page_change: Option<EventHandler<u64>>,
    /// Pages shown on each side of the current page. Defaults to 1.
    #[props(default = 1)]
    pub siblings: u32,
    /// Pages pinned at each end. Defaults to 1.
    #[props(default = 1)]
    pub boundaries: u32,
    /// Localized names for the landmark, steps, and page links.
    #[props(default)]
    pub labels: PaginationLabels,
    /// Accessible name of the landmark. Overrides `labels.navigation`.
    #[props(into)]
    pub aria_label: Option<String>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<nav>` or global attribute.
    #[props(extends = GlobalAttributes, extends = nav)]
    pub attributes: Vec<Attribute>,
    /// Slot-mode content, used when `current` or `total` is unset.
    pub children: Element,
}

fn page_href(href: Option<Callback<u64, String>>, page: u64) -> Option<String> {
    let value = href.map_or_else(|| format!("?page={page}"), |builder| builder.call(page));

    resolve_safe_href(&value)
}

/// Page navigation for paged content.
///
/// In data mode it renders previous and next steps, boundary pages, a window around the current
/// page, and ellipses for hidden runs, with the same markup as lumen-react.
#[component]
pub fn Pagination(props: PaginationProps) -> Element {
    let class = compose([Some("ui-pagination"), props.class.as_deref()]);

    let (Some(current), Some(total)) = (props.current, props.total) else {
        return rsx! {
            nav {
                aria_label: props.aria_label.unwrap_or_else(|| "Pagination".to_string()),
                class,
                ..props.attributes,
                {props.children}
            }
        };
    };

    let labels = props.labels.resolve();
    let current = pagination_page(current, total);
    let items = pagination_items(current, total, props.siblings, props.boundaries);
    let previous = (current > 1).then(|| current - 1);
    let next = (current < total).then(|| current + 1);
    let href = props.href;
    let on_page_change = props.on_page_change;
    let aria_label = props.aria_label.unwrap_or(labels.navigation);
    let page_template = labels.page;

    let step = move |page: Option<u64>, label: String, rel: &'static str| {
        let destination = page.and_then(|page| page_href(href, page));
        let data_step = if rel == "prev" { "previous" } else { "next" };

        rsx! {
            li { class: "ui-pagination__item",
                match (page, destination) {
                    (Some(page), Some(destination)) => rsx! {
                        a {
                            class: "ui-pagination__link ui-pagination__step",
                            "data-step": data_step,
                            href: destination,
                            rel,
                            onclick: move |event: MouseEvent| {
                                if let Some(handler) = on_page_change {
                                    event.prevent_default();
                                    handler.call(page);
                                }
                            },
                            "{label}"
                        }
                    },
                    _ => rsx! {
                        span {
                            aria_disabled: "true",
                            class: "ui-pagination__link ui-pagination__step",
                            "data-step": data_step,
                            "{label}"
                        }
                    },
                }
            }
        }
    };

    rsx! {
        nav {
            aria_label,
            class,
            "data-ui-pagination-mode": "data",
            ..props.attributes,
            ul { class: "ui-pagination__list", role: "list",
                {step(previous, labels.previous, "prev")}
                for item in items {
                    match item {
                        PaginationItem::Ellipsis(ellipsis) => rsx! {
                            li {
                                key: "{ellipsis.as_str()}",
                                aria_hidden: "true",
                                class: "ui-pagination__item",
                                "data-key": ellipsis.as_str(),
                                span { class: "ui-pagination__ellipsis", "…" }
                            }
                        },
                        PaginationItem::Page { page, current } => {
                            let label = page_label(&page_template, page);
                            let aria_current = current.then_some("page");

                            rsx! {
                                li { key: "{page}", class: "ui-pagination__item",
                                    if let Some(destination) = page_href(href, page) {
                                        a {
                                            aria_current,
                                            aria_label: label,
                                            class: "ui-pagination__link",
                                            href: destination,
                                            onclick: move |event: MouseEvent| {
                                                if let Some(handler) = on_page_change {
                                                    event.prevent_default();
                                                    handler.call(page);
                                                }
                                            },
                                            "{page}"
                                        }
                                    } else {
                                        span {
                                            aria_current,
                                            aria_disabled: (!current).then_some("true"),
                                            class: "ui-pagination__link",
                                            span { class: "ui-sr-only", "{label}" }
                                            span { aria_hidden: "true", "{page}" }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                {step(next, labels.next, "next")}
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{
        PaginationEllipsis, PaginationItem, page_label, pagination_items, pagination_page,
    };

    fn render(items: &[PaginationItem]) -> String {
        items
            .iter()
            .map(|item| match item {
                PaginationItem::Page {
                    page,
                    current: true,
                } => format!("[{page}]"),
                PaginationItem::Page { page, .. } => page.to_string(),
                PaginationItem::Ellipsis(PaginationEllipsis::Start) => "<".to_string(),
                PaginationItem::Ellipsis(PaginationEllipsis::End) => ">".to_string(),
            })
            .collect::<Vec<_>>()
            .join(" ")
    }

    #[test]
    fn windows_match_lumen_core() {
        assert_eq!(render(&pagination_items(5, 10, 1, 1)), "1 < 4 [5] 6 > 10");
        assert_eq!(render(&pagination_items(1, 10, 1, 1)), "[1] 2 > 10");
        assert_eq!(render(&pagination_items(10, 10, 1, 1)), "1 < 9 [10]");
        // A one-page gap is shown instead of hidden.
        assert_eq!(render(&pagination_items(4, 10, 1, 1)), "1 2 3 [4] 5 > 10");
        assert_eq!(render(&pagination_items(3, 5, 1, 1)), "1 2 [3] 4 5");
        assert_eq!(render(&pagination_items(5, 10, 0, 0)), "[5]");
        assert_eq!(
            render(&pagination_items(5, 10, 1, 2)),
            "1 2 3 4 [5] 6 > 9 10"
        );
        assert_eq!(
            render(&pagination_items(6, 12, 1, 2)),
            "1 2 < 5 [6] 7 > 11 12"
        );
        assert_eq!(render(&pagination_items(1, 1, 1, 1)), "[1]");
    }

    #[test]
    fn inputs_clamp() {
        assert_eq!(pagination_items(1, 0, 1, 1), Vec::new());
        assert_eq!(render(&pagination_items(0, 3, 1, 1)), "[1] 2 3");
        assert_eq!(render(&pagination_items(99, 3, 1, 1)), "1 2 [3]");
        assert_eq!(pagination_page(0, 0), 1);
        assert_eq!(pagination_page(7, 4), 4);
    }

    #[test]
    fn huge_totals_stay_proportional_to_the_window() {
        let items = pagination_items(u64::MAX / 2, u64::MAX, 2, 1);
        assert_eq!(items.len(), 9);
        let items = pagination_items(1, u64::MAX, u32::MAX, u32::MAX);
        assert!(items.len() <= 203);
    }

    #[test]
    fn page_labels_fill_the_template() {
        assert_eq!(page_label("Page {page}", 3), "Page 3");
        assert_eq!(page_label("Página {page} de {page}", 2), "Página 2 de 2");
    }
}