tvision_rs/widgets/table/
model.rs1use std::borrow::Cow;
5use std::cmp::Ordering;
6use std::fmt;
7
8use crate::theme::Role;
9
10#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
16pub struct RowKey(pub String);
17
18impl RowKey {
19 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#[derive(Clone, Debug, PartialEq)]
51pub enum SortKey {
52 Num(f64),
54 Text(String),
56}
57
58impl SortKey {
59 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 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 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
88pub trait TableModel {
94 fn row_count(&self) -> usize;
96
97 fn cell(&self, row: usize, col: usize) -> Cow<'_, str>;
99
100 fn row_key(&self, row: usize) -> RowKey;
103
104 fn sort_key(&self, row: usize, col: usize) -> SortKey {
108 SortKey::parse(&self.cell(row, col))
109 }
110
111 fn row_role(&self, _row: usize) -> Option<Role> {
115 None
116 }
117
118 fn set_cell(&mut self, _row: usize, _col: usize, _text: &str) -> Result<(), String> {
123 Err("read-only".to_string())
124 }
125}
126
127#[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 pub fn new(rows: Vec<Vec<String>>) -> Self {
142 VecModel {
143 rows,
144 keys: None,
145 roles: Vec::new(),
146 }
147 }
148
149 pub fn with_keys(mut self, keys: Vec<RowKey>) -> Self {
152 self.keys = Some(keys);
153 self
154 }
155
156 pub fn with_row_roles(mut self, roles: Vec<Option<Role>>) -> Self {
160 self.roles = roles;
161 self
162 }
163
164 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 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}