Skip to main content

tui/tabs/list/
balances.rs

1//! The Accounts tab's Balance column cells.
2
3use std::collections::HashMap;
4
5const LOADING: &str = "…";
6const MORE: &str = "+";
7const ZERO: &str = "0";
8const SEPARATOR: &str = ", ";
9
10/// What the Balance column knows: each account's amounts, as whole `10.00 USD` texts.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Balances {
13    Loading,
14    Failed,
15    Ready(HashMap<String, Vec<String>>),
16}
17
18impl Balances {
19    /// The cell of account `id` in a column `width` characters wide.
20    pub fn cell(&self, id: Option<&String>, width: usize) -> String {
21        match self {
22            Self::Loading => LOADING.to_string(),
23            Self::Failed => String::new(),
24            Self::Ready(cells) => match id.and_then(|id| cells.get(id)) {
25                Some(parts) if !parts.is_empty() => fit(parts, width),
26                _ => ZERO.to_string(),
27            },
28        }
29    }
30}
31
32fn width_of(text: &str) -> usize {
33    text.chars().count()
34}
35
36/// Whole amounts only; `+N` counts the amounts that do not fit.
37fn fit(parts: &[String], width: usize) -> String {
38    let all = parts.join(SEPARATOR);
39    if width_of(&all) <= width {
40        return all;
41    }
42    let mut shown = String::new();
43    let mut count = 0;
44    for part in parts {
45        let next = if shown.is_empty() {
46            part.clone()
47        } else {
48            format!("{shown}{SEPARATOR}{part}")
49        };
50        let hidden = parts.len() - count - 1;
51        if width_of(&next) + width_of(SEPARATOR) + width_of(&more(hidden)) > width {
52            break;
53        }
54        shown = next;
55        count += 1;
56    }
57    let hidden = more(parts.len() - count);
58    if shown.is_empty() {
59        hidden
60    } else {
61        format!("{shown}{SEPARATOR}{hidden}")
62    }
63}
64
65fn more(hidden: usize) -> String {
66    format!("{MORE}{hidden}")
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    fn parts(texts: &[&str]) -> Vec<String> {
74        texts.iter().map(ToString::to_string).collect()
75    }
76
77    #[test]
78    fn whole_amounts_that_fit_are_joined() {
79        assert_eq!(fit(&parts(&["1 EUR", "2 USD"]), 20), "1 EUR, 2 USD");
80    }
81
82    #[test]
83    fn an_amount_is_never_cut() {
84        let both = parts(&["12345.50 EUR", "5678.25 USD"]);
85        assert_eq!(fit(&both, 19), "12345.50 EUR, +1");
86        assert_eq!(fit(&both, 13), "+2");
87        assert_eq!(fit(&parts(&["12345678901234567890 USD"]), 10), "+1");
88    }
89
90    #[test]
91    fn cells_distinguish_loading_failed_and_zero() {
92        let id = "a".to_string();
93        assert_eq!(Balances::Loading.cell(Some(&id), 10), "…");
94        assert_eq!(Balances::Failed.cell(Some(&id), 10), "");
95        let ready = Balances::Ready(HashMap::new());
96        assert_eq!(ready.cell(Some(&id), 10), "0");
97        assert_eq!(ready.cell(None, 10), "0");
98    }
99}