Skip to main content

tui/tabs/
list.rs

1//! Generic list-display tab for Accounts, Transactions, Commodities.
2
3use cli_core::render::schema::{self, EntitySchema};
4use cli_core::render::{ErrorReply, ListRow, RenderError, WireValue, parse_wire};
5use cli_core::transaction::{Page, parse_page};
6use forms::FormValues;
7use ratatui::buffer::Buffer;
8use ratatui::layout::{Constraint, Rect};
9use ratatui::widgets::{Cell, Paragraph, Row, Widget};
10use std::collections::BTreeSet;
11use std::ops::Range;
12use tvui::{FrameState, Panel, RowWindow, render_info};
13
14pub use balances::Balances;
15
16use crate::tabs::fetch::Fetch;
17use crate::tabs::paging::{self, Pager};
18use crate::tabs::seq::Seq;
19use crate::view::DrawCtx;
20use crate::widgets::TablePanel;
21
22mod balances;
23
24const BALANCE_HEADER: &str = "Balance";
25const PAGED_HEADERS: [&str; 3] = ["Date", "Note", "Amount"];
26
27enum Source {
28    Fixed(String, &'static EntitySchema),
29    Paged(Pager),
30}
31
32pub struct ListTab {
33    source: Source,
34    pub state: Fetch<Vec<ListRow>>,
35    pub selected: usize,
36    pub window: RowWindow,
37    anchor: Option<String>,
38    /// Whether the page being fetched lands on its last row, not its first.
39    land_last: bool,
40    marks: BTreeSet<String>,
41    /// `None` when the tab has no balance column.
42    balances: Option<Balances>,
43    pub filter_seq: Seq,
44    pub balances_seq: Seq,
45}
46
47impl ListTab {
48    pub fn new(request_form: impl Into<String>, schema: &'static EntitySchema) -> Self {
49        Self {
50            source: Source::Fixed(request_form.into(), schema),
51            state: Fetch::Idle,
52            selected: 0,
53            window: RowWindow::default(),
54            anchor: None,
55            land_last: false,
56            marks: BTreeSet::new(),
57            balances: None,
58            filter_seq: Seq::default(),
59            balances_seq: Seq::default(),
60        }
61    }
62
63    /// Adds a Balance column, loading until [`ListTab::set_balances`] settles it.
64    #[must_use]
65    pub fn with_balance_column(mut self) -> Self {
66        self.balances = Some(Balances::Loading);
67        self
68    }
69
70    pub fn balances_loading(&self) -> bool {
71        self.balances == Some(Balances::Loading)
72    }
73
74    /// Settles the Balance column; a no-op on a tab without one.
75    pub fn set_balances(&mut self, state: Balances) {
76        if let Some(balances) = &mut self.balances {
77            *balances = state;
78        }
79    }
80
81    /// A tab over the `transaction-query` form, one page at a time.
82    pub fn paged() -> Self {
83        Self {
84            source: Source::Paged(Pager::default()),
85            state: Fetch::Idle,
86            selected: 0,
87            window: RowWindow::default(),
88            anchor: None,
89            land_last: false,
90            marks: BTreeSet::new(),
91            balances: None,
92            filter_seq: Seq::default(),
93            balances_seq: Seq::default(),
94        }
95    }
96
97    fn headers(&self) -> Vec<&'static str> {
98        match &self.source {
99            Source::Fixed(_, schema) => schema::headers(schema),
100            Source::Paged(_) => PAGED_HEADERS.to_vec(),
101        }
102    }
103
104    /// The form that fetches the tab's current contents.
105    pub fn request_form(&self) -> String {
106        match &self.source {
107            Source::Fixed(form, _) => form.clone(),
108            Source::Paged(pager) => pager.request(),
109        }
110    }
111
112    /// Move to the next (`forward`) or previous page and drop the rows so the
113    /// caller re-fetches; `false` when there is no such page, the tab is not paged or a page
114    /// is in flight.
115    pub fn turn_page(&mut self, forward: bool) -> bool {
116        let Source::Paged(pager) = &mut self.source else {
117            return false;
118        };
119        if matches!(self.state, Fetch::Loading { .. }) {
120            return false;
121        }
122        let turned = if forward {
123            pager.advance()
124        } else {
125            pager.retreat()
126        };
127        if turned {
128            self.reset();
129        }
130        turned
131    }
132
133    /// Turn the page when the selection sits on the loaded page's edge row in
134    /// the direction of travel; the selection lands on the opposite edge of
135    /// the new page. `false` when nothing was turned.
136    pub fn turn_page_at_edge(&mut self, forward: bool) -> bool {
137        let Fetch::Loaded(ref rows) = self.state else {
138            return false;
139        };
140        let at_edge = if forward {
141            self.selected + 1 >= rows.len()
142        } else {
143            self.selected == 0
144        };
145        let turned = at_edge && self.turn_page(forward);
146        if turned {
147            self.land_last = !forward;
148        }
149        turned
150    }
151
152    /// The call that fetches the first page of `filter`; `None` when the tab is not paged.
153    pub fn filter_request(&self, filter: &FormValues) -> Option<String> {
154        matches!(self.source, Source::Paged(_)).then(|| Pager::request_filtered(filter))
155    }
156
157    /// Make `filter` the tab's filter and drop the rows so they are fetched anew.
158    pub fn set_filter(&mut self, filter: &FormValues, summary: String) {
159        if let Source::Paged(pager) = &mut self.source {
160            pager.set_filter(filter, summary);
161            self.marks.clear();
162            self.reset();
163        }
164    }
165
166    /// Drop the filter and the rows; `false` when the tab is not paged.
167    pub fn clear_filter(&mut self) -> bool {
168        let Source::Paged(pager) = &mut self.source else {
169            return false;
170        };
171        pager.clear_filter();
172        self.marks.clear();
173        self.reset();
174        true
175    }
176
177    /// The values of the active filter.
178    pub fn filter(&self) -> FormValues {
179        match &self.source {
180            Source::Paged(pager) => pager.filter().clone(),
181            Source::Fixed(..) => FormValues::default(),
182        }
183    }
184
185    /// `label`, followed by the active filter in brackets.
186    pub fn title(&self, label: &str) -> String {
187        match &self.source {
188            Source::Paged(pager) if !pager.summary().is_empty() => {
189                format!("{label} [{}]", pager.summary())
190            }
191            _ => label.to_string(),
192        }
193    }
194
195    /// The rows the list has in all and the index of the first of the `loaded` ones among them.
196    fn extent(&self, loaded: usize) -> (usize, usize) {
197        match &self.source {
198            Source::Paged(pager) => pager.extent(loaded),
199            Source::Fixed(..) => (loaded, 0),
200        }
201    }
202
203    /// `n–m of total` of the `visible` rows of the page on screen.
204    pub fn range_note(&self, visible: Range<usize>) -> Option<String> {
205        match &self.source {
206            Source::Paged(pager) => pager.range(visible),
207            Source::Fixed(..) => None,
208        }
209    }
210
211    /// Whether the tab waits for the reply to request `id`.
212    pub fn awaits(&self, id: i64) -> bool {
213        self.state == Fetch::Loading { id }
214    }
215
216    /// Update loading id after the eval assigned a real envelope id.
217    pub fn set_loading_id(&mut self, id: i64) {
218        self.state = Fetch::Loading { id };
219    }
220
221    /// Process a routed reply wire frame and update fetch state.
222    pub fn on_reply(&mut self, wire: &str) {
223        self.set_balances(Balances::Loading);
224        self.state = match &mut self.source {
225            Source::Fixed(_, schema) => parse_reply(wire, schema),
226            Source::Paged(pager) => parse_page_reply(wire, pager),
227        };
228        self.reselect();
229    }
230
231    /// Return the entity id of the focused row, or `None` when not loaded or no id.
232    pub fn selected_id(&self) -> Option<&str> {
233        let Fetch::Loaded(ref rows) = self.state else {
234            return None;
235        };
236        rows.get(self.selected).and_then(|r| r.id.as_deref())
237    }
238
239    /// Fall back to the row's index when the id is gone.
240    fn reselect(&mut self) {
241        let land_last = std::mem::take(&mut self.land_last);
242        match &self.state {
243            Fetch::Loaded(rows) => {
244                let kept = self
245                    .anchor
246                    .take()
247                    .and_then(|id| rows.iter().position(|r| r.id.as_deref() == Some(&id)));
248                let last = rows.len().saturating_sub(1);
249                self.selected = match (kept, land_last) {
250                    (Some(row), _) => row,
251                    (None, true) => last,
252                    (None, false) => self.selected.min(last),
253                };
254            }
255            Fetch::Idle => self.land_last = true,
256            Fetch::Error(_) => self.anchor = None,
257            _ => {}
258        }
259    }
260
261    /// Re-fetch keeping the focused row, by id, once the rows arrive.
262    pub fn refresh(&mut self) {
263        self.anchor = self.selected_id().map(str::to_string);
264        self.state = Fetch::Idle;
265    }
266
267    pub fn select_next(&mut self) {
268        if let Fetch::Loaded(ref rows) = self.state
269            && self.selected + 1 < rows.len()
270        {
271            self.selected += 1;
272        }
273    }
274
275    pub fn select_prev(&mut self) {
276        self.selected = self.selected.saturating_sub(1);
277    }
278
279    /// Move the selection a view's height down or up.
280    pub fn select_view(&mut self, down: bool) {
281        if let Fetch::Loaded(ref rows) = self.state {
282            self.selected = self.window.paged(self.selected, rows.len(), down);
283        }
284    }
285
286    pub fn select_first(&mut self) {
287        self.selected = 0;
288    }
289
290    /// Selects row `index` when the list holds it.
291    pub fn select_row(&mut self, index: usize) {
292        if let Fetch::Loaded(ref rows) = self.state
293            && index < rows.len()
294        {
295            self.selected = index;
296        }
297    }
298
299    pub fn select_last(&mut self) {
300        if let Fetch::Loaded(ref rows) = self.state {
301            self.selected = rows.len().saturating_sub(1);
302        }
303    }
304
305    /// Toggle the mark of the focused row; `false` when there is none.
306    pub fn toggle_mark(&mut self) -> bool {
307        let Some(id) = self.selected_id().map(str::to_string) else {
308            return false;
309        };
310        if !self.marks.remove(&id) {
311            self.marks.insert(id);
312        }
313        true
314    }
315
316    pub fn clear_marks(&mut self) {
317        self.marks.clear();
318    }
319
320    pub fn marked_ids(&self) -> Vec<String> {
321        self.marks.iter().cloned().collect()
322    }
323
324    pub fn unmark(&mut self, id: &str) {
325        self.marks.remove(id);
326    }
327
328    /// Reset to idle so the next tab-switch re-fetches.
329    pub fn reset(&mut self) {
330        self.state = Fetch::Idle;
331        self.selected = 0;
332        self.window.reset();
333        self.anchor = None;
334        self.land_last = false;
335    }
336
337    /// Draw the tab using the current fetch state.
338    pub fn draw(&self, buf: &mut Buffer, area: Rect, ctx: &mut DrawCtx) {
339        let title = ctx.title.clone();
340        match &self.state {
341            Fetch::Idle => draw_notice(buf, area, &title, "Waiting...", ctx),
342            Fetch::Loading { .. } => draw_notice(buf, area, &title, "Loading...", ctx),
343            Fetch::Error(e) => draw_notice(buf, area, &title, &format!("[error] {e}"), ctx),
344            Fetch::Loaded(rows) => self.draw_rows(buf, area, &title, rows, ctx),
345        }
346    }
347
348    fn draw_rows(
349        &self,
350        buf: &mut Buffer,
351        area: Rect,
352        title: &str,
353        rows: &[ListRow],
354        ctx: &mut DrawCtx,
355    ) {
356        let mut headers = self.headers();
357        headers.extend(self.balances.as_ref().map(|_| BALANCE_HEADER));
358        let widths = column_widths(headers.len(), self.balances.is_some());
359        let balance_width = Panel::new(ctx.theme, title, FrameState::default())
360            .widths(&widths)
361            .columns(area)
362            .last()
363            .map_or(0, |column| usize::from(column.width));
364        let table = Rows {
365            marks: &self.marks,
366            balances: self.balances.as_ref(),
367            balance_width,
368        };
369        let visible = TablePanel {
370            theme: ctx.theme,
371            title,
372            state: ctx.frame,
373            headers: &headers,
374            widths: &widths,
375            rows: rows.iter().map(|row| Row::new(table.cells(row))).collect(),
376            selected: self.selected,
377            extent: self.extent(rows.len()),
378        }
379        .draw(buf, area, &self.window, ctx.hits);
380        let info = self.range_note(visible).unwrap_or_default();
381        render_info(ctx.theme, area, buf, ctx.frame, &info);
382    }
383}
384
385fn draw_notice(buf: &mut Buffer, area: Rect, title: &str, text: &str, ctx: &DrawCtx) {
386    Panel::new(ctx.theme, title, ctx.frame).render(area, buf);
387    Paragraph::new(text.to_string()).render(Panel::inner(area), buf);
388}
389
390fn page_of(wire: &str) -> Result<Page, String> {
391    match parse_wire(wire) {
392        Ok(WireValue::Value(ref value)) => parse_page(value).map_err(|err| err.to_string()),
393        Err(RenderError::Server(ErrorReply { code, message, .. })) => {
394            Err(format!("[{code}] {message}"))
395        }
396        Err(err) => Err(err.to_string()),
397    }
398}
399
400/// `Idle` when the page overshot the end, so the caller fetches the last one.
401fn parse_page_reply(wire: &str, pager: &mut Pager) -> Fetch<Vec<ListRow>> {
402    match page_of(wire) {
403        Ok(page) if pager.accept(&page) => Fetch::Idle,
404        Ok(page) => Fetch::Loaded(paging::rows(&page)),
405        Err(message) => Fetch::Error(message),
406    }
407}
408
409fn parse_reply(wire: &str, entity_schema: &EntitySchema) -> Fetch<Vec<ListRow>> {
410    match parse_wire(wire) {
411        Ok(WireValue::Value(ref v)) => Fetch::Loaded(schema::project_rows(v, entity_schema)),
412        Err(RenderError::Server(ErrorReply { code, message, .. })) => {
413            Fetch::Error(format!("[{code}] {message}"))
414        }
415        Err(e) => Fetch::Error(e.to_string()),
416    }
417}
418
419/// Column constraints; the balance column, the last one, takes two fifths so whole amounts fit.
420fn column_widths(cols: usize, balance: bool) -> Vec<Constraint> {
421    let cols = cols.max(1);
422    if !balance {
423        return vec![Constraint::Ratio(1, cols as u32); cols];
424    }
425    let mut widths = vec![Constraint::Fill(1); cols - 1];
426    widths.push(Constraint::Percentage(40));
427    widths
428}
429
430/// The rows of a table with the state their cells depend on.
431struct Rows<'a> {
432    marks: &'a BTreeSet<String>,
433    balances: Option<&'a Balances>,
434    balance_width: usize,
435}
436
437impl Rows<'_> {
438    fn cells(&self, row: &ListRow) -> Vec<Cell<'static>> {
439        let marked = row.id.as_ref().is_some_and(|id| self.marks.contains(id));
440        let balance = self
441            .balances
442            .map(|balances| balances.cell(row.id.as_ref(), self.balance_width));
443        row.cells
444            .iter()
445            .enumerate()
446            .map(|(i, c)| marked_cell(c, i == 0, marked, self.marks.is_empty()))
447            .chain(balance)
448            .map(Cell::from)
449            .collect()
450    }
451}
452
453/// The first cell carries the mark gutter once any row is marked.
454fn marked_cell(cell: &str, first: bool, marked: bool, no_marks: bool) -> String {
455    match (first, marked, no_marks) {
456        (true, true, _) => format!("* {cell}"),
457        (true, false, false) => format!("  {cell}"),
458        _ => cell.to_string(),
459    }
460}
461
462#[cfg(test)]
463mod panel_tests;
464#[cfg(test)]
465mod tests;