leptos_pagination/
state.rs

1use leptos::prelude::*;
2use reactive_stores::Store;
3
4/// The state of pagination.
5///
6/// Used as a reactive store to communicate between control and display components.
7#[derive(Store, Clone, Debug, PartialEq, Eq)]
8pub struct PaginationState {
9    /// The current page number. Counting starts from 0.
10    pub current_page: usize,
11    /// The total number of pages or None initially or if the count could not be determined.
12    pub page_count: Option<usize>,
13    /// The error message if the page count could not be determined.
14    pub page_count_error: Option<String>,
15}
16
17impl PaginationState {
18    pub fn new_store() -> Store<Self> {
19        Store::new(Self {
20            current_page: 0,
21            page_count: None,
22            page_count_error: None,
23        })
24    }
25
26    /// If possible, move to the next page.
27    pub fn next(this_store: Store<Self>) {
28        if !Self::is_last_page(this_store) {
29            this_store.current_page().update(|cp| *cp += 1);
30        }
31    }
32
33    /// If possible, move to the previous page.
34    pub fn prev(this_store: Store<Self>) {
35        if this_store.current_page().get() > 0 {
36            this_store.current_page().update(|cp| *cp -= 1);
37        }
38    }
39
40    pub fn is_first_page(this_store: Store<Self>) -> bool {
41        this_store.current_page().get() == 0
42    }
43
44    pub fn is_last_page(this_store: Store<Self>) -> bool {
45        if let Some(page_count) = this_store.page_count().get() {
46            this_store.current_page().get() >= page_count.saturating_sub(1)
47        } else {
48            false
49        }
50    }
51}