1
//! What a click does inside a form: focus a grid cell.
2

            
3
use ratatui::layout::{Position, Rect};
4
use tvui::{InputLine, TextView};
5

            
6
use super::Form;
7
use crate::widgets::Widget;
8
use crate::widgets::grid::CellId;
9

            
10
impl Form {
11
    /// Focuses `cell` of the grid in field `field`; a field that is not a grid changes nothing.
12
57
    pub fn focus_cell(&mut self, field: usize, cell: CellId) {
13
57
        let Some(grid) = self.fields.get_mut(field) else {
14
            return;
15
        };
16
57
        match &mut grid.widget {
17
56
            Widget::Splits(splits) => splits.focus_cell_id(cell),
18
            Widget::Rows(rows) => rows.focus_at(cell.row, cell.col),
19
1
            _ => return,
20
        }
21
56
        self.focus_field(field);
22
57
    }
23

            
24
    /// Puts the caret of the focused text where a click at `point` landed in `area`, the area its
25
    /// text was drawn in through the editor's scroll.
26
27
    pub fn place_caret(&mut self, area: Rect, point: Position) {
27
27
        let Some(editor) = self
28
27
            .fields
29
27
            .get_mut(self.focus)
30
27
            .and_then(|field| field.widget.focused_editor_mut())
31
        else {
32
            return;
33
        };
34
27
        if editor.is_multiline() {
35
7
            let lines = editor.text_lines();
36
7
            let at = TextView::position_at(area, &lines, editor.viewport(), point);
37
7
            editor.set_cursor_position(at);
38
7
            return;
39
20
        }
40
20
        let at = InputLine::position_at(area, editor.buffer(), editor.viewport(), point);
41
20
        editor.set_cursor(at);
42
27
    }
43

            
44
    /// Whether the focus is on `cell` of the grid in field `field`.
45
    #[must_use]
46
70
    pub fn cell_focused(&self, field: usize, cell: CellId) -> bool {
47
70
        if self.focus != field {
48
22
            return false;
49
48
        }
50
48
        match self.fields.get(field).map(|field| &field.widget) {
51
48
            Some(Widget::Splits(splits)) => splits.focused_cell() == cell,
52
            Some(Widget::Rows(rows)) => rows.focused_cell() == cell,
53
            _ => false,
54
        }
55
70
    }
56
}
57

            
58
#[cfg(test)]
59
mod tests;