1use dioxus::prelude::*;
4
5use crate::class::compose;
6
7use super::util::{non_empty_or, resolve_safe_href};
8
9const MAX_WINDOW_RADIUS: u32 = 100;
11
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum PaginationEllipsis {
15 Start,
17 End,
19}
20
21impl PaginationEllipsis {
22 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33#[non_exhaustive]
34pub enum PaginationItem {
35 Page {
37 page: u64,
39 current: bool,
41 },
42 Ellipsis(PaginationEllipsis),
44}
45
46pub 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 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
74pub 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 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
131pub struct PaginationLabels {
132 pub navigation: Option<String>,
134 pub next: Option<String>,
136 pub previous: Option<String>,
138 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#[derive(Props, Clone, PartialEq)]
172pub struct PaginationProps {
173 pub current: Option<u64>,
176 pub total: Option<u64>,
178 pub href: Option<Callback<u64, String>>,
181 pub on_page_change: Option<EventHandler<u64>>,
184 #[props(default = 1)]
186 pub siblings: u32,
187 #[props(default = 1)]
189 pub boundaries: u32,
190 #[props(default)]
192 pub labels: PaginationLabels,
193 #[props(into)]
195 pub aria_label: Option<String>,
196 #[props(into)]
198 pub class: Option<String>,
199 #[props(extends = GlobalAttributes, extends = nav)]
201 pub attributes: Vec<Attribute>,
202 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#[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 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}