1
//! The body of a form dialog: one block per field, each in its own area.
2

            
3
use std::cell::Cell;
4

            
5
use crate::draw::canvas::Offscreen;
6
use ratatui::layout::{Position, Rect};
7
use ratatui::text::Line;
8
use ratatui::widgets::{ListState, Paragraph};
9
use tvui::{
10
    ARROW_CELLS, Button, ButtonRow, Dialog, DropDown, HISTORY_CELLS, History, InputLine, Label,
11
    RowWindow, Theme, Viewport, dropdown_area, scrollbar_parts,
12
};
13

            
14
use super::grid::{draw_grid, record_cells};
15
use super::text_area::TextArea;
16
use crate::draw::modal::{record_buttons, scroll_to};
17
use crate::hits::{Hits, Surface, Target};
18
use crate::widgets::grid::Grid;
19

            
20
pub(super) const INPUT_MIN: usize = 20 + ARROW_CELLS as usize;
21
const MAX_VISIBLE_OPTIONS: usize = 8;
22

            
23
/// A one-line field: its label and the text the value column shows; a `combo` ends in the
24
/// `▐↓▌` history mark. The terminal cursor shows at `cursor` when the field has a `caret`.
25
pub(in crate::draw) struct Input<'a> {
26
    pub label: String,
27
    pub column: u16,
28
    pub text: String,
29
    pub cursor: usize,
30
    pub scroll: Option<&'a Cell<Viewport>>,
31
    pub focused: bool,
32
    pub combo: bool,
33
    pub caret: bool,
34
}
35

            
36
/// The open list of the focused select: the labels of the options matching its filter and
37
/// the highlighted one.
38
pub(in crate::draw) struct Popup<'a> {
39
    pub labels: Vec<String>,
40
    pub selected: usize,
41
    pub window: &'a RowWindow,
42
}
43

            
44
pub(in crate::draw) enum Block<'a> {
45
    Text(TextArea<'a>),
46
    Input(Input<'a>),
47
    Grid(Grid<'a>),
48
}
49

            
50
impl Input<'_> {
51
    /// The value column, history mark included.
52
1722
    fn field(&self, rect: Rect) -> Rect {
53
1722
        let x = rect.x.saturating_add(self.column).min(rect.right());
54
1722
        let width = rect.right().saturating_sub(x).saturating_sub(1);
55
1722
        Rect::new(x, rect.y, width, 1)
56
1722
    }
57

            
58
    /// The part of the field the text is drawn in.
59
1453
    fn area(&self, rect: Rect) -> Rect {
60
1453
        let field = self.field(rect);
61
1453
        let marker = if self.combo { HISTORY_CELLS } else { 0 };
62
1453
        Rect::new(field.x, field.y, field.width.saturating_sub(marker), 1)
63
1453
    }
64

            
65
653
    fn width(&self) -> usize {
66
653
        let mark = if self.combo { HISTORY_CELLS } else { 0 };
67
653
        usize::from(self.column) + INPUT_MIN + 1 + usize::from(mark)
68
653
    }
69
}
70

            
71
impl Block<'_> {
72
3040
    fn height(&self) -> usize {
73
3040
        match self {
74
612
            Block::Text(_) => TextArea::height(),
75
1350
            Block::Input(_) => 1,
76
1078
            Block::Grid(grid) => grid.lines.len(),
77
        }
78
3040
    }
79

            
80
1461
    fn width(&self) -> usize {
81
1461
        match self {
82
293
            Block::Text(text) => text.width(),
83
653
            Block::Input(input) => input.width(),
84
515
            Block::Grid(grid) => grid.width(),
85
        }
86
1461
    }
87
}
88

            
89
pub(in crate::draw) struct FormBody<'a> {
90
    pub title: &'static str,
91
    pub notices: Vec<Line<'static>>,
92
    pub blocks: Vec<Block<'a>>,
93
    pub tail: Vec<Line<'static>>,
94
    pub focus: usize,
95
    pub button: Option<usize>,
96
    pub pressed: Option<usize>,
97
    pub dragging: bool,
98
    pub active: bool,
99
    pub popup: Option<Popup<'a>>,
100
}
101

            
102
/// The area of each part of a form body.
103
pub(in crate::draw) struct Rects {
104
    pub notices: Rect,
105
    pub fields: Vec<Rect>,
106
    pub tail: Rect,
107
}
108

            
109
impl FormBody<'_> {
110
442
    pub fn widest(&self) -> usize {
111
442
        let widths = self.notices.iter().chain(&self.tail).map(Line::width);
112
442
        widths
113
442
            .chain(self.blocks.iter().map(Block::width))
114
442
            .max()
115
442
            .unwrap_or(0)
116
442
    }
117

            
118
457
    pub fn height(&self) -> usize {
119
457
        let fields: usize = self.blocks.iter().map(Block::height).sum();
120
457
        self.notices.len() + fields + self.tail.len()
121
457
    }
122

            
123
    /// Rows of the notices, then of each field, then of the tail.
124
459
    fn heights(&self) -> Vec<u16> {
125
2440
        let rows = |n: usize| u16::try_from(n).unwrap_or(u16::MAX);
126
459
        let fields = self.blocks.iter().map(Block::height);
127
459
        let all = std::iter::once(self.notices.len())
128
459
            .chain(fields)
129
459
            .chain(std::iter::once(self.tail.len()));
130
459
        all.map(rows).collect()
131
459
    }
132

            
133
    /// The terminal cursor: at the edit position of the focused field in view.
134
456
    pub fn cursor(&self, rects: &Rects) -> Option<Position> {
135
456
        let rect = rects
136
456
            .fields
137
456
            .get(self.focus)
138
449
            .filter(|rect| rect.height > 0)?;
139
449
        match self.blocks.get(self.focus)? {
140
269
            Block::Input(input) if input.caret => {
141
233
                let area = input.area(*rect);
142
233
                (area.width > 0).then(|| {
143
233
                    InputLine::cursor(
144
233
                        area,
145
233
                        &input.text,
146
233
                        input.cursor,
147
233
                        input.scroll.map_or_else(Viewport::default, Cell::get),
148
233
                    )
149
233
                })
150
            }
151
159
            Block::Grid(grid) => grid.caret(&grid_rects(grid, *rect, true)),
152
21
            Block::Text(text) => text.cursor(*rect),
153
36
            Block::Input(_) => None,
154
        }
155
456
    }
156
}
157

            
158
/// The cell areas of a grid in its field `rect`, scrolled by rows to the focused line when
159
/// `current`.
160
1282
fn grid_rects(grid: &Grid<'_>, rect: Rect, current: bool) -> Vec<Vec<Rect>> {
161
1282
    let scroll = if current {
162
528
        scroll_to(grid.focus_line, rect.height)
163
    } else {
164
754
        0
165
    };
166
1282
    grid.cell_rects(rect, scroll)
167
1282
}
168

            
169
/// Draws `field`, which scrolls through `scroll` and leaves it where the draw ended.
170
2456
pub(super) fn draw_input(
171
2456
    frame: &mut Offscreen,
172
2456
    field: InputLine<'_>,
173
2456
    area: Rect,
174
2456
    scroll: Option<&Cell<Viewport>>,
175
2456
) {
176
2456
    let mut viewport = scroll.map_or_else(Viewport::default, Cell::get);
177
2456
    frame.render_stateful_widget(field, area, &mut viewport);
178
2456
    if let Some(scroll) = scroll {
179
2456
        scroll.set(viewport);
180
    }
181
2456
}
182

            
183
/// Stack the body in `area`, scrolled by whole fields from the top just far enough to show
184
/// the focused one; what does not fit is cut off or left out with an empty area.
185
459
pub(in crate::draw) fn field_rects(body: &FormBody<'_>, area: Rect) -> Rects {
186
459
    let heights = body.heights();
187
459
    let focused = body.focus.min(body.blocks.len().saturating_sub(1)) + 1;
188
1515
    let span = |top: usize| -> u32 { heights[top..=focused].iter().map(|&h| u32::from(h)).sum() };
189
459
    let mut top = 0;
190
469
    while top < focused && span(top) > u32::from(area.height) {
191
10
        top += 1;
192
    }
193
459
    let mut y = area.y;
194
459
    let mut rects = vec![Rect::new(area.x, area.y, area.width, 0); heights.len()];
195
459
    for (rect, &height) in rects.iter_mut().zip(&heights).skip(top) {
196
2430
        let height = height.min(area.bottom().saturating_sub(y));
197
2430
        *rect = Rect::new(area.x, y, area.width, height);
198
2430
        y += height;
199
    }
200
459
    let tail = rects.pop().unwrap_or_default();
201
459
    let fields = rects.split_off(1);
202
459
    Rects {
203
459
        notices: rects.first().copied().unwrap_or_default(),
204
459
        fields,
205
459
        tail,
206
459
    }
207
459
}
208

            
209
912
fn draw_lines(frame: &mut Offscreen, lines: &[Line<'static>], rect: Rect) {
210
912
    if rect.height > 0 {
211
287
        frame.render_widget(Paragraph::new(lines.to_vec()), rect);
212
625
    }
213
912
}
214

            
215
1514
fn draw_block(frame: &mut Offscreen, block: &Block<'_>, rect: Rect, current: bool, theme: &Theme) {
216
1514
    if rect.height == 0 {
217
7
        return;
218
1507
    }
219
1507
    match block {
220
303
        Block::Text(text) => text.draw(frame, rect, theme),
221
535
        Block::Grid(grid) => draw_grid(frame, grid, &grid_rects(grid, rect, current), theme),
222
        Block::Input(input) => {
223
669
            let label = Rect::new(rect.x, rect.y, input.column.min(rect.width), 1);
224
669
            frame.render_widget(Label::new(theme, &input.label, input.focused), label);
225
669
            let field = InputLine::new(theme, &input.text, input.cursor, input.focused);
226
669
            draw_input(frame, field, input.area(rect), input.scroll);
227
669
            if input.combo {
228
121
                frame.render_widget(History::new(theme), input.field(rect));
229
548
            }
230
        }
231
    }
232
1514
}
233

            
234
/// The dialog of a form: frame, buttons and the body; the terminal cursor goes to the
235
/// focused one-line field when `with_cursor`.
236
456
pub(in crate::draw) fn draw_form(
237
456
    frame: &mut Offscreen,
238
456
    area: Rect,
239
456
    body: &FormBody<'_>,
240
456
    buttons: &[Button<'_>],
241
456
    theme: &Theme,
242
456
    with_cursor: bool,
243
456
    hits: &mut Hits,
244
456
) {
245
456
    let dialog = Dialog::new(theme, body.title, buttons)
246
456
        .focused(body.button)
247
456
        .pressed(body.pressed)
248
456
        .dragging(body.dragging)
249
456
        .inactive(!body.active)
250
456
        .row(ButtonRow::BottomRight);
251
456
    frame.render_widget(dialog, area);
252
456
    let rects = field_rects(body, Dialog::body_area(area));
253
456
    draw_lines(frame, &body.notices, rects.notices);
254
456
    for (i, (block, rect)) in body.blocks.iter().zip(&rects.fields).enumerate() {
255
1514
        draw_block(frame, block, *rect, i == body.focus, theme);
256
    }
257
456
    draw_lines(frame, &body.tail, rects.tail);
258
456
    record_buttons(hits, area, buttons, ButtonRow::BottomRight);
259
456
    for (i, (block, rect)) in body.blocks.iter().zip(&rects.fields).enumerate() {
260
1514
        hits.push(*rect, Target::Field(i));
261
1514
        record_block(hits, i, block, *rect, i == body.focus);
262
    }
263
456
    if let Some(popup) = &body.popup {
264
78
        draw_popup(frame, body, &rects, popup, theme, hits);
265
378
    }
266
456
    if let (true, Some(at)) = (with_cursor, body.cursor(&rects)) {
267
332
        frame.set_cursor_position(at);
268
124
    }
269
456
}
270

            
271
/// What a click can do inside field `field`'s block in `rect`: place the caret in its text, or
272
/// open the list of its `▐↓▌` mark.
273
1514
fn record_block(hits: &mut Hits, field: usize, block: &Block<'_>, rect: Rect, current: bool) {
274
1514
    let cell = None;
275
1514
    match block {
276
672
        Block::Input(input) if input.combo => {
277
121
            hits.push(
278
121
                History::area(input.field(rect)),
279
121
                Target::Mark { field, cell },
280
121
            );
281
        }
282
551
        Block::Input(input) => hits.push(input.area(rect), Target::Caret { field, cell }),
283
305
        Block::Text(text) => hits.push(text.area(rect), Target::Caret { field, cell }),
284
537
        Block::Grid(grid) => record_cells(hits, field, grid, &grid_rects(grid, rect, current)),
285
    }
286
1514
}
287

            
288
/// The one-row area the focused select's list opens under, in screen cells.
289
78
fn popup_anchor(block: &Block<'_>, rect: Rect) -> Rect {
290
78
    match block {
291
27
        Block::Input(input) => input.field(rect),
292
51
        Block::Grid(grid) => grid
293
51
            .anchor(&grid_rects(grid, rect, true))
294
            .unwrap_or_else(|| Rect::new(rect.x, rect.y, 0, 1)),
295
        Block::Text(_) => Rect::new(rect.x, rect.y, 0, 1),
296
    }
297
78
}
298

            
299
78
fn draw_popup(
300
78
    frame: &mut Offscreen,
301
78
    body: &FormBody<'_>,
302
78
    rects: &Rects,
303
78
    popup: &Popup<'_>,
304
78
    theme: &Theme,
305
78
    hits: &mut Hits,
306
78
) {
307
78
    let (Some(block), Some(rect)) = (body.blocks.get(body.focus), rects.fields.get(body.focus))
308
    else {
309
        return;
310
    };
311
78
    if rect.height == 0 {
312
        return;
313
78
    }
314
78
    let mut anchor = popup_anchor(block, *rect);
315
78
    anchor.width = anchor.width.max(DropDown::width(&popup.labels));
316
78
    let rows = popup.labels.len().clamp(1, MAX_VISIBLE_OPTIONS);
317
78
    let area = dropdown_area(
318
78
        anchor,
319
78
        u16::try_from(rows).unwrap_or(u16::MAX),
320
78
        frame.area(),
321
78
    );
322
78
    let mut state = ListState::default()
323
78
        .with_offset(popup.window.top())
324
78
        .with_selected(Some(popup.selected));
325
78
    frame.render_stateful_widget(DropDown::new(theme, &popup.labels), area, &mut state);
326
78
    popup.window.set_top(state.offset());
327
78
    let view = usize::from(DropDown::rows(area).height);
328
78
    let top = popup.window.fit(popup.labels.len(), view);
329
78
    record_popup(hits, area, top, (popup.labels.len(), view));
330
78
}
331

            
332
/// The box of the open list, its options and its scrollbar parts.
333
78
fn record_popup(hits: &mut Hits, area: Rect, top: usize, (len, view): (usize, usize)) {
334
78
    hits.push(area, Target::Body(Surface::Options));
335
78
    for (index, rect) in DropDown::option_rows(area, top, len) {
336
378
        hits.push(rect, Target::Option(index));
337
    }
338
78
    for (rect, part) in scrollbar_parts(area, (len, view, top)) {
339
136
        hits.push(rect, Target::Scroll(Surface::Options, part));
340
    }
341
78
}