Guide API
Skip to main content

tvision_rs/widgets/table/
model.rs

1//! The table's data source: the [`TableModel`] trait, its row identity
2//! [`RowKey`], the sort currency [`SortKey`], and the ready-made [`VecModel`].
3
4use std::borrow::Cow;
5use std::cmp::Ordering;
6use std::fmt;
7
8use crate::theme::Role;
9
10/// The stable identity of a table row.
11///
12/// Focus and the multi-selection follow the key, not the row position, so a
13/// reload ([`Table::set_model`](super::Table::set_model)) or a re-sort keeps the
14/// user on the same record. Keys must be unique within one model.
15#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct RowKey(pub String);
17
18impl RowKey {
19    /// The key as text.
20    pub fn as_str(&self) -> &str {
21        &self.0
22    }
23}
24
25impl From<&str> for RowKey {
26    fn from(s: &str) -> Self {
27        RowKey(s.to_string())
28    }
29}
30
31impl From<String> for RowKey {
32    fn from(s: String) -> Self {
33        RowKey(s)
34    }
35}
36
37impl fmt::Display for RowKey {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        f.write_str(&self.0)
40    }
41}
42
43/// The value a column sorts by.
44///
45/// Numbers sort before text in **both** directions (a descending sort
46/// reverses numbers among themselves and texts among themselves, never the
47/// two groups). Two numbers compare numerically, two texts as strings. Only
48/// finite numbers come out of [`parse`](Self::parse); a NaN that a model
49/// supplies itself sorts after every other number.
50#[derive(Clone, Debug, PartialEq)]
51pub enum SortKey {
52    /// A numeric key — `"10.2"` sorts after `"9.9"`.
53    Num(f64),
54    /// A text key, compared as a plain string.
55    Text(String),
56}
57
58impl SortKey {
59    /// Parse `cell` (trimmed) as a finite number; anything else, including
60    /// `"nan"`, `"inf"` and `"infinity"`, stays text.
61    pub fn parse(cell: &str) -> SortKey {
62        match cell.trim().parse::<f64>() {
63            Ok(n) if n.is_finite() => SortKey::Num(n),
64            _ => SortKey::Text(cell.to_string()),
65        }
66    }
67
68    /// Whether both keys are of the same kind (both numbers or both text).
69    pub fn same_kind(&self, other: &SortKey) -> bool {
70        matches!(
71            (self, other),
72            (SortKey::Num(_), SortKey::Num(_)) | (SortKey::Text(_), SortKey::Text(_))
73        )
74    }
75
76    /// The total sort order: numbers before text, numbers by value, text by
77    /// string order.
78    pub fn compare(&self, other: &SortKey) -> Ordering {
79        match (self, other) {
80            (SortKey::Num(a), SortKey::Num(b)) => a.total_cmp(b),
81            (SortKey::Num(_), SortKey::Text(_)) => Ordering::Less,
82            (SortKey::Text(_), SortKey::Num(_)) => Ordering::Greater,
83            (SortKey::Text(a), SortKey::Text(b)) => a.cmp(b),
84        }
85    }
86}
87
88/// The rows a [`Table`](super::Table) shows.
89///
90/// The table never reorders the model: it keeps its own row permutation for
91/// the current sort. Implement this over your own records to avoid copying
92/// them into strings up front; [`VecModel`] covers the plain-strings case.
93pub trait TableModel {
94    /// Number of rows.
95    fn row_count(&self) -> usize;
96
97    /// The text of cell (`row`, `col`). An out-of-range column yields `""`.
98    fn cell(&self, row: usize, col: usize) -> Cow<'_, str>;
99
100    /// Stable identity of a row; focus and selection follow the key across
101    /// reloads.
102    fn row_key(&self, row: usize) -> RowKey;
103
104    /// Sort key of cell (`row`, `col`). The default parses the cell as a
105    /// number and falls back to its text; override it when the displayed
106    /// text is not what should sort (`"10.2%"`, `"3 days ago"`).
107    fn sort_key(&self, row: usize, col: usize) -> SortKey {
108        SortKey::parse(&self.cell(row, col))
109    }
110
111    /// Optional theme role for the whole row (e.g. a dimmed or an error row).
112    /// It replaces only the normal row colour: the focused and the selected
113    /// colours still win.
114    fn row_role(&self, _row: usize) -> Option<Role> {
115        None
116    }
117
118    /// Store `text` in cell (`row`, `col`) — a cell editor committing on an
119    /// [`editable`](super::ColumnSpec::editable) column. `Err(message)`
120    /// refuses the text: the table shows `message` in an error box and keeps
121    /// the editor open. The default refuses every edit with `"read-only"`.
122    fn set_cell(&mut self, _row: usize, _col: usize, _text: &str) -> Result<(), String> {
123        Err("read-only".to_string())
124    }
125}
126
127/// A [`TableModel`] over `Vec<Vec<String>>`.
128///
129/// Rows are keyed by their index as text unless keys are supplied with
130/// [`with_keys`](Self::with_keys); give real keys whenever the rows can be
131/// reloaded in a different order, or focus cannot follow the record.
132#[derive(Clone, Debug, Default)]
133pub struct VecModel {
134    rows: Vec<Vec<String>>,
135    keys: Option<Vec<RowKey>>,
136    roles: Vec<Option<Role>>,
137}
138
139impl VecModel {
140    /// A model over `rows`, keyed by row index.
141    pub fn new(rows: Vec<Vec<String>>) -> Self {
142        VecModel {
143            rows,
144            keys: None,
145            roles: Vec::new(),
146        }
147    }
148
149    /// Builder: one key per row, index-aligned with the rows. A row without a
150    /// key (the vector is too short) falls back to its index.
151    pub fn with_keys(mut self, keys: Vec<RowKey>) -> Self {
152        self.keys = Some(keys);
153        self
154    }
155
156    /// Builder: one optional row role per row, index-aligned with the rows
157    /// (see [`TableModel::row_role`]). A shorter vector leaves the remaining
158    /// rows plain.
159    pub fn with_row_roles(mut self, roles: Vec<Option<Role>>) -> Self {
160        self.roles = roles;
161        self
162    }
163
164    /// The rows.
165    pub fn rows(&self) -> &[Vec<String>] {
166        &self.rows
167    }
168}
169
170impl TableModel for VecModel {
171    fn row_count(&self) -> usize {
172        self.rows.len()
173    }
174
175    fn cell(&self, row: usize, col: usize) -> Cow<'_, str> {
176        self.rows
177            .get(row)
178            .and_then(|r| r.get(col))
179            .map_or(Cow::Borrowed(""), |s| Cow::Borrowed(s.as_str()))
180    }
181
182    fn row_key(&self, row: usize) -> RowKey {
183        self.keys
184            .as_ref()
185            .and_then(|k| k.get(row))
186            .cloned()
187            .unwrap_or_else(|| RowKey(row.to_string()))
188    }
189
190    fn row_role(&self, row: usize) -> Option<Role> {
191        self.roles.get(row).copied().flatten()
192    }
193
194    /// Replace the cell's text. A row too short for `col` is padded with
195    /// empty cells; a missing row is an error.
196    fn set_cell(&mut self, row: usize, col: usize, text: &str) -> Result<(), String> {
197        let r = self
198            .rows
199            .get_mut(row)
200            .ok_or_else(|| format!("no row {row}"))?;
201        if r.len() <= col {
202            r.resize(col + 1, String::new());
203        }
204        r[col] = text.to_string();
205        Ok(())
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn sort_key_parses_numbers_and_falls_back_to_text() {
215        assert_eq!(SortKey::parse(" 10.5 "), SortKey::Num(10.5));
216        assert_eq!(SortKey::parse("-3"), SortKey::Num(-3.0));
217        assert_eq!(SortKey::parse("10.2%"), SortKey::Text("10.2%".into()));
218        assert_eq!(SortKey::parse(""), SortKey::Text(String::new()));
219        for t in ["nan", "NaN", "inf", "-inf", "infinity", "Infinity"] {
220            assert_eq!(SortKey::parse(t), SortKey::Text(t.into()), "{t} is text");
221        }
222    }
223
224    #[test]
225    fn numbers_sort_before_text_and_by_value() {
226        let n = |v| SortKey::Num(v);
227        let t = |s: &str| SortKey::Text(s.into());
228        assert_eq!(n(9.9).compare(&n(10.2)), Ordering::Less);
229        assert_eq!(n(1e9).compare(&t("a")), Ordering::Less);
230        assert_eq!(t("a").compare(&n(0.0)), Ordering::Greater);
231        assert_eq!(t("b").compare(&t("a")), Ordering::Greater);
232        assert_eq!(
233            n(f64::NAN).compare(&n(f64::NAN)),
234            Ordering::Equal,
235            "two NaNs tie, so a stable sort keeps their order"
236        );
237    }
238
239    #[test]
240    fn vec_model_defaults_and_keys() {
241        let m = VecModel::new(vec![vec!["a".into(), "b".into()], vec!["c".into()]]);
242        assert_eq!(m.row_count(), 2);
243        assert_eq!(m.cell(0, 1), "b");
244        assert_eq!(m.cell(1, 1), "", "missing cell is empty");
245        assert_eq!(m.cell(5, 0), "", "missing row is empty");
246        assert_eq!(m.row_key(1), RowKey::from("1"), "index key by default");
247        let m = m.with_keys(vec!["x".into()]);
248        assert_eq!(m.row_key(0), RowKey::from("x"));
249        assert_eq!(m.row_key(1), RowKey::from("1"), "short key list falls back");
250        let m = m.with_row_roles(vec![None, Some(Role::Error)]);
251        assert_eq!(m.row_role(0), None);
252        assert_eq!(m.row_role(1), Some(Role::Error));
253        assert_eq!(m.row_role(2), None);
254    }
255
256    #[test]
257    fn vec_model_set_cell_writes_pads_and_rejects_missing_rows() {
258        let mut m = VecModel::new(vec![vec!["a".into()]]);
259        assert_eq!(m.set_cell(0, 0, "x"), Ok(()));
260        assert_eq!(m.cell(0, 0), "x");
261        assert_eq!(m.set_cell(0, 2, "z"), Ok(()), "a short row is padded");
262        assert_eq!(m.rows()[0], ["x", "", "z"]);
263        assert!(m.set_cell(1, 0, "?").is_err(), "no such row");
264    }
265
266    #[test]
267    fn set_cell_defaults_to_read_only() {
268        struct Fixed;
269        impl TableModel for Fixed {
270            fn row_count(&self) -> usize {
271                1
272            }
273            fn cell(&self, _: usize, _: usize) -> Cow<'_, str> {
274                Cow::Borrowed("v")
275            }
276            fn row_key(&self, _: usize) -> RowKey {
277                RowKey::from("k")
278            }
279        }
280        assert_eq!(Fixed.set_cell(0, 0, "w"), Err("read-only".to_string()));
281    }
282}