Skip to main content

rustango_cms/admin/
pagination.rs

1//! Shared pagination context for admin list pages.
2//!
3//! Three list pages had each grown their own pagination: different
4//! context variable names (`page` vs `current_page`), different labels
5//! ("Prev" vs "Previous"), one hand-building query strings and one
6//! using the `querystring` filter — and none of them offered a page
7//! size or a way to jump to a page.
8//!
9//! This builds the context that `rcms_admin/_pagination.html` renders,
10//! so every list gets the same controls from one place. The page
11//! arithmetic itself comes from [`rustango::pagination::Paginator`].
12
13/// Rows per page when the request doesn't say.
14pub const DEFAULT_PER_PAGE: usize = 50;
15/// Ceiling for `?per_page=`. A hostile or fat-fingered value must not
16/// turn a list page into a full-table fetch.
17pub const MAX_PER_PAGE: usize = 100;
18/// Offered in the size selector. Kept at/below [`MAX_PER_PAGE`].
19pub const PER_PAGE_CHOICES: [usize; 3] = [25, 50, 100];
20
21/// Snap a requested page size to one of [`PER_PAGE_CHOICES`].
22///
23/// Snapping, rather than merely capping at [`MAX_PER_PAGE`]: the size
24/// selector can only display a value it offers, so an off-list size like
25/// `?per_page=2` left the select showing "25" while the server served 2
26/// — the control lied about the state it was in. Rounding up to the
27/// nearest offered size keeps the two in agreement.
28#[must_use]
29pub fn clamp_per_page(requested: Option<usize>) -> usize {
30    match requested {
31        None | Some(0) => DEFAULT_PER_PAGE,
32        Some(n) => PER_PAGE_CHOICES
33            .into_iter()
34            .find(|&choice| n <= choice)
35            .unwrap_or(MAX_PER_PAGE),
36    }
37}
38
39/// Build the template context for the shared pagination partial.
40///
41/// `page` is 1-based and clamped into range, so an out-of-range `?page=`
42/// lands on the last page instead of rendering an empty list with dead
43/// prev/next links.
44#[must_use]
45pub fn context(page: i64, per_page: usize, total: usize) -> serde_json::Value {
46    let paginator = rustango::pagination::Paginator::new(total, per_page);
47    let total_pages = paginator.num_pages().max(1) as i64;
48    let current = page.clamp(1, total_pages);
49    let start = if total == 0 {
50        0
51    } else {
52        (current - 1) * per_page as i64 + 1
53    };
54    let end = (current * per_page as i64).min(total as i64);
55
56    serde_json::json!({
57        "page": current,
58        "per_page": per_page,
59        "total": total,
60        "total_pages": total_pages,
61        "start_index": start,
62        "end_index": end,
63        "has_prev": current > 1,
64        "has_next": current < total_pages,
65        "prev_page": (current - 1).max(1),
66        "next_page": (current + 1).min(total_pages),
67        "pages": (1..=total_pages).collect::<Vec<i64>>(),
68        "per_page_choices": PER_PAGE_CHOICES,
69        // Show the row when there is paging to do, when the list is
70        // big enough that the size matters — or when the size is not
71        // the default. That last clause matters: without it, picking a
72        // size large enough to fit everything on one page hid the row,
73        // and with it the only control that could put the size back.
74        "show": total_pages > 1
75            || total > PER_PAGE_CHOICES[0]
76            || per_page != DEFAULT_PER_PAGE,
77    })
78}
79
80/// Zero-based offset for the current page, for `.offset()`.
81#[must_use]
82pub fn offset(page: i64, per_page: usize) -> i64 {
83    (page.max(1) - 1) * per_page as i64
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    #[test]
91    fn per_page_is_clamped_to_the_ceiling() {
92        assert_eq!(clamp_per_page(None), DEFAULT_PER_PAGE);
93        assert_eq!(clamp_per_page(Some(0)), DEFAULT_PER_PAGE);
94        assert_eq!(clamp_per_page(Some(25)), 25);
95        // The point of the ceiling: a big `?per_page=` must not become a
96        // full-table fetch.
97        assert_eq!(clamp_per_page(Some(100_000)), MAX_PER_PAGE);
98    }
99
100    #[test]
101    fn odd_sizes_snap_to_an_offered_choice() {
102        // The selector can only show a size it offers; serving a size it
103        // cannot display makes the control misreport the current state.
104        assert_eq!(clamp_per_page(Some(2)), 25);
105        assert_eq!(clamp_per_page(Some(26)), 50);
106        assert_eq!(clamp_per_page(Some(51)), 100);
107        for n in PER_PAGE_CHOICES {
108            assert_eq!(clamp_per_page(Some(n)), n, "offered sizes pass through");
109        }
110    }
111
112    #[test]
113    fn the_size_control_never_hides_itself() {
114        // A non-default size must keep the row visible even when
115        // everything fits on one page — otherwise there is no way back.
116        let c = context(1, 100, 6);
117        assert_eq!(c["total_pages"], 1);
118        assert!(
119            c["show"].as_bool().unwrap(),
120            "picking a large size must not remove the size selector"
121        );
122        // Default size on a short list still needs no controls.
123        assert!(!context(1, DEFAULT_PER_PAGE, 6)["show"].as_bool().unwrap());
124    }
125
126    #[test]
127    fn out_of_range_page_clamps_to_the_last_one() {
128        let c = context(99, 50, 120);
129        assert_eq!(c["page"], 3, "120 items / 50 = 3 pages");
130        assert!(!c["has_next"].as_bool().unwrap());
131        assert!(c["has_prev"].as_bool().unwrap());
132    }
133
134    #[test]
135    fn indices_describe_the_visible_slice() {
136        let c = context(2, 50, 120);
137        assert_eq!(c["start_index"], 51);
138        assert_eq!(c["end_index"], 100);
139        // Last page is short: the end index is the total, not page*size.
140        let last = context(3, 50, 120);
141        assert_eq!(last["start_index"], 101);
142        assert_eq!(last["end_index"], 120);
143    }
144
145    #[test]
146    fn an_empty_list_is_still_page_one() {
147        let c = context(1, 50, 0);
148        assert_eq!(c["page"], 1);
149        assert_eq!(c["total_pages"], 1);
150        assert_eq!(c["start_index"], 0);
151        assert_eq!(c["end_index"], 0);
152        assert!(
153            !c["show"].as_bool().unwrap(),
154            "no controls for an empty list"
155        );
156    }
157
158    #[test]
159    fn offsets_follow_the_page() {
160        assert_eq!(offset(1, 50), 0);
161        assert_eq!(offset(3, 50), 100);
162        assert_eq!(offset(0, 50), 0, "page 0 is treated as page 1");
163    }
164}