1
//! The cell model of a grid field (splits, rows) and its layout.
2
//!
3
//! A grid is lines of items; the columns of the cell lines with one indent align, so a line
4
//! with fewer items leaves the later columns blank.
5

            
6
use std::cell::Cell;
7
use std::collections::BTreeMap;
8

            
9
use ratatui::layout::{Position, Rect};
10
use ratatui::text::Span;
11
use tvui::{ARROW_CELLS, InputLine, Viewport};
12

            
13
use super::SelectWidget;
14

            
15
mod tail;
16
mod width;
17
use width::Width;
18
use width::{Column, frozen_edge, gap, resolve};
19

            
20
/// How far a field's lines sit in from its label.
21
pub const GRID_INDENT: u16 = 4;
22
/// A text cell reserves this much, so typing a usual amount does not reflow the grid.
23
const TEXT_RESERVE: u16 = 10 + ARROW_CELLS;
24
const MIN_SELECT: u16 = 6 + ARROW_CELLS;
25
/// The cells the `▼` mark of a select cell takes at the end of its field.
26
const MARK_CELLS: u16 = 1;
27

            
28
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29
pub enum ItemKind {
30
    Label,
31
    Text,
32
    Select,
33
}
34

            
35
/// The cell of its widget an item edits: a cell of a rows or splits widget, or of the tag list
36
/// a splits widget has open under its split.
37
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38
pub struct CellId {
39
    pub tag: bool,
40
    pub row: usize,
41
    pub col: usize,
42
}
43

            
44
/// One drawn thing of a cell line: a fixed label, a text cell or a select cell.
45
#[derive(Debug, Clone, PartialEq, Eq)]
46
pub struct Item<'a> {
47
    pub kind: ItemKind,
48
    pub text: String,
49
    pub cursor: usize,
50
    pub focused: bool,
51
    /// Whether the terminal cursor shows at `cursor` while the item is focused.
52
    pub caret: bool,
53
    /// The cell a click on the item focuses; labels have none.
54
    pub cell: Option<CellId>,
55
    /// Where the draw of the text keeps its scroll between frames; a label has none.
56
    pub scroll: Option<&'a Cell<Viewport>>,
57
    min: u16,
58
    rule: Width,
59
    frozen: bool,
60
    tail: bool,
61
}
62

            
63
23647
fn width_of(text: &str) -> u16 {
64
23647
    u16::try_from(Span::raw(text).width()).unwrap_or(u16::MAX)
65
23647
}
66

            
67
impl<'a> Item<'a> {
68
    #[must_use]
69
2891
    pub fn label(text: impl Into<String>) -> Self {
70
2891
        Item {
71
2891
            kind: ItemKind::Label,
72
2891
            text: text.into(),
73
2891
            cursor: 0,
74
2891
            focused: false,
75
2891
            caret: false,
76
2891
            cell: None,
77
2891
            scroll: None,
78
2891
            min: 0,
79
2891
            rule: Width::Fit,
80
2891
            frozen: false,
81
2891
            tail: false,
82
2891
        }
83
2891
    }
84

            
85
    /// A text cell with its cursor as a character index.
86
    #[must_use]
87
534
    pub fn text(text: impl Into<String>, cursor: usize, focused: bool) -> Self {
88
534
        Item {
89
534
            kind: ItemKind::Text,
90
534
            text: text.into(),
91
534
            cursor,
92
534
            focused,
93
534
            caret: true,
94
534
            cell: None,
95
534
            scroll: None,
96
534
            min: 0,
97
534
            rule: Width::Fit,
98
534
            frozen: false,
99
534
            tail: false,
100
534
        }
101
534
    }
102

            
103
    /// The item scrolled through `scroll`, the handle of the editor its text is edited in.
104
    #[must_use]
105
474
    pub fn scrolled(mut self, scroll: &'a Cell<Viewport>) -> Self {
106
474
        self.scroll = Some(scroll);
107
474
        self
108
474
    }
109

            
110
    /// A select cell: the typed filter while there is one, else the selected label (`?` when
111
    /// none). The width holds the widest option, so filtering does not reflow the grid.
112
    #[must_use]
113
1617
    pub fn select(select: &'a SelectWidget, focused: bool) -> Self {
114
1617
        let text = match select.shown() {
115
366
            "" => "?",
116
1251
            shown => shown,
117
        };
118
1617
        let widest = select
119
1617
            .options()
120
1617
            .iter()
121
5911
            .map(|option| width_of(&option.label));
122
1617
        let widest = widest.max().unwrap_or(0).max(width_of(select.query()));
123
1617
        Item {
124
1617
            kind: ItemKind::Select,
125
1617
            text: text.to_string(),
126
1617
            cursor: select.query().chars().count(),
127
1617
            focused,
128
1617
            caret: select.open,
129
1617
            cell: None,
130
1617
            scroll: Some(select.scroll()),
131
1617
            min: widest.saturating_add(ARROW_CELLS).max(MIN_SELECT),
132
1617
            rule: Width::Fit,
133
1617
            frozen: false,
134
1617
            tail: false,
135
1617
        }
136
1617
    }
137

            
138
    /// The item as the cell at `row` and `col` of its widget.
139
    #[must_use]
140
2080
    pub fn at(mut self, row: usize, col: usize) -> Self {
141
2080
        self.cell = Some(CellId {
142
2080
            tag: false,
143
2080
            row,
144
2080
            col,
145
2080
        });
146
2080
        self
147
2080
    }
148

            
149
    /// The item in `width` cells whatever it shows, the mark of a select included; a text
150
    /// cell scrolls inside.
151
    #[must_use]
152
1639
    pub fn fixed(mut self, width: u16) -> Self {
153
1639
        self.rule = Width::Fixed(width);
154
1639
        self
155
1639
    }
156

            
157
    /// The item stays in place when its line scrolls to show a focused cell; the leading
158
    /// run of such items is the line's frozen columns.
159
    #[must_use]
160
1201
    pub fn frozen(mut self) -> Self {
161
1201
        self.frozen = true;
162
1201
        self
163
1201
    }
164

            
165
    /// The item in a share of the leftover width, within `min..=max` cells.
166
    #[must_use]
167
799
    pub fn flex(mut self, min: u16, max: u16) -> Self {
168
799
        self.rule = Width::Flex { min, max };
169
799
        self
170
799
    }
171

            
172
    /// A select without a rule sizes to its widest option; text has a column for its cursor.
173
16189
    fn fit_width(&self) -> u16 {
174
16189
        match self.kind {
175
15760
            ItemKind::Label => width_of(&self.text),
176
359
            ItemKind::Text => width_of(&self.text)
177
359
                .saturating_add(ARROW_CELLS)
178
359
                .max(TEXT_RESERVE),
179
70
            ItemKind::Select => self.min.saturating_add(MARK_CELLS),
180
        }
181
16189
    }
182

            
183
    /// The width the item takes when there is room.
184
    #[must_use]
185
29885
    pub fn width(&self) -> u16 {
186
29885
        match self.rule {
187
16189
            Width::Fit => self.fit_width(),
188
10999
            Width::Fixed(width) => width,
189
2697
            Width::Flex { max, .. } => max,
190
        }
191
29885
    }
192

            
193
16285
    fn floor(&self) -> u16 {
194
16285
        match self.rule {
195
2697
            Width::Flex { min, .. } => min,
196
13588
            _ => self.width(),
197
        }
198
16285
    }
199

            
200
    /// The part of the item's `rect` its text is drawn in: a select ends in its `▼` mark.
201
    #[must_use]
202
6990
    pub fn area(&self, rect: Rect) -> Rect {
203
6990
        let mark = if self.kind == ItemKind::Select {
204
5691
            MARK_CELLS
205
        } else {
206
1299
            0
207
        };
208
6990
        Rect {
209
6990
            width: rect.width.saturating_sub(mark),
210
6990
            ..rect
211
6990
        }
212
6990
    }
213
}
214

            
215
#[derive(Debug, Clone, PartialEq, Eq)]
216
pub enum GridLine<'a> {
217
    Text {
218
        indent: u16,
219
        text: String,
220
        focused: bool,
221
    },
222
    Cells {
223
        indent: u16,
224
        items: Vec<Item<'a>>,
225
    },
226
}
227

            
228
impl GridLine<'_> {
229
4293
    fn indent(&self) -> u16 {
230
4293
        match self {
231
4293
            GridLine::Text { indent, .. } | GridLine::Cells { indent, .. } => *indent,
232
        }
233
4293
    }
234

            
235
943
    fn indented(mut self, by: u16) -> Self {
236
943
        match &mut self {
237
            GridLine::Text { indent, .. } | GridLine::Cells { indent, .. } => {
238
943
                *indent = indent.saturating_add(by);
239
            }
240
        }
241
943
        self
242
943
    }
243

            
244
4512
    fn frozen_count(&self) -> usize {
245
4512
        match self {
246
1813
            GridLine::Text { .. } => 0,
247
8588
            GridLine::Cells { items, .. } => items.iter().take_while(|item| item.frozen).count(),
248
        }
249
4512
    }
250

            
251
28
    fn len(&self) -> usize {
252
28
        match self {
253
10
            GridLine::Text { .. } => 1,
254
18
            GridLine::Cells { items, .. } => items.len(),
255
        }
256
28
    }
257

            
258
    /// The `(left, width)` of each item in the line, from the grid's left edge.
259
4600
    fn spans(&self, widths: &[u16]) -> Vec<(u16, u16)> {
260
4600
        match self {
261
1813
            GridLine::Text { indent, .. } => vec![(*indent, u16::MAX)],
262
            GridLine::Cells { indent, items } => {
263
2787
                let mut x = *indent;
264
2787
                let columns = items.iter().zip(widths);
265
2787
                columns
266
21166
                    .map(|(_, &width)| {
267
21166
                        let span = (x, width);
268
21166
                        x = x.saturating_add(width).saturating_add(gap(width));
269
21166
                        span
270
21166
                    })
271
                    .collect()
272
            }
273
        }
274
4600
    }
275

            
276
    /// The item rects in `strip`, cut to it on the right. The columns after the first `frozen`
277
    /// shift left by `shift`; with frozen columns one cut on the left is clipped at the frozen
278
    /// edge, without them it has an empty rect.
279
3442
    fn rects(&self, strip: Rect, widths: &[u16], shift: u16) -> Vec<Rect> {
280
3442
        let frozen = self.frozen_count();
281
3442
        let spans = self.spans(widths);
282
3442
        let edge = frozen_edge(&spans, frozen);
283
13650
        let cut = |(at, (left, width)): (usize, (u16, u16))| {
284
13650
            let scrolled = at >= frozen;
285
13650
            let by = if scrolled { shift } else { 0 };
286
13650
            if frozen == 0 && left < by {
287
21
                return Rect::new(strip.x, strip.y, 0, 1);
288
13629
            }
289
13629
            let start = if scrolled { edge } else { 0 };
290
13629
            let from = left.saturating_sub(by).max(start).min(strip.width);
291
13629
            let to = left
292
13629
                .saturating_add(width)
293
13629
                .saturating_sub(by)
294
13629
                .min(strip.width);
295
13629
            let wide = to.saturating_sub(from);
296
13629
            Rect::new(strip.x.saturating_add(from), strip.y, wide, 1)
297
13650
        };
298
3442
        spans.into_iter().enumerate().map(cut).collect()
299
3442
    }
300
}
301

            
302
#[derive(Debug, Clone, Default, PartialEq, Eq)]
303
pub struct Grid<'a> {
304
    pub lines: Vec<GridLine<'a>>,
305
    /// The line to keep in view.
306
    pub focus_line: usize,
307
}
308

            
309
impl<'a> Grid<'a> {
310
749
    pub fn push_cells(&mut self, indent: u16, items: Vec<Item<'a>>) {
311
749
        self.lines.push(GridLine::Cells { indent, items });
312
749
    }
313

            
314
277
    pub fn push_note(&mut self, indent: u16, text: impl Into<String>) {
315
277
        self.lines.push(GridLine::Text {
316
277
            indent,
317
277
            text: text.into(),
318
277
            focused: false,
319
277
        });
320
277
    }
321

            
322
    /// Add the lines of `other`, `indent` further in; the view follows them when `focused`.
323
554
    pub fn append(&mut self, other: Grid<'a>, indent: u16, focused: bool) {
324
554
        if focused {
325
554
            self.focus_line = self.lines.len() + other.focus_line;
326
        }
327
554
        self.lines
328
943
            .extend(other.lines.into_iter().map(|line| line.indented(indent)));
329
554
    }
330

            
331
    /// The grid under a `title` line, its lines in by [`GRID_INDENT`].
332
    #[must_use]
333
541
    pub fn titled(self, title: impl Into<String>, focused: bool) -> Self {
334
541
        let mut titled = Grid::default();
335
541
        titled.lines.push(GridLine::Text {
336
541
            indent: 0,
337
541
            text: title.into(),
338
541
            focused,
339
541
        });
340
541
        titled.append(self, GRID_INDENT, true);
341
541
        titled
342
541
    }
343

            
344
    /// The grid with every cell id taken as a cell of the open tag list.
345
    #[must_use]
346
13
    pub fn of_tags(mut self) -> Self {
347
13
        for line in &mut self.lines {
348
26
            if let GridLine::Cells { items, .. } = line {
349
84
                for cell in items.iter_mut().filter_map(|item| item.cell.as_mut()) {
350
32
                    cell.tag = true;
351
                }
352
5
            }
353
        }
354
13
        self
355
13
    }
356

            
357
    /// The width of each column of the cell lines of each indent: the flexible ones share what
358
    /// `avail` columns leave over, with no `avail` every column has the width it wants.
359
1829
    fn column_widths(&self, avail: Option<u16>) -> BTreeMap<u16, Vec<u16>> {
360
1829
        let mut columns: BTreeMap<u16, Vec<Column>> = BTreeMap::new();
361
1829
        for line in &self.lines {
362
4864
            let GridLine::Cells { indent, items } = line else {
363
2594
                continue;
364
            };
365
2270
            let group = columns.entry(*indent).or_default();
366
2270
            if group.len() < items.len() {
367
1870
                group.resize(items.len(), Column::default());
368
400
            }
369
2270
            for (column, item) in group.iter_mut().zip(items) {
370
16283
                column.absorb(item);
371
            }
372
        }
373
1870
        let resolved = |(indent, group): (u16, Vec<Column>)| {
374
            (
375
1870
                indent,
376
1870
                resolve(&group, avail.map(|a| a.saturating_sub(indent))),
377
            )
378
1870
        };
379
1829
        columns.into_iter().map(resolved).collect()
380
1829
    }
381

            
382
    /// The columns the grid needs: the far edge of its widest line.
383
    #[must_use]
384
521
    pub fn width(&self) -> usize {
385
521
        let widths = self.column_widths(None);
386
1394
        let ends = self.lines.iter().map(|line| match line {
387
771
            GridLine::Text { indent, text, .. } => usize::from(*indent) + Span::raw(text).width(),
388
            GridLine::Cells { indent, .. } => {
389
623
                let spans = line.spans(widths.get(indent).map_or(&[][..], Vec::as_slice));
390
4312
                let edges = spans.iter().filter(|(_, width)| *width > 0);
391
623
                edges
392
3678
                    .map(|(left, width)| usize::from(*left) + usize::from(*width))
393
                    .max()
394
623
                    .unwrap_or(0)
395
            }
396
1394
        });
397
521
        ends.max().unwrap_or(0)
398
521
    }
399

            
400
    /// The indent of the column group holding the focused cell and how far to shift its
401
    /// columns after the frozen ones left to bring the cell fully into `width` columns, never
402
    /// past the frozen ones; the columns stay aligned.
403
1308
    fn focus_shift(&self, widths: &BTreeMap<u16, Vec<u16>>, width: u16) -> Option<(u16, u16)> {
404
3335
        self.lines.iter().find_map(|line| {
405
3335
            let GridLine::Cells { indent, items } = line else {
406
1823
                return None;
407
            };
408
8392
            let index = items.iter().position(|item| item.focused)?;
409
535
            let spans = line.spans(widths.get(indent)?);
410
535
            let (left, cell) = *spans.get(index)?;
411
535
            let edge = frozen_edge(&spans, line.frozen_count());
412
535
            let over = left.saturating_add(cell).saturating_sub(width);
413
535
            let room = if index < line.frozen_count() {
414
216
                0
415
            } else {
416
319
                left.saturating_sub(edge)
417
            };
418
535
            Some((*indent, over.min(room)))
419
3335
        })
420
1308
    }
421

            
422
    /// The area of every item of every line (one rect for a text line) in `area`, the lines
423
    /// scrolled up by `scroll`. The column group of the focused cell shifts left to show it whole;
424
    /// cells cut at an edge are clipped. A line out of view, or a column beyond the area, gets
425
    /// an empty rect.
426
    #[must_use]
427
1308
    pub fn cell_rects(&self, area: Rect, scroll: u16) -> Vec<Vec<Rect>> {
428
1308
        let widths = self.column_widths(Some(area.width));
429
1308
        let focus = self.focus_shift(&widths, area.width);
430
1308
        let lines = self.lines.iter().enumerate();
431
1308
        lines
432
3470
            .map(|(at, line)| {
433
3470
                let row = at
434
3470
                    .checked_sub(usize::from(scroll))
435
3451
                    .and_then(|row| u16::try_from(row).ok())
436
3451
                    .filter(|&row| row < area.height);
437
3470
                let Some(row) = row else {
438
28
                    return vec![Rect::default(); line.len()];
439
                };
440
3442
                let strip = Rect::new(area.x, area.y + row, area.width, 1);
441
3442
                let columns = widths.get(&line.indent()).map_or(&[][..], Vec::as_slice);
442
3442
                let grouped = matches!(line, GridLine::Cells { .. });
443
3442
                let shift = focus
444
1362
                    .filter(|(indent, _)| grouped && *indent == line.indent())
445
3442
                    .map_or(0, |(_, by)| by);
446
3442
                line.rects(strip, columns, shift)
447
3470
            })
448
            .collect()
449
1308
    }
450

            
451
    /// The focused cell item with its rect.
452
218
    fn focused<'b>(&'b self, rects: &'b [Vec<Rect>]) -> Option<(&'b Item<'a>, Rect)> {
453
499
        let cells = self.lines.iter().zip(rects).filter_map(|(line, rects)| {
454
499
            let GridLine::Cells { items, .. } = line else {
455
214
                return None;
456
            };
457
285
            Some(items.iter().zip(rects))
458
499
        });
459
218
        cells
460
218
            .flatten()
461
1627
            .find(|(item, _)| item.focused)
462
214
            .map(|(item, rect)| (item, *rect))
463
218
    }
464

            
465
    /// The terminal cursor: at the edit position of the focused cell, when it has one in view.
466
    #[must_use]
467
164
    pub fn caret(&self, rects: &[Vec<Rect>]) -> Option<Position> {
468
164
        let (item, rect) = self.focused(rects)?;
469
160
        let area = item.area(rect);
470
160
        (item.caret && area.width > 0).then(|| {
471
113
            InputLine::cursor(
472
113
                area,
473
113
                &item.text,
474
113
                item.cursor,
475
113
                item.scroll.map_or_else(Viewport::default, Cell::get),
476
113
            )
477
113
        })
478
164
    }
479

            
480
    /// The rect of the focused select cell, which its list opens under.
481
    #[must_use]
482
54
    pub fn anchor(&self, rects: &[Vec<Rect>]) -> Option<Rect> {
483
54
        let (item, rect) = self.focused(rects)?;
484
54
        (item.kind == ItemKind::Select).then_some(rect)
485
54
    }
486
}
487

            
488
#[cfg(test)]
489
mod tests;