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    // Saturating: `?page=` is user input, and a wrapped (negative)
84    // OFFSET is an error on some backends.
85    (page.max(1) - 1).saturating_mul(i64::try_from(per_page).unwrap_or(i64::MAX))
86}
87
88/// `?page=&per_page=` for a list with no other query parameters.
89#[derive(Debug, Default, serde::Deserialize)]
90pub struct PageQuery {
91    #[serde(default)]
92    pub page: Option<i64>,
93    #[serde(default)]
94    pub per_page: Option<usize>,
95}
96
97/// One page of a list: what to fetch and what the partial renders.
98#[derive(Debug)]
99pub struct Window {
100    pub limit: i64,
101    pub offset: i64,
102    /// The `pagination` context for `_pagination.html`.
103    pub context: serde_json::Value,
104}
105
106impl PageQuery {
107    /// The page window over `total` rows; an out-of-range `?page=`
108    /// lands on the last page.
109    #[must_use]
110    pub fn window(&self, total: usize) -> Window {
111        let per_page = clamp_per_page(self.per_page);
112        let context = context(self.page.unwrap_or(1), per_page, total);
113        let page = context["page"].as_i64().unwrap_or(1);
114        Window {
115            limit: per_page as i64,
116            offset: offset(page, per_page),
117            context,
118        }
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::*;
125
126    #[test]
127    fn per_page_is_clamped_to_the_ceiling() {
128        assert_eq!(clamp_per_page(None), DEFAULT_PER_PAGE);
129        assert_eq!(clamp_per_page(Some(0)), DEFAULT_PER_PAGE);
130        assert_eq!(clamp_per_page(Some(25)), 25);
131        // The point of the ceiling: a big `?per_page=` must not become a
132        // full-table fetch.
133        assert_eq!(clamp_per_page(Some(100_000)), MAX_PER_PAGE);
134    }
135
136    #[test]
137    fn odd_sizes_snap_to_an_offered_choice() {
138        // The selector can only show a size it offers; serving a size it
139        // cannot display makes the control misreport the current state.
140        assert_eq!(clamp_per_page(Some(2)), 25);
141        assert_eq!(clamp_per_page(Some(26)), 50);
142        assert_eq!(clamp_per_page(Some(51)), 100);
143        for n in PER_PAGE_CHOICES {
144            assert_eq!(clamp_per_page(Some(n)), n, "offered sizes pass through");
145        }
146    }
147
148    #[test]
149    fn the_size_control_never_hides_itself() {
150        // A non-default size must keep the row visible even when
151        // everything fits on one page — otherwise there is no way back.
152        let c = context(1, 100, 6);
153        assert_eq!(c["total_pages"], 1);
154        assert!(
155            c["show"].as_bool().unwrap(),
156            "picking a large size must not remove the size selector"
157        );
158        // Default size on a short list still needs no controls.
159        assert!(!context(1, DEFAULT_PER_PAGE, 6)["show"].as_bool().unwrap());
160    }
161
162    #[test]
163    fn out_of_range_page_clamps_to_the_last_one() {
164        let c = context(99, 50, 120);
165        assert_eq!(c["page"], 3, "120 items / 50 = 3 pages");
166        assert!(!c["has_next"].as_bool().unwrap());
167        assert!(c["has_prev"].as_bool().unwrap());
168    }
169
170    #[test]
171    fn indices_describe_the_visible_slice() {
172        let c = context(2, 50, 120);
173        assert_eq!(c["start_index"], 51);
174        assert_eq!(c["end_index"], 100);
175        // Last page is short: the end index is the total, not page*size.
176        let last = context(3, 50, 120);
177        assert_eq!(last["start_index"], 101);
178        assert_eq!(last["end_index"], 120);
179    }
180
181    #[test]
182    fn an_empty_list_is_still_page_one() {
183        let c = context(1, 50, 0);
184        assert_eq!(c["page"], 1);
185        assert_eq!(c["total_pages"], 1);
186        assert_eq!(c["start_index"], 0);
187        assert_eq!(c["end_index"], 0);
188        assert!(
189            !c["show"].as_bool().unwrap(),
190            "no controls for an empty list"
191        );
192    }
193
194    #[test]
195    fn offsets_follow_the_page() {
196        assert_eq!(offset(1, 50), 0);
197        assert_eq!(offset(3, 50), 100);
198        assert_eq!(offset(0, 50), 0, "page 0 is treated as page 1");
199    }
200
201    #[test]
202    fn a_window_past_the_end_shows_the_last_page() {
203        let q = PageQuery { page: Some(99), per_page: Some(25) };
204        let w = q.window(60);
205        assert_eq!((w.limit, w.offset), (25, 50));
206        assert_eq!(w.context["page"], 3);
207    }
208}