Skip to main content

tui/tabs/
paging.rs

1//! Paging state of the Transactions tab over the `transaction-query` form.
2
3use std::ops::Range;
4
5use cli_core::render::ListRow;
6use cli_core::transaction::{Page, submit_call};
7use forms::{FormValues, PAGING_KEYS, TRANSACTION_QUERY};
8use tvui::range_text;
9
10pub const PAGE_SIZE: u64 = 20;
11
12#[derive(Debug, Clone, Default, PartialEq, Eq)]
13pub struct Pager {
14    offset: u64,
15    total: Option<u64>,
16    has_more: bool,
17    filter: FormValues,
18    summary: String,
19}
20
21/// The filtering values of `values`: the non-empty ones, paging keys left out.
22#[must_use]
23pub fn filter_of(values: &FormValues) -> FormValues {
24    let mut filter = FormValues::default();
25    TRANSACTION_QUERY
26        .filter_fields()
27        .filter_map(|field| Some((field.key, values.text(field.key)?)))
28        .filter(|(_, text)| !text.is_empty())
29        .for_each(|(key, text)| filter.set(key, text));
30    filter
31}
32
33/// Short note of a filter: the account label and the `from–to` range.
34#[must_use]
35pub fn filter_summary(account_label: &str, filter: &FormValues) -> String {
36    let (from, to) = (filter.text("from"), filter.text("to"));
37    let range = (from.is_some() || to.is_some())
38        .then(|| format!("{}\u{2013}{}", from.unwrap_or(""), to.unwrap_or("")));
39    let account = filter.text("account").map(|_| account_label.to_string());
40    [account, range]
41        .into_iter()
42        .flatten()
43        .collect::<Vec<_>>()
44        .join(" ")
45}
46
47fn query_call(filter: &FormValues, offset: u64) -> String {
48    let mut values = filter.clone();
49    let [limit_key, offset_key] = PAGING_KEYS;
50    values.set(limit_key, &PAGE_SIZE.to_string());
51    values.set(offset_key, &offset.to_string());
52    submit_call(&TRANSACTION_QUERY, &values)
53}
54
55impl Pager {
56    /// The `submit-form` call that fetches the current page.
57    #[must_use]
58    pub fn request(&self) -> String {
59        query_call(&self.filter, self.offset)
60    }
61
62    /// The call that fetches the first page of `filter`, which is not applied yet.
63    #[must_use]
64    pub fn request_filtered(filter: &FormValues) -> String {
65        query_call(&filter_of(filter), 0)
66    }
67
68    /// Show the first page of `filter` from now on.
69    pub fn set_filter(&mut self, filter: &FormValues, summary: String) {
70        *self = Self {
71            filter: filter_of(filter),
72            summary,
73            ..Self::default()
74        };
75    }
76
77    /// Drop the filter and go back to the first page.
78    pub fn clear_filter(&mut self) {
79        *self = Self::default();
80    }
81
82    #[must_use]
83    pub fn filter(&self) -> &FormValues {
84        &self.filter
85    }
86
87    #[must_use]
88    pub fn summary(&self) -> &str {
89        &self.summary
90    }
91
92    /// Step to the next page; `false` when the last one is showing.
93    pub fn advance(&mut self) -> bool {
94        let moved = self.has_more;
95        if moved {
96            self.offset = self.offset.saturating_add(PAGE_SIZE);
97        }
98        moved
99    }
100
101    /// Step to the previous page; `false` when the first one is showing.
102    pub fn retreat(&mut self) -> bool {
103        let moved = self.offset > 0;
104        self.offset = self.offset.saturating_sub(PAGE_SIZE);
105        moved
106    }
107
108    /// Record a received page. `true` when it is empty past the first page
109    /// (rows were deleted), after which the offset points at the last page.
110    pub fn accept(&mut self, page: &Page) -> bool {
111        self.total = page.total;
112        self.has_more = page.has_more;
113        let overshot = page.rows.is_empty() && self.offset > 0;
114        if overshot {
115            let rows = page.total.unwrap_or(0);
116            self.offset = rows.saturating_sub(1) / PAGE_SIZE * PAGE_SIZE;
117        }
118        overshot
119    }
120
121    /// The rows in all, when known, and the index of the page's first row among them.
122    #[must_use]
123    pub fn extent(&self, loaded: usize) -> (usize, usize) {
124        let first = usize::try_from(self.offset).unwrap_or(usize::MAX);
125        let total = self.total.and_then(|total| usize::try_from(total).ok());
126        (total.unwrap_or(first.saturating_add(loaded)), first)
127    }
128
129    /// `n–m of total` for the `visible` rows of the page.
130    #[must_use]
131    pub fn range(&self, visible: Range<usize>) -> Option<String> {
132        let total = usize::try_from(self.total?).ok()?;
133        let first = usize::try_from(self.offset).ok()?;
134        range_text(
135            first.saturating_add(visible.start)..first.saturating_add(visible.end),
136            total,
137        )
138    }
139}
140
141/// The display row of every transaction of the page.
142#[must_use]
143pub fn rows(page: &Page) -> Vec<ListRow> {
144    page.rows
145        .iter()
146        .map(|row| ListRow {
147            id: Some(row.id.clone()),
148            cells: vec![row.date.clone(), row.note.clone(), row.amount.clone()],
149        })
150        .collect()
151}
152
153#[cfg(test)]
154mod filter_tests;
155#[cfg(test)]
156mod tests;