1
//! Generic list-display tab for Accounts, Transactions, Commodities.
2

            
3
use cli_core::render::schema::{self, EntitySchema};
4
use cli_core::render::{ErrorReply, ListRow, RenderError, WireValue, parse_wire};
5
use cli_core::transaction::{Page, parse_page};
6
use forms::FormValues;
7
use ratatui::buffer::Buffer;
8
use ratatui::layout::{Constraint, Rect};
9
use ratatui::widgets::{Cell, Paragraph, Row, Widget};
10
use std::collections::BTreeSet;
11
use std::ops::Range;
12
use tvui::{FrameState, Panel, RowWindow, render_info};
13

            
14
pub use balances::Balances;
15

            
16
use crate::tabs::fetch::Fetch;
17
use crate::tabs::paging::{self, Pager};
18
use crate::tabs::seq::Seq;
19
use crate::view::DrawCtx;
20
use crate::widgets::TablePanel;
21

            
22
mod balances;
23

            
24
const BALANCE_HEADER: &str = "Balance";
25
const PAGED_HEADERS: [&str; 3] = ["Date", "Note", "Amount"];
26

            
27
enum Source {
28
    Fixed(String, &'static EntitySchema),
29
    Paged(Pager),
30
}
31

            
32
pub 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

            
47
impl ListTab {
48
4165
    pub fn new(request_form: impl Into<String>, schema: &'static EntitySchema) -> Self {
49
4165
        Self {
50
4165
            source: Source::Fixed(request_form.into(), schema),
51
4165
            state: Fetch::Idle,
52
4165
            selected: 0,
53
4165
            window: RowWindow::default(),
54
4165
            anchor: None,
55
4165
            land_last: false,
56
4165
            marks: BTreeSet::new(),
57
4165
            balances: None,
58
4165
            filter_seq: Seq::default(),
59
4165
            balances_seq: Seq::default(),
60
4165
        }
61
4165
    }
62

            
63
    /// Adds a Balance column, loading until [`ListTab::set_balances`] settles it.
64
    #[must_use]
65
2100
    pub fn with_balance_column(mut self) -> Self {
66
2100
        self.balances = Some(Balances::Loading);
67
2100
        self
68
2100
    }
69

            
70
6
    pub fn balances_loading(&self) -> bool {
71
6
        self.balances == Some(Balances::Loading)
72
6
    }
73

            
74
    /// Settles the Balance column; a no-op on a tab without one.
75
355
    pub fn set_balances(&mut self, state: Balances) {
76
355
        if let Some(balances) = &mut self.balances {
77
244
            *balances = state;
78
111
        }
79
355
    }
80

            
81
    /// A tab over the `transaction-query` form, one page at a time.
82
2055
    pub fn paged() -> Self {
83
2055
        Self {
84
2055
            source: Source::Paged(Pager::default()),
85
2055
            state: Fetch::Idle,
86
2055
            selected: 0,
87
2055
            window: RowWindow::default(),
88
2055
            anchor: None,
89
2055
            land_last: false,
90
2055
            marks: BTreeSet::new(),
91
2055
            balances: None,
92
2055
            filter_seq: Seq::default(),
93
2055
            balances_seq: Seq::default(),
94
2055
        }
95
2055
    }
96

            
97
440
    fn headers(&self) -> Vec<&'static str> {
98
440
        match &self.source {
99
416
            Source::Fixed(_, schema) => schema::headers(schema),
100
24
            Source::Paged(_) => PAGED_HEADERS.to_vec(),
101
        }
102
440
    }
103

            
104
    /// The form that fetches the tab's current contents.
105
589
    pub fn request_form(&self) -> String {
106
589
        match &self.source {
107
340
            Source::Fixed(form, _) => form.clone(),
108
249
            Source::Paged(pager) => pager.request(),
109
        }
110
589
    }
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
43
    pub fn turn_page(&mut self, forward: bool) -> bool {
116
43
        let Source::Paged(pager) = &mut self.source else {
117
            return false;
118
        };
119
43
        if matches!(self.state, Fetch::Loading { .. }) {
120
1
            return false;
121
42
        }
122
42
        let turned = if forward {
123
33
            pager.advance()
124
        } else {
125
9
            pager.retreat()
126
        };
127
42
        if turned {
128
36
            self.reset();
129
6
        }
130
42
        turned
131
43
    }
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
62
    pub fn turn_page_at_edge(&mut self, forward: bool) -> bool {
137
62
        let Fetch::Loaded(ref rows) = self.state else {
138
7
            return false;
139
        };
140
55
        let at_edge = if forward {
141
50
            self.selected + 1 >= rows.len()
142
        } else {
143
5
            self.selected == 0
144
        };
145
55
        let turned = at_edge && self.turn_page(forward);
146
55
        if turned {
147
19
            self.land_last = !forward;
148
36
        }
149
55
        turned
150
62
    }
151

            
152
    /// The call that fetches the first page of `filter`; `None` when the tab is not paged.
153
21
    pub fn filter_request(&self, filter: &FormValues) -> Option<String> {
154
21
        matches!(self.source, Source::Paged(_)).then(|| Pager::request_filtered(filter))
155
21
    }
156

            
157
    /// Make `filter` the tab's filter and drop the rows so they are fetched anew.
158
19
    pub fn set_filter(&mut self, filter: &FormValues, summary: String) {
159
19
        if let Source::Paged(pager) = &mut self.source {
160
19
            pager.set_filter(filter, summary);
161
19
            self.marks.clear();
162
19
            self.reset();
163
        }
164
19
    }
165

            
166
    /// Drop the filter and the rows; `false` when the tab is not paged.
167
7
    pub fn clear_filter(&mut self) -> bool {
168
7
        let Source::Paged(pager) = &mut self.source else {
169
            return false;
170
        };
171
7
        pager.clear_filter();
172
7
        self.marks.clear();
173
7
        self.reset();
174
7
        true
175
7
    }
176

            
177
    /// The values of the active filter.
178
43
    pub fn filter(&self) -> FormValues {
179
43
        match &self.source {
180
43
            Source::Paged(pager) => pager.filter().clone(),
181
            Source::Fixed(..) => FormValues::default(),
182
        }
183
43
    }
184

            
185
    /// `label`, followed by the active filter in brackets.
186
3630
    pub fn title(&self, label: &str) -> String {
187
3630
        match &self.source {
188
529
            Source::Paged(pager) if !pager.summary().is_empty() => {
189
5
                format!("{label} [{}]", pager.summary())
190
            }
191
3625
            _ => label.to_string(),
192
        }
193
3630
    }
194

            
195
    /// The rows the list has in all and the index of the first of the `loaded` ones among them.
196
439
    fn extent(&self, loaded: usize) -> (usize, usize) {
197
439
        match &self.source {
198
23
            Source::Paged(pager) => pager.extent(loaded),
199
416
            Source::Fixed(..) => (loaded, 0),
200
        }
201
439
    }
202

            
203
    /// `n–m of total` of the `visible` rows of the page on screen.
204
443
    pub fn range_note(&self, visible: Range<usize>) -> Option<String> {
205
443
        match &self.source {
206
27
            Source::Paged(pager) => pager.range(visible),
207
416
            Source::Fixed(..) => None,
208
        }
209
443
    }
210

            
211
    /// Whether the tab waits for the reply to request `id`.
212
17
    pub fn awaits(&self, id: i64) -> bool {
213
17
        self.state == Fetch::Loading { id }
214
17
    }
215

            
216
    /// Update loading id after the eval assigned a real envelope id.
217
215
    pub fn set_loading_id(&mut self, id: i64) {
218
215
        self.state = Fetch::Loading { id };
219
215
    }
220

            
221
    /// Process a routed reply wire frame and update fetch state.
222
275
    pub fn on_reply(&mut self, wire: &str) {
223
275
        self.set_balances(Balances::Loading);
224
275
        self.state = match &mut self.source {
225
180
            Source::Fixed(_, schema) => parse_reply(wire, schema),
226
95
            Source::Paged(pager) => parse_page_reply(wire, pager),
227
        };
228
275
        self.reselect();
229
275
    }
230

            
231
    /// Return the entity id of the focused row, or `None` when not loaded or no id.
232
194
    pub fn selected_id(&self) -> Option<&str> {
233
194
        let Fetch::Loaded(ref rows) = self.state else {
234
51
            return None;
235
        };
236
143
        rows.get(self.selected).and_then(|r| r.id.as_deref())
237
194
    }
238

            
239
    /// Fall back to the row's index when the id is gone.
240
275
    fn reselect(&mut self) {
241
275
        let land_last = std::mem::take(&mut self.land_last);
242
275
        match &self.state {
243
            Fetch::Loaded(rows) => {
244
264
                let kept = self
245
264
                    .anchor
246
264
                    .take()
247
13
                    .and_then(|id| rows.iter().position(|r| r.id.as_deref() == Some(&id)));
248
264
                let last = rows.len().saturating_sub(1);
249
264
                self.selected = match (kept, land_last) {
250
5
                    (Some(row), _) => row,
251
4
                    (None, true) => last,
252
255
                    (None, false) => self.selected.min(last),
253
                };
254
            }
255
2
            Fetch::Idle => self.land_last = true,
256
9
            Fetch::Error(_) => self.anchor = None,
257
            _ => {}
258
        }
259
275
    }
260

            
261
    /// Re-fetch keeping the focused row, by id, once the rows arrive.
262
54
    pub fn refresh(&mut self) {
263
54
        self.anchor = self.selected_id().map(str::to_string);
264
54
        self.state = Fetch::Idle;
265
54
    }
266

            
267
122
    pub fn select_next(&mut self) {
268
122
        if let Fetch::Loaded(ref rows) = self.state
269
116
            && self.selected + 1 < rows.len()
270
        {
271
112
            self.selected += 1;
272
10
        }
273
122
    }
274

            
275
23
    pub fn select_prev(&mut self) {
276
23
        self.selected = self.selected.saturating_sub(1);
277
23
    }
278

            
279
    /// Move the selection a view's height down or up.
280
35
    pub fn select_view(&mut self, down: bool) {
281
35
        if let Fetch::Loaded(ref rows) = self.state {
282
34
            self.selected = self.window.paged(self.selected, rows.len(), down);
283
1
        }
284
35
    }
285

            
286
9
    pub fn select_first(&mut self) {
287
9
        self.selected = 0;
288
9
    }
289

            
290
    /// Selects row `index` when the list holds it.
291
37
    pub fn select_row(&mut self, index: usize) {
292
37
        if let Fetch::Loaded(ref rows) = self.state
293
36
            && index < rows.len()
294
        {
295
35
            self.selected = index;
296
2
        }
297
37
    }
298

            
299
14
    pub fn select_last(&mut self) {
300
14
        if let Fetch::Loaded(ref rows) = self.state {
301
13
            self.selected = rows.len().saturating_sub(1);
302
1
        }
303
14
    }
304

            
305
    /// Toggle the mark of the focused row; `false` when there is none.
306
35
    pub fn toggle_mark(&mut self) -> bool {
307
35
        let Some(id) = self.selected_id().map(str::to_string) else {
308
            return false;
309
        };
310
35
        if !self.marks.remove(&id) {
311
34
            self.marks.insert(id);
312
1
        }
313
35
        true
314
35
    }
315

            
316
1
    pub fn clear_marks(&mut self) {
317
1
        self.marks.clear();
318
1
    }
319

            
320
34
    pub fn marked_ids(&self) -> Vec<String> {
321
34
        self.marks.iter().cloned().collect()
322
34
    }
323

            
324
13
    pub fn unmark(&mut self, id: &str) {
325
13
        self.marks.remove(id);
326
13
    }
327

            
328
    /// Reset to idle so the next tab-switch re-fetches.
329
63
    pub fn reset(&mut self) {
330
63
        self.state = Fetch::Idle;
331
63
        self.selected = 0;
332
63
        self.window.reset();
333
63
        self.anchor = None;
334
63
        self.land_last = false;
335
63
    }
336

            
337
    /// Draw the tab using the current fetch state.
338
1167
    pub fn draw(&self, buf: &mut Buffer, area: Rect, ctx: &mut DrawCtx) {
339
1167
        let title = ctx.title.clone();
340
1167
        match &self.state {
341
695
            Fetch::Idle => draw_notice(buf, area, &title, "Waiting...", ctx),
342
32
            Fetch::Loading { .. } => draw_notice(buf, area, &title, "Loading...", ctx),
343
1
            Fetch::Error(e) => draw_notice(buf, area, &title, &format!("[error] {e}"), ctx),
344
439
            Fetch::Loaded(rows) => self.draw_rows(buf, area, &title, rows, ctx),
345
        }
346
1167
    }
347

            
348
439
    fn draw_rows(
349
439
        &self,
350
439
        buf: &mut Buffer,
351
439
        area: Rect,
352
439
        title: &str,
353
439
        rows: &[ListRow],
354
439
        ctx: &mut DrawCtx,
355
439
    ) {
356
439
        let mut headers = self.headers();
357
439
        headers.extend(self.balances.as_ref().map(|_| BALANCE_HEADER));
358
439
        let widths = column_widths(headers.len(), self.balances.is_some());
359
439
        let balance_width = Panel::new(ctx.theme, title, FrameState::default())
360
439
            .widths(&widths)
361
439
            .columns(area)
362
439
            .last()
363
439
            .map_or(0, |column| usize::from(column.width));
364
439
        let table = Rows {
365
439
            marks: &self.marks,
366
439
            balances: self.balances.as_ref(),
367
439
            balance_width,
368
439
        };
369
        let visible = TablePanel {
370
439
            theme: ctx.theme,
371
439
            title,
372
439
            state: ctx.frame,
373
439
            headers: &headers,
374
439
            widths: &widths,
375
6815
            rows: rows.iter().map(|row| Row::new(table.cells(row))).collect(),
376
439
            selected: self.selected,
377
439
            extent: self.extent(rows.len()),
378
        }
379
439
        .draw(buf, area, &self.window, ctx.hits);
380
439
        let info = self.range_note(visible).unwrap_or_default();
381
439
        render_info(ctx.theme, area, buf, ctx.frame, &info);
382
439
    }
383
}
384

            
385
728
fn draw_notice(buf: &mut Buffer, area: Rect, title: &str, text: &str, ctx: &DrawCtx) {
386
728
    Panel::new(ctx.theme, title, ctx.frame).render(area, buf);
387
728
    Paragraph::new(text.to_string()).render(Panel::inner(area), buf);
388
728
}
389

            
390
95
fn page_of(wire: &str) -> Result<Page, String> {
391
95
    match parse_wire(wire) {
392
90
        Ok(WireValue::Value(ref value)) => parse_page(value).map_err(|err| err.to_string()),
393
        Err(RenderError::Server(ErrorReply { code, message, .. })) => {
394
5
            Err(format!("[{code}] {message}"))
395
        }
396
        Err(err) => Err(err.to_string()),
397
    }
398
95
}
399

            
400
/// `Idle` when the page overshot the end, so the caller fetches the last one.
401
95
fn parse_page_reply(wire: &str, pager: &mut Pager) -> Fetch<Vec<ListRow>> {
402
95
    match page_of(wire) {
403
89
        Ok(page) if pager.accept(&page) => Fetch::Idle,
404
87
        Ok(page) => Fetch::Loaded(paging::rows(&page)),
405
6
        Err(message) => Fetch::Error(message),
406
    }
407
95
}
408

            
409
180
fn parse_reply(wire: &str, entity_schema: &EntitySchema) -> Fetch<Vec<ListRow>> {
410
180
    match parse_wire(wire) {
411
177
        Ok(WireValue::Value(ref v)) => Fetch::Loaded(schema::project_rows(v, entity_schema)),
412
        Err(RenderError::Server(ErrorReply { code, message, .. })) => {
413
3
            Fetch::Error(format!("[{code}] {message}"))
414
        }
415
        Err(e) => Fetch::Error(e.to_string()),
416
    }
417
180
}
418

            
419
/// Column constraints; the balance column, the last one, takes two fifths so whole amounts fit.
420
439
fn column_widths(cols: usize, balance: bool) -> Vec<Constraint> {
421
439
    let cols = cols.max(1);
422
439
    if !balance {
423
38
        return vec![Constraint::Ratio(1, cols as u32); cols];
424
401
    }
425
401
    let mut widths = vec![Constraint::Fill(1); cols - 1];
426
401
    widths.push(Constraint::Percentage(40));
427
401
    widths
428
439
}
429

            
430
/// The rows of a table with the state their cells depend on.
431
struct Rows<'a> {
432
    marks: &'a BTreeSet<String>,
433
    balances: Option<&'a Balances>,
434
    balance_width: usize,
435
}
436

            
437
impl Rows<'_> {
438
6815
    fn cells(&self, row: &ListRow) -> Vec<Cell<'static>> {
439
6815
        let marked = row.id.as_ref().is_some_and(|id| self.marks.contains(id));
440
6815
        let balance = self
441
6815
            .balances
442
6266
            .map(|balances| balances.cell(row.id.as_ref(), self.balance_width));
443
6815
        row.cells
444
6815
            .iter()
445
6815
            .enumerate()
446
20433
            .map(|(i, c)| marked_cell(c, i == 0, marked, self.marks.is_empty()))
447
6815
            .chain(balance)
448
6815
            .map(Cell::from)
449
            .collect()
450
6815
    }
451
}
452

            
453
/// The first cell carries the mark gutter once any row is marked.
454
20437
fn marked_cell(cell: &str, first: bool, marked: bool, no_marks: bool) -> String {
455
20437
    match (first, marked, no_marks) {
456
1
        (true, true, _) => format!("* {cell}"),
457
1
        (true, false, false) => format!("  {cell}"),
458
20435
        _ => cell.to_string(),
459
    }
460
20437
}
461

            
462
#[cfg(test)]
463
mod panel_tests;
464
#[cfg(test)]
465
mod tests;