Lines
97.29 %
Functions
76.92 %
Branches
100 %
//! Generic list-display tab for Accounts, Transactions, Commodities.
use cli_core::render::schema::{self, EntitySchema};
use cli_core::render::{ErrorReply, ListRow, RenderError, WireValue, parse_wire};
use cli_core::transaction::{Page, parse_page};
use forms::FormValues;
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Rect};
use ratatui::widgets::{Cell, Paragraph, Row, Widget};
use std::collections::BTreeSet;
use std::ops::Range;
use tvui::{FrameState, Panel, RowWindow, render_info};
pub use balances::Balances;
use crate::tabs::fetch::Fetch;
use crate::tabs::paging::{self, Pager};
use crate::tabs::seq::Seq;
use crate::view::DrawCtx;
use crate::widgets::TablePanel;
mod balances;
const BALANCE_HEADER: &str = "Balance";
const PAGED_HEADERS: [&str; 3] = ["Date", "Note", "Amount"];
enum Source {
Fixed(String, &'static EntitySchema),
Paged(Pager),
}
pub struct ListTab {
source: Source,
pub state: Fetch<Vec<ListRow>>,
pub selected: usize,
pub window: RowWindow,
anchor: Option<String>,
/// Whether the page being fetched lands on its last row, not its first.
land_last: bool,
marks: BTreeSet<String>,
/// `None` when the tab has no balance column.
balances: Option<Balances>,
pub filter_seq: Seq,
pub balances_seq: Seq,
impl ListTab {
pub fn new(request_form: impl Into<String>, schema: &'static EntitySchema) -> Self {
Self {
source: Source::Fixed(request_form.into(), schema),
state: Fetch::Idle,
selected: 0,
window: RowWindow::default(),
anchor: None,
land_last: false,
marks: BTreeSet::new(),
balances: None,
filter_seq: Seq::default(),
balances_seq: Seq::default(),
/// Adds a Balance column, loading until [`ListTab::set_balances`] settles it.
#[must_use]
pub fn with_balance_column(mut self) -> Self {
self.balances = Some(Balances::Loading);
self
pub fn balances_loading(&self) -> bool {
self.balances == Some(Balances::Loading)
/// Settles the Balance column; a no-op on a tab without one.
pub fn set_balances(&mut self, state: Balances) {
if let Some(balances) = &mut self.balances {
*balances = state;
/// A tab over the `transaction-query` form, one page at a time.
pub fn paged() -> Self {
source: Source::Paged(Pager::default()),
fn headers(&self) -> Vec<&'static str> {
match &self.source {
Source::Fixed(_, schema) => schema::headers(schema),
Source::Paged(_) => PAGED_HEADERS.to_vec(),
/// The form that fetches the tab's current contents.
pub fn request_form(&self) -> String {
Source::Fixed(form, _) => form.clone(),
Source::Paged(pager) => pager.request(),
/// Move to the next (`forward`) or previous page and drop the rows so the
/// caller re-fetches; `false` when there is no such page, the tab is not paged or a page
/// is in flight.
pub fn turn_page(&mut self, forward: bool) -> bool {
let Source::Paged(pager) = &mut self.source else {
return false;
};
if matches!(self.state, Fetch::Loading { .. }) {
let turned = if forward {
pager.advance()
} else {
pager.retreat()
if turned {
self.reset();
turned
/// Turn the page when the selection sits on the loaded page's edge row in
/// the direction of travel; the selection lands on the opposite edge of
/// the new page. `false` when nothing was turned.
pub fn turn_page_at_edge(&mut self, forward: bool) -> bool {
let Fetch::Loaded(ref rows) = self.state else {
let at_edge = if forward {
self.selected + 1 >= rows.len()
self.selected == 0
let turned = at_edge && self.turn_page(forward);
self.land_last = !forward;
/// The call that fetches the first page of `filter`; `None` when the tab is not paged.
pub fn filter_request(&self, filter: &FormValues) -> Option<String> {
matches!(self.source, Source::Paged(_)).then(|| Pager::request_filtered(filter))
/// Make `filter` the tab's filter and drop the rows so they are fetched anew.
pub fn set_filter(&mut self, filter: &FormValues, summary: String) {
if let Source::Paged(pager) = &mut self.source {
pager.set_filter(filter, summary);
self.marks.clear();
/// Drop the filter and the rows; `false` when the tab is not paged.
pub fn clear_filter(&mut self) -> bool {
pager.clear_filter();
true
/// The values of the active filter.
pub fn filter(&self) -> FormValues {
Source::Paged(pager) => pager.filter().clone(),
Source::Fixed(..) => FormValues::default(),
/// `label`, followed by the active filter in brackets.
pub fn title(&self, label: &str) -> String {
Source::Paged(pager) if !pager.summary().is_empty() => {
format!("{label} [{}]", pager.summary())
_ => label.to_string(),
/// The rows the list has in all and the index of the first of the `loaded` ones among them.
fn extent(&self, loaded: usize) -> (usize, usize) {
Source::Paged(pager) => pager.extent(loaded),
Source::Fixed(..) => (loaded, 0),
/// `n–m of total` of the `visible` rows of the page on screen.
pub fn range_note(&self, visible: Range<usize>) -> Option<String> {
Source::Paged(pager) => pager.range(visible),
Source::Fixed(..) => None,
/// Whether the tab waits for the reply to request `id`.
pub fn awaits(&self, id: i64) -> bool {
self.state == Fetch::Loading { id }
/// Update loading id after the eval assigned a real envelope id.
pub fn set_loading_id(&mut self, id: i64) {
self.state = Fetch::Loading { id };
/// Process a routed reply wire frame and update fetch state.
pub fn on_reply(&mut self, wire: &str) {
self.set_balances(Balances::Loading);
self.state = match &mut self.source {
Source::Fixed(_, schema) => parse_reply(wire, schema),
Source::Paged(pager) => parse_page_reply(wire, pager),
self.reselect();
/// Return the entity id of the focused row, or `None` when not loaded or no id.
pub fn selected_id(&self) -> Option<&str> {
return None;
rows.get(self.selected).and_then(|r| r.id.as_deref())
/// Fall back to the row's index when the id is gone.
fn reselect(&mut self) {
let land_last = std::mem::take(&mut self.land_last);
match &self.state {
Fetch::Loaded(rows) => {
let kept = self
.anchor
.take()
.and_then(|id| rows.iter().position(|r| r.id.as_deref() == Some(&id)));
let last = rows.len().saturating_sub(1);
self.selected = match (kept, land_last) {
(Some(row), _) => row,
(None, true) => last,
(None, false) => self.selected.min(last),
Fetch::Idle => self.land_last = true,
Fetch::Error(_) => self.anchor = None,
_ => {}
/// Re-fetch keeping the focused row, by id, once the rows arrive.
pub fn refresh(&mut self) {
self.anchor = self.selected_id().map(str::to_string);
self.state = Fetch::Idle;
pub fn select_next(&mut self) {
if let Fetch::Loaded(ref rows) = self.state
&& self.selected + 1 < rows.len()
{
self.selected += 1;
pub fn select_prev(&mut self) {
self.selected = self.selected.saturating_sub(1);
/// Move the selection a view's height down or up.
pub fn select_view(&mut self, down: bool) {
if let Fetch::Loaded(ref rows) = self.state {
self.selected = self.window.paged(self.selected, rows.len(), down);
pub fn select_first(&mut self) {
self.selected = 0;
/// Selects row `index` when the list holds it.
pub fn select_row(&mut self, index: usize) {
&& index < rows.len()
self.selected = index;
pub fn select_last(&mut self) {
self.selected = rows.len().saturating_sub(1);
/// Toggle the mark of the focused row; `false` when there is none.
pub fn toggle_mark(&mut self) -> bool {
let Some(id) = self.selected_id().map(str::to_string) else {
if !self.marks.remove(&id) {
self.marks.insert(id);
pub fn clear_marks(&mut self) {
pub fn marked_ids(&self) -> Vec<String> {
self.marks.iter().cloned().collect()
pub fn unmark(&mut self, id: &str) {
self.marks.remove(id);
/// Reset to idle so the next tab-switch re-fetches.
pub fn reset(&mut self) {
self.window.reset();
self.anchor = None;
self.land_last = false;
/// Draw the tab using the current fetch state.
pub fn draw(&self, buf: &mut Buffer, area: Rect, ctx: &mut DrawCtx) {
let title = ctx.title.clone();
Fetch::Idle => draw_notice(buf, area, &title, "Waiting...", ctx),
Fetch::Loading { .. } => draw_notice(buf, area, &title, "Loading...", ctx),
Fetch::Error(e) => draw_notice(buf, area, &title, &format!("[error] {e}"), ctx),
Fetch::Loaded(rows) => self.draw_rows(buf, area, &title, rows, ctx),
fn draw_rows(
&self,
buf: &mut Buffer,
area: Rect,
title: &str,
rows: &[ListRow],
ctx: &mut DrawCtx,
) {
let mut headers = self.headers();
headers.extend(self.balances.as_ref().map(|_| BALANCE_HEADER));
let widths = column_widths(headers.len(), self.balances.is_some());
let balance_width = Panel::new(ctx.theme, title, FrameState::default())
.widths(&widths)
.columns(area)
.last()
.map_or(0, |column| usize::from(column.width));
let table = Rows {
marks: &self.marks,
balances: self.balances.as_ref(),
balance_width,
let visible = TablePanel {
theme: ctx.theme,
title,
state: ctx.frame,
headers: &headers,
widths: &widths,
rows: rows.iter().map(|row| Row::new(table.cells(row))).collect(),
selected: self.selected,
extent: self.extent(rows.len()),
.draw(buf, area, &self.window, ctx.hits);
let info = self.range_note(visible).unwrap_or_default();
render_info(ctx.theme, area, buf, ctx.frame, &info);
fn draw_notice(buf: &mut Buffer, area: Rect, title: &str, text: &str, ctx: &DrawCtx) {
Panel::new(ctx.theme, title, ctx.frame).render(area, buf);
Paragraph::new(text.to_string()).render(Panel::inner(area), buf);
fn page_of(wire: &str) -> Result<Page, String> {
match parse_wire(wire) {
Ok(WireValue::Value(ref value)) => parse_page(value).map_err(|err| err.to_string()),
Err(RenderError::Server(ErrorReply { code, message, .. })) => {
Err(format!("[{code}] {message}"))
Err(err) => Err(err.to_string()),
/// `Idle` when the page overshot the end, so the caller fetches the last one.
fn parse_page_reply(wire: &str, pager: &mut Pager) -> Fetch<Vec<ListRow>> {
match page_of(wire) {
Ok(page) if pager.accept(&page) => Fetch::Idle,
Ok(page) => Fetch::Loaded(paging::rows(&page)),
Err(message) => Fetch::Error(message),
fn parse_reply(wire: &str, entity_schema: &EntitySchema) -> Fetch<Vec<ListRow>> {
Ok(WireValue::Value(ref v)) => Fetch::Loaded(schema::project_rows(v, entity_schema)),
Fetch::Error(format!("[{code}] {message}"))
Err(e) => Fetch::Error(e.to_string()),
/// Column constraints; the balance column, the last one, takes two fifths so whole amounts fit.
fn column_widths(cols: usize, balance: bool) -> Vec<Constraint> {
let cols = cols.max(1);
if !balance {
return vec![Constraint::Ratio(1, cols as u32); cols];
let mut widths = vec![Constraint::Fill(1); cols - 1];
widths.push(Constraint::Percentage(40));
widths
/// The rows of a table with the state their cells depend on.
struct Rows<'a> {
marks: &'a BTreeSet<String>,
balances: Option<&'a Balances>,
balance_width: usize,
impl Rows<'_> {
fn cells(&self, row: &ListRow) -> Vec<Cell<'static>> {
let marked = row.id.as_ref().is_some_and(|id| self.marks.contains(id));
let balance = self
.balances
.map(|balances| balances.cell(row.id.as_ref(), self.balance_width));
row.cells
.iter()
.enumerate()
.map(|(i, c)| marked_cell(c, i == 0, marked, self.marks.is_empty()))
.chain(balance)
.map(Cell::from)
.collect()
/// The first cell carries the mark gutter once any row is marked.
fn marked_cell(cell: &str, first: bool, marked: bool, no_marks: bool) -> String {
match (first, marked, no_marks) {
(true, true, _) => format!("* {cell}"),
(true, false, false) => format!(" {cell}"),
_ => cell.to_string(),
#[cfg(test)]
mod panel_tests;
mod tests;