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

            
8
use forms::{Field, Kind, LINK_CELL, Row, Suggest};
9

            
10
use crate::widgets::grid::{CellId, Grid, Item};
11
use 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]
17
815
pub fn is_text_rows(cells: &[Field]) -> bool {
18
2084
    cells.iter().all(|cell| {
19
2084
        matches!(
20
2084
            cell.kind,
21
            Kind::Text { .. } | Kind::Choice { .. } | Kind::Hidden
22
        )
23
2084
    })
24
815
}
25

            
26
/// One shown cell: typed text, or a pick among a choice field's options.
27
#[derive(Debug)]
28
enum Cell {
29
    Text(Editor),
30
    Choice(SelectWidget),
31
}
32

            
33
impl Cell {
34
826
    fn loaded(field: &Field, text: &str) -> Self {
35
826
        match field.kind {
36
            Kind::Choice { options, default } => {
37
123
                let mut select = SelectWidget::choice(options, default);
38
123
                if !text.is_empty() {
39
28
                    select.select_id(text);
40
95
                }
41
123
                Self::Choice(select)
42
            }
43
703
            _ => Self::Text(Editor::with_buffer(text)),
44
        }
45
826
    }
46

            
47
2526
    fn value(&self) -> &str {
48
2526
        match self {
49
2138
            Self::Text(editor) => editor.buffer(),
50
388
            Self::Choice(select) => select.value(),
51
        }
52
2526
    }
53

            
54
55
    fn item(&self, focused: bool) -> Item<'_> {
55
55
        match self {
56
45
            Self::Text(editor) => Item::text(
57
45
                editor.buffer().replace('\n', "\u{23ce}"),
58
45
                editor.cursor(),
59
45
                focused,
60
45
            )
61
45
            .scrolled(editor.scroll()),
62
10
            Self::Choice(select) => Item::select(select, focused),
63
        }
64
55
    }
65
}
66

            
67
#[derive(Debug)]
68
struct 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)]
78
pub 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

            
87
impl RowsWidget {
88
    #[must_use]
89
1173
    pub fn new(cells: &'static [Field]) -> Self {
90
1173
        Self {
91
1173
            cells,
92
1173
            rows: Vec::new(),
93
1173
            present: false,
94
1173
            row_focus: 0,
95
1173
            col_focus: 0,
96
1173
        }
97
1173
    }
98

            
99
    /// The shown cells in descriptor order; the link to a parent row is not one.
100
1774
    pub fn columns(&self) -> impl Iterator<Item = &'static Field> + use<> {
101
6346
        self.cells.iter().filter(|cell| {
102
6346
            cell.key != LINK_CELL && matches!(cell.kind, Kind::Text { .. } | Kind::Choice { .. })
103
6346
        })
104
1774
    }
105

            
106
38
    fn column_count(&self) -> usize {
107
38
        self.columns().count()
108
38
    }
109

            
110
    /// The label of cell `key`, if the row defines it.
111
    #[must_use]
112
5
    pub fn cell_label(&self, key: &str) -> Option<&'static str> {
113
5
        self.cells
114
5
            .iter()
115
10
            .find(|cell| cell.key == key)
116
4
            .map(|cell| cell.label)
117
5
    }
118

            
119
    /// Replaces the rows; `None` makes the field absent again.
120
301
    pub fn load_rows(&mut self, rows: Option<&[Row]>) {
121
301
        self.present = rows.is_some();
122
301
        self.rows = rows
123
301
            .unwrap_or_default()
124
301
            .iter()
125
189
            .map(|row| self.loaded_row(row))
126
            .collect();
127
301
        self.row_focus = 0;
128
301
        self.col_focus = 0;
129
301
    }
130

            
131
242
    fn loaded_row(&self, row: &Row) -> RowCells {
132
826
        let text = |key: &str| row.get(key).map_or("", String::as_str);
133
        RowCells {
134
242
            cells: self
135
242
                .columns()
136
826
                .map(|cell| Cell::loaded(cell, text(cell.key)))
137
                .collect(),
138
242
            hidden: self
139
242
                .cells
140
242
                .iter()
141
966
                .filter(|cell| cell.kind == Kind::Hidden)
142
24
                .filter_map(|cell| Some((cell.key.to_string(), row.get(cell.key)?.clone())))
143
                .collect(),
144
242
            blank: self
145
242
                .columns()
146
826
                .filter(|cell| row.get(cell.key).is_some_and(String::is_empty))
147
46
                .map(|cell| cell.key)
148
                .collect(),
149
        }
150
242
    }
151

            
152
    /// The rows as values: empty cells are left out. `None` when absent.
153
    #[must_use]
154
688
    pub fn values(&self) -> Option<Vec<Row>> {
155
688
        self.present.then(|| self.rows())
156
688
    }
157

            
158
    /// The rows as values whether or not the field is present.
159
    #[must_use]
160
1385
    pub fn rows(&self) -> Vec<Row> {
161
1385
        self.rows.iter().map(|r| self.row(r)).collect()
162
1385
    }
163

            
164
693
    fn row(&self, row: &RowCells) -> Row {
165
693
        let shown = self
166
693
            .columns()
167
693
            .zip(&row.cells)
168
2452
            .map(|(cell, shown)| (cell.key, shown.value()))
169
2452
            .filter(|(key, text)| !text.is_empty() || row.blank.contains(key))
170
1668
            .map(|(key, text)| (key.to_string(), text.to_string()));
171
693
        let hidden = row.hidden.iter().filter(|(_, text)| !text.is_empty());
172
693
        shown
173
693
            .chain(hidden.map(|(key, text)| (key.clone(), text.clone())))
174
            .collect()
175
693
    }
176

            
177
    /// Inserts an empty row after the focused one and focuses its first cell.
178
53
    pub fn add_row(&mut self) {
179
53
        let at = if self.rows.is_empty() {
180
48
            0
181
        } else {
182
5
            self.row_focus + 1
183
        };
184
53
        let row = self.loaded_row(&Row::new());
185
53
        self.rows.insert(at, row);
186
53
        self.present = true;
187
53
        self.row_focus = at;
188
53
        self.col_focus = 0;
189
53
    }
190

            
191
    /// Removes the focused row; an emptied field stays present.
192
15
    pub fn remove_row(&mut self) {
193
15
        if self.row_focus >= self.rows.len() {
194
2
            return;
195
13
        }
196
13
        self.rows.remove(self.row_focus);
197
13
        self.row_focus = self.row_focus.min(self.rows.len().saturating_sub(1));
198
15
    }
199

            
200
35
    pub fn advance_cell(&mut self) {
201
35
        if self.col_focus + 1 < self.column_count() {
202
33
            self.col_focus += 1;
203
2
        } else if self.row_focus + 1 < self.rows.len() {
204
1
            self.row_focus += 1;
205
1
            self.col_focus = 0;
206
1
        }
207
35
    }
208

            
209
3
    pub fn retreat_cell(&mut self) {
210
3
        if self.col_focus > 0 {
211
2
            self.col_focus -= 1;
212
1
        } else if self.row_focus > 0 {
213
1
            self.row_focus -= 1;
214
1
            self.col_focus = self.column_count().saturating_sub(1);
215
        }
216
3
    }
217

            
218
    #[must_use]
219
3
    pub fn at_first_cell(&self) -> bool {
220
3
        self.row_focus == 0 && self.col_focus == 0
221
3
    }
222

            
223
    #[must_use]
224
3
    pub fn at_last_cell(&self) -> bool {
225
3
        self.rows.is_empty()
226
1
            || (self.row_focus + 1 == self.rows.len() && self.col_focus + 1 == self.column_count())
227
3
    }
228

            
229
    #[must_use]
230
11
    pub fn at_first_row(&self) -> bool {
231
11
        self.row_focus == 0
232
11
    }
233

            
234
    #[must_use]
235
11
    pub fn at_last_row(&self) -> bool {
236
11
        self.row_focus + 1 >= self.rows.len()
237
11
    }
238

            
239
3
    pub fn next_row(&mut self) {
240
3
        self.row_focus = (self.row_focus + 1).min(self.rows.len().saturating_sub(1));
241
3
    }
242

            
243
1
    pub fn prev_row(&mut self) {
244
1
        self.row_focus = self.row_focus.saturating_sub(1);
245
1
    }
246

            
247
    /// Focuses cell `key` of `row`; an unknown key focuses the row's first cell.
248
22
    pub fn focus_cell(&mut self, row: usize, key: &str) {
249
22
        self.row_focus = row.min(self.rows.len().saturating_sub(1));
250
50
        self.col_focus = self.columns().position(|cell| cell.key == key).unwrap_or(0);
251
22
    }
252

            
253
    /// Focuses the cell at `row` and `col`, both held inside the rows and columns there are.
254
1
    pub fn focus_at(&mut self, row: usize, col: usize) {
255
1
        self.row_focus = row.min(self.rows.len().saturating_sub(1));
256
1
        self.col_focus = col.min(self.column_count().saturating_sub(1));
257
1
    }
258

            
259
    /// The focused cell.
260
    #[must_use]
261
1
    pub fn focused_cell(&self) -> CellId {
262
1
        CellId {
263
1
            tag: false,
264
1
            row: self.row_focus,
265
1
            col: self.col_focus,
266
1
        }
267
1
    }
268

            
269
98
    pub fn focused_editor_mut(&mut self) -> Option<&mut Editor> {
270
98
        match self.focused_cell_mut()? {
271
95
            Cell::Text(editor) => Some(editor),
272
            Cell::Choice(_) => None,
273
        }
274
98
    }
275

            
276
    #[must_use]
277
170
    pub fn focused_select(&self) -> Option<&SelectWidget> {
278
170
        match self.rows.get(self.row_focus)?.cells.get(self.col_focus)? {
279
38
            Cell::Choice(select) => Some(select),
280
94
            Cell::Text(_) => None,
281
        }
282
170
    }
283

            
284
116
    pub fn focused_select_mut(&mut self) -> Option<&mut SelectWidget> {
285
116
        match self.focused_cell_mut()? {
286
39
            Cell::Choice(select) => Some(select),
287
64
            Cell::Text(_) => None,
288
        }
289
116
    }
290

            
291
214
    fn focused_cell_mut(&mut self) -> Option<&mut Cell> {
292
214
        self.rows
293
214
            .get_mut(self.row_focus)?
294
            .cells
295
198
            .get_mut(self.col_focus)
296
214
    }
297

            
298
    /// The widget kind of the focused cell.
299
    #[must_use]
300
1
    pub fn focused_kind(&self) -> WidgetKind {
301
1
        match self.columns().nth(self.col_focus).map(|cell| cell.kind) {
302
1
            Some(Kind::Choice { .. }) => WidgetKind::Select,
303
            _ => WidgetKind::Text,
304
        }
305
1
    }
306

            
307
    /// The descriptor key of the focused cell.
308
    #[must_use]
309
71
    pub fn focused_key(&self) -> Option<&'static str> {
310
71
        self.columns().nth(self.col_focus).map(|cell| cell.key)
311
71
    }
312

            
313
    /// What the focused cell asks to be suggested.
314
    #[must_use]
315
97
    pub fn focused_suggest(&self) -> Option<Suggest> {
316
97
        match self.columns().nth(self.col_focus)?.kind {
317
81
            Kind::Text { suggest, .. } if !self.rows.is_empty() => suggest,
318
24
            _ => None,
319
        }
320
97
    }
321

            
322
    /// The text of cell `key` in the focused row.
323
    #[must_use]
324
78
    pub fn focused_text(&self, key: &str) -> &str {
325
102
        let col = self.columns().position(|cell| cell.key == key);
326
78
        let cell = col.and_then(|col| self.rows.get(self.row_focus)?.cells.get(col));
327
78
        cell.map_or("", Cell::value)
328
78
    }
329

            
330
    /// Replaces the focused text cell's content.
331
12
    pub fn set_focused_text(&mut self, text: &str) {
332
12
        if let Some(editor) = self.focused_editor_mut() {
333
12
            *editor = Editor::with_buffer(text);
334
        }
335
12
    }
336

            
337
    #[must_use]
338
63
    pub fn is_empty(&self) -> bool {
339
63
        self.rows.is_empty()
340
63
    }
341

            
342
    #[must_use]
343
1
    pub fn display(&self) -> String {
344
1
        format!("{} row(s)", self.rows.len())
345
1
    }
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
289
    pub fn grid(&self, active: bool, suggestion: Option<&str>, empty: Option<&str>) -> Grid<'_> {
351
289
        let mut grid = Grid::default();
352
873
        let header = self.columns().map(|cell| Item::label(cell.label));
353
289
        grid.push_cells(0, header.collect());
354
289
        for (at, row) in self.rows.iter().enumerate() {
355
19
            if at == self.row_focus {
356
16
                grid.focus_line = at + 1;
357
3
            }
358
55
            let focus = |col| active && (at, col) == (self.row_focus, self.col_focus);
359
19
            let items = row
360
19
                .cells
361
19
                .iter()
362
19
                .enumerate()
363
55
                .map(|(col, cell)| cell.item(focus(col)).at(at, col));
364
19
            grid.push_cells(0, items.collect());
365
        }
366
289
        if let Some(note) = empty.filter(|_| self.rows.is_empty()) {
367
273
            grid.push_note(0, note);
368
16
        }
369
289
        if let Some(line) = suggestion {
370
1
            grid.push_note(0, line);
371
288
        }
372
289
        grid
373
289
    }
374
}
375

            
376
/// The note of an empty field of `what`, naming the key that adds one.
377
284
pub fn empty_note(what: &str, add_key: Option<&str>) -> String {
378
284
    let hint = add_key.map_or_else(String::new, |key| format!(": {key} adds one"));
379
284
    format!("(no {what}{hint})")
380
284
}
381

            
382
#[cfg(test)]
383
mod tests;