Skip to main content

max / makenotwork

2.0 KB · 63 lines History Blame Raw
1 //! Shared pagination helpers for the public page handlers.
2
3 use crate::constants;
4
5 /// Build a sliding window of page numbers for pagination controls.
6 ///
7 /// One definition for every public list page (feed, discover, landing), they
8 /// previously each carried a byte-identical copy, so a tweak to the window
9 /// behavior had to be made in lockstep or silently drift.
10 ///
11 /// `pub(crate)` rather than `pub(super)` because the feed is described now and
12 /// `crate::quasi::feeds::load` windows the same way the Askama handlers did.
13 /// Widening it was the alternative to a fourth copy; do not narrow it back
14 /// without moving the function.
15 pub(crate) fn build_pagination_range(current_page: u32, total_pages: u32) -> Vec<u32> {
16 if total_pages <= constants::PAGINATION_WINDOW_SIZE {
17 (1..=total_pages).collect()
18 } else {
19 let start = current_page.saturating_sub(2).max(1);
20 let end = (start + 4).min(total_pages);
21 let start = end.saturating_sub(4).max(1);
22 (start..=end).collect()
23 }
24 }
25
26 #[cfg(test)]
27 mod tests {
28 use super::*;
29
30 #[test]
31 fn pagination_small_total() {
32 assert_eq!(build_pagination_range(1, 3), vec![1, 2, 3]);
33 assert_eq!(build_pagination_range(2, 5), vec![1, 2, 3, 4, 5]);
34 }
35
36 #[test]
37 fn pagination_large_at_start() {
38 assert_eq!(build_pagination_range(1, 20), vec![1, 2, 3, 4, 5]);
39 assert_eq!(build_pagination_range(2, 20), vec![1, 2, 3, 4, 5]);
40 }
41
42 #[test]
43 fn pagination_large_at_middle() {
44 assert_eq!(build_pagination_range(10, 20), vec![8, 9, 10, 11, 12]);
45 }
46
47 #[test]
48 fn pagination_large_at_end() {
49 assert_eq!(build_pagination_range(20, 20), vec![16, 17, 18, 19, 20]);
50 assert_eq!(build_pagination_range(19, 20), vec![16, 17, 18, 19, 20]);
51 }
52
53 #[test]
54 fn pagination_zero_pages() {
55 assert_eq!(build_pagination_range(1, 0), Vec::<u32>::new());
56 }
57
58 #[test]
59 fn pagination_single_page() {
60 assert_eq!(build_pagination_range(1, 1), vec![1]);
61 }
62 }
63