Skip to main content

tui/widgets/
rows.rs

1//! Generic editor for a rows field whose cells are all text or hidden.
2//!
3//! Keys while focused: Tab/BackTab walk the cells and yield to the outer form
4//! at the first and last one, Up/Down change the row, Ctrl+N adds a row below
5//! and Ctrl+D removes the focused one. A printable non-space key on an empty
6//! field starts a row; any other key edits the focused cell.
7
8use forms::{Field, Kind, LINK_CELL, Row, Suggest};
9
10use crate::widgets::grid::{CellId, Grid, Item};
11use crate::widgets::{Editor, SelectWidget, WidgetKind};
12
13/// Whether a rows field's own cells are text, choice or hidden only, so this
14/// widget can edit it; a choice cell is a pick among its options. Any other cell
15/// kind belongs to the splits editor.
16#[must_use]
17pub fn is_text_rows(cells: &[Field]) -> bool {
18    cells.iter().all(|cell| {
19        matches!(
20            cell.kind,
21            Kind::Text { .. } | Kind::Choice { .. } | Kind::Hidden
22        )
23    })
24}
25
26/// One shown cell: typed text, or a pick among a choice field's options.
27#[derive(Debug)]
28enum Cell {
29    Text(Editor),
30    Choice(SelectWidget),
31}
32
33impl Cell {
34    fn loaded(field: &Field, text: &str) -> Self {
35        match field.kind {
36            Kind::Choice { options, default } => {
37                let mut select = SelectWidget::choice(options, default);
38                if !text.is_empty() {
39                    select.select_id(text);
40                }
41                Self::Choice(select)
42            }
43            _ => Self::Text(Editor::with_buffer(text)),
44        }
45    }
46
47    fn value(&self) -> &str {
48        match self {
49            Self::Text(editor) => editor.buffer(),
50            Self::Choice(select) => select.value(),
51        }
52    }
53
54    fn item(&self, focused: bool) -> Item<'_> {
55        match self {
56            Self::Text(editor) => Item::text(
57                editor.buffer().replace('\n', "\u{23ce}"),
58                editor.cursor(),
59                focused,
60            )
61            .scrolled(editor.scroll()),
62            Self::Choice(select) => Item::select(select, focused),
63        }
64    }
65}
66
67#[derive(Debug)]
68struct RowCells {
69    cells: Vec<Cell>,
70    hidden: Row,
71    /// Shown cells the loaded row held as empty text: written back empty, not left out.
72    blank: Vec<&'static str>,
73}
74
75/// Rows of text cells. `row_focus` is `< rows.len()` and `col_focus` is
76/// `< columns().count()` while any row exists.
77#[derive(Debug)]
78pub struct RowsWidget {
79    cells: &'static [Field],
80    rows: Vec<RowCells>,
81    /// Whether the field is part of the values: absent until loaded or edited.
82    present: bool,
83    pub row_focus: usize,
84    pub col_focus: usize,
85}
86
87impl RowsWidget {
88    #[must_use]
89    pub fn new(cells: &'static [Field]) -> Self {
90        Self {
91            cells,
92            rows: Vec::new(),
93            present: false,
94            row_focus: 0,
95            col_focus: 0,
96        }
97    }
98
99    /// The shown cells in descriptor order; the link to a parent row is not one.
100    pub fn columns(&self) -> impl Iterator<Item = &'static Field> + use<> {
101        self.cells.iter().filter(|cell| {
102            cell.key != LINK_CELL && matches!(cell.kind, Kind::Text { .. } | Kind::Choice { .. })
103        })
104    }
105
106    fn column_count(&self) -> usize {
107        self.columns().count()
108    }
109
110    /// The label of cell `key`, if the row defines it.
111    #[must_use]
112    pub fn cell_label(&self, key: &str) -> Option<&'static str> {
113        self.cells
114            .iter()
115            .find(|cell| cell.key == key)
116            .map(|cell| cell.label)
117    }
118
119    /// Replaces the rows; `None` makes the field absent again.
120    pub fn load_rows(&mut self, rows: Option<&[Row]>) {
121        self.present = rows.is_some();
122        self.rows = rows
123            .unwrap_or_default()
124            .iter()
125            .map(|row| self.loaded_row(row))
126            .collect();
127        self.row_focus = 0;
128        self.col_focus = 0;
129    }
130
131    fn loaded_row(&self, row: &Row) -> RowCells {
132        let text = |key: &str| row.get(key).map_or("", String::as_str);
133        RowCells {
134            cells: self
135                .columns()
136                .map(|cell| Cell::loaded(cell, text(cell.key)))
137                .collect(),
138            hidden: self
139                .cells
140                .iter()
141                .filter(|cell| cell.kind == Kind::Hidden)
142                .filter_map(|cell| Some((cell.key.to_string(), row.get(cell.key)?.clone())))
143                .collect(),
144            blank: self
145                .columns()
146                .filter(|cell| row.get(cell.key).is_some_and(String::is_empty))
147                .map(|cell| cell.key)
148                .collect(),
149        }
150    }
151
152    /// The rows as values: empty cells are left out. `None` when absent.
153    #[must_use]
154    pub fn values(&self) -> Option<Vec<Row>> {
155        self.present.then(|| self.rows())
156    }
157
158    /// The rows as values whether or not the field is present.
159    #[must_use]
160    pub fn rows(&self) -> Vec<Row> {
161        self.rows.iter().map(|r| self.row(r)).collect()
162    }
163
164    fn row(&self, row: &RowCells) -> Row {
165        let shown = self
166            .columns()
167            .zip(&row.cells)
168            .map(|(cell, shown)| (cell.key, shown.value()))
169            .filter(|(key, text)| !text.is_empty() || row.blank.contains(key))
170            .map(|(key, text)| (key.to_string(), text.to_string()));
171        let hidden = row.hidden.iter().filter(|(_, text)| !text.is_empty());
172        shown
173            .chain(hidden.map(|(key, text)| (key.clone(), text.clone())))
174            .collect()
175    }
176
177    /// Inserts an empty row after the focused one and focuses its first cell.
178    pub fn add_row(&mut self) {
179        let at = if self.rows.is_empty() {
180            0
181        } else {
182            self.row_focus + 1
183        };
184        let row = self.loaded_row(&Row::new());
185        self.rows.insert(at, row);
186        self.present = true;
187        self.row_focus = at;
188        self.col_focus = 0;
189    }
190
191    /// Removes the focused row; an emptied field stays present.
192    pub fn remove_row(&mut self) {
193        if self.row_focus >= self.rows.len() {
194            return;
195        }
196        self.rows.remove(self.row_focus);
197        self.row_focus = self.row_focus.min(self.rows.len().saturating_sub(1));
198    }
199
200    pub fn advance_cell(&mut self) {
201        if self.col_focus + 1 < self.column_count() {
202            self.col_focus += 1;
203        } else if self.row_focus + 1 < self.rows.len() {
204            self.row_focus += 1;
205            self.col_focus = 0;
206        }
207    }
208
209    pub fn retreat_cell(&mut self) {
210        if self.col_focus > 0 {
211            self.col_focus -= 1;
212        } else if self.row_focus > 0 {
213            self.row_focus -= 1;
214            self.col_focus = self.column_count().saturating_sub(1);
215        }
216    }
217
218    #[must_use]
219    pub fn at_first_cell(&self) -> bool {
220        self.row_focus == 0 && self.col_focus == 0
221    }
222
223    #[must_use]
224    pub fn at_last_cell(&self) -> bool {
225        self.rows.is_empty()
226            || (self.row_focus + 1 == self.rows.len() && self.col_focus + 1 == self.column_count())
227    }
228
229    #[must_use]
230    pub fn at_first_row(&self) -> bool {
231        self.row_focus == 0
232    }
233
234    #[must_use]
235    pub fn at_last_row(&self) -> bool {
236        self.row_focus + 1 >= self.rows.len()
237    }
238
239    pub fn next_row(&mut self) {
240        self.row_focus = (self.row_focus + 1).min(self.rows.len().saturating_sub(1));
241    }
242
243    pub fn prev_row(&mut self) {
244        self.row_focus = self.row_focus.saturating_sub(1);
245    }
246
247    /// Focuses cell `key` of `row`; an unknown key focuses the row's first cell.
248    pub fn focus_cell(&mut self, row: usize, key: &str) {
249        self.row_focus = row.min(self.rows.len().saturating_sub(1));
250        self.col_focus = self.columns().position(|cell| cell.key == key).unwrap_or(0);
251    }
252
253    /// Focuses the cell at `row` and `col`, both held inside the rows and columns there are.
254    pub fn focus_at(&mut self, row: usize, col: usize) {
255        self.row_focus = row.min(self.rows.len().saturating_sub(1));
256        self.col_focus = col.min(self.column_count().saturating_sub(1));
257    }
258
259    /// The focused cell.
260    #[must_use]
261    pub fn focused_cell(&self) -> CellId {
262        CellId {
263            tag: false,
264            row: self.row_focus,
265            col: self.col_focus,
266        }
267    }
268
269    pub fn focused_editor_mut(&mut self) -> Option<&mut Editor> {
270        match self.focused_cell_mut()? {
271            Cell::Text(editor) => Some(editor),
272            Cell::Choice(_) => None,
273        }
274    }
275
276    #[must_use]
277    pub fn focused_select(&self) -> Option<&SelectWidget> {
278        match self.rows.get(self.row_focus)?.cells.get(self.col_focus)? {
279            Cell::Choice(select) => Some(select),
280            Cell::Text(_) => None,
281        }
282    }
283
284    pub fn focused_select_mut(&mut self) -> Option<&mut SelectWidget> {
285        match self.focused_cell_mut()? {
286            Cell::Choice(select) => Some(select),
287            Cell::Text(_) => None,
288        }
289    }
290
291    fn focused_cell_mut(&mut self) -> Option<&mut Cell> {
292        self.rows
293            .get_mut(self.row_focus)?
294            .cells
295            .get_mut(self.col_focus)
296    }
297
298    /// The widget kind of the focused cell.
299    #[must_use]
300    pub fn focused_kind(&self) -> WidgetKind {
301        match self.columns().nth(self.col_focus).map(|cell| cell.kind) {
302            Some(Kind::Choice { .. }) => WidgetKind::Select,
303            _ => WidgetKind::Text,
304        }
305    }
306
307    /// The descriptor key of the focused cell.
308    #[must_use]
309    pub fn focused_key(&self) -> Option<&'static str> {
310        self.columns().nth(self.col_focus).map(|cell| cell.key)
311    }
312
313    /// What the focused cell asks to be suggested.
314    #[must_use]
315    pub fn focused_suggest(&self) -> Option<Suggest> {
316        match self.columns().nth(self.col_focus)?.kind {
317            Kind::Text { suggest, .. } if !self.rows.is_empty() => suggest,
318            _ => None,
319        }
320    }
321
322    /// The text of cell `key` in the focused row.
323    #[must_use]
324    pub fn focused_text(&self, key: &str) -> &str {
325        let col = self.columns().position(|cell| cell.key == key);
326        let cell = col.and_then(|col| self.rows.get(self.row_focus)?.cells.get(col));
327        cell.map_or("", Cell::value)
328    }
329
330    /// Replaces the focused text cell's content.
331    pub fn set_focused_text(&mut self, text: &str) {
332        if let Some(editor) = self.focused_editor_mut() {
333            *editor = Editor::with_buffer(text);
334        }
335    }
336
337    #[must_use]
338    pub fn is_empty(&self) -> bool {
339        self.rows.is_empty()
340    }
341
342    #[must_use]
343    pub fn display(&self) -> String {
344        format!("{} row(s)", self.rows.len())
345    }
346
347    /// A header line and a line of cells per row, `active` when the field has the focus;
348    /// `suggestion` follows the rows, and an empty field shows `empty`.
349    #[must_use]
350    pub fn grid(&self, active: bool, suggestion: Option<&str>, empty: Option<&str>) -> Grid<'_> {
351        let mut grid = Grid::default();
352        let header = self.columns().map(|cell| Item::label(cell.label));
353        grid.push_cells(0, header.collect());
354        for (at, row) in self.rows.iter().enumerate() {
355            if at == self.row_focus {
356                grid.focus_line = at + 1;
357            }
358            let focus = |col| active && (at, col) == (self.row_focus, self.col_focus);
359            let items = row
360                .cells
361                .iter()
362                .enumerate()
363                .map(|(col, cell)| cell.item(focus(col)).at(at, col));
364            grid.push_cells(0, items.collect());
365        }
366        if let Some(note) = empty.filter(|_| self.rows.is_empty()) {
367            grid.push_note(0, note);
368        }
369        if let Some(line) = suggestion {
370            grid.push_note(0, line);
371        }
372        grid
373    }
374}
375
376/// The note of an empty field of `what`, naming the key that adds one.
377pub fn empty_note(what: &str, add_key: Option<&str>) -> String {
378    let hint = add_key.map_or_else(String::new, |key| format!(": {key} adds one"));
379    format!("(no {what}{hint})")
380}
381
382#[cfg(test)]
383mod tests;