1
//! A multi-line field: its label and a text box of [`TEXT_AREA_ROWS`] rows beside it.
2

            
3
use crate::draw::canvas::Offscreen;
4
use ratatui::layout::{Position, Rect};
5
use tvui::{Label, TextView, Theme};
6

            
7
use crate::widgets::{Editor, TEXT_AREA_ROWS};
8

            
9
pub(in crate::draw) struct TextArea<'a> {
10
    label: String,
11
    column: u16,
12
    editor: &'a Editor,
13
    lines: Vec<&'a str>,
14
    cursor: (usize, usize),
15
    focused: bool,
16
}
17

            
18
impl<'a> TextArea<'a> {
19
306
    pub fn new(label: String, column: u16, editor: &'a Editor, focused: bool) -> Self {
20
306
        TextArea {
21
306
            label,
22
306
            column,
23
306
            editor,
24
306
            lines: editor.text_lines(),
25
306
            cursor: editor.cursor_position(),
26
306
            focused,
27
306
        }
28
306
    }
29

            
30
612
    pub fn height() -> usize {
31
612
        TEXT_AREA_ROWS
32
612
    }
33

            
34
293
    pub fn width(&self) -> usize {
35
293
        usize::from(self.column) + super::body::INPUT_MIN + 1
36
293
    }
37

            
38
    /// The text box in the value column of the field's `rect`.
39
629
    pub(super) fn area(&self, rect: Rect) -> Rect {
40
629
        let x = rect.x.saturating_add(self.column).min(rect.right());
41
629
        let width = rect.right().saturating_sub(x).saturating_sub(1);
42
629
        let height = u16::try_from(TEXT_AREA_ROWS).unwrap_or(u16::MAX);
43
629
        Rect::new(x, rect.y, width, height.min(rect.height))
44
629
    }
45

            
46
303
    pub fn draw(&self, frame: &mut Offscreen, rect: Rect, theme: &Theme) {
47
303
        let label = Rect::new(rect.x, rect.y, self.column.min(rect.width), 1);
48
303
        frame.render_widget(Label::new(theme, &self.label, self.focused), label);
49
303
        let area = self.area(rect);
50
303
        let mut viewport = self.editor.viewport();
51
303
        let view = TextView::new(theme, &self.lines, self.cursor, self.focused);
52
303
        frame.render_stateful_widget(view, area, &mut viewport);
53
303
        self.editor.set_viewport(viewport);
54
303
    }
55

            
56
    /// The edit position as drawn by the last [`TextArea::draw`].
57
21
    pub fn cursor(&self, rect: Rect) -> Option<Position> {
58
21
        let area = self.area(rect);
59
21
        let at = TextView::cursor(area, &self.lines, self.cursor, self.editor.viewport());
60
21
        (area.width > 0 && area.height > 0).then_some(at)
61
21
    }
62
}