use dioxus::prelude::*;
use crate::class::compose;
use super::util::{non_empty_or, resolve_safe_href};
const MAX_WINDOW_RADIUS: u32 = 100;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PaginationEllipsis {
Start,
End,
}
impl PaginationEllipsis {
pub fn as_str(self) -> &'static str {
match self {
Self::Start => "ellipsis-start",
Self::End => "ellipsis-end",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum PaginationItem {
Page {
page: u64,
current: bool,
},
Ellipsis(PaginationEllipsis),
}
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() {
Some(previous) if start <= previous.1.saturating_add(2) => {
previous.1 = previous.1.max(end);
}
_ => ranges.push((start, end)),
}
}
ranges
}
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));
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
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PaginationLabels {
pub navigation: Option<String>,
pub next: Option<String>,
pub previous: Option<String>,
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
}
}
#[derive(Props, Clone, PartialEq)]
pub struct PaginationProps {
pub current: Option<u64>,
pub total: Option<u64>,
pub href: Option<Callback<u64, String>>,
pub on_page_change: Option<EventHandler<u64>>,
#[props(default = 1)]
pub siblings: u32,
#[props(default = 1)]
pub boundaries: u32,
#[props(default)]
pub labels: PaginationLabels,
#[props(into)]
pub aria_label: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = nav)]
pub attributes: Vec<Attribute>,
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)
}
#[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]");
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");
}
}