Skip to main content

tui/form/
pointer.rs

1//! What a click does inside a form: focus a grid cell.
2
3use ratatui::layout::{Position, Rect};
4use tvui::{InputLine, TextView};
5
6use super::Form;
7use crate::widgets::Widget;
8use crate::widgets::grid::CellId;
9
10impl Form {
11    /// Focuses `cell` of the grid in field `field`; a field that is not a grid changes nothing.
12    pub fn focus_cell(&mut self, field: usize, cell: CellId) {
13        let Some(grid) = self.fields.get_mut(field) else {
14            return;
15        };
16        match &mut grid.widget {
17            Widget::Splits(splits) => splits.focus_cell_id(cell),
18            Widget::Rows(rows) => rows.focus_at(cell.row, cell.col),
19            _ => return,
20        }
21        self.focus_field(field);
22    }
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    pub fn place_caret(&mut self, area: Rect, point: Position) {
27        let Some(editor) = self
28            .fields
29            .get_mut(self.focus)
30            .and_then(|field| field.widget.focused_editor_mut())
31        else {
32            return;
33        };
34        if editor.is_multiline() {
35            let lines = editor.text_lines();
36            let at = TextView::position_at(area, &lines, editor.viewport(), point);
37            editor.set_cursor_position(at);
38            return;
39        }
40        let at = InputLine::position_at(area, editor.buffer(), editor.viewport(), point);
41        editor.set_cursor(at);
42    }
43
44    /// Whether the focus is on `cell` of the grid in field `field`.
45    #[must_use]
46    pub fn cell_focused(&self, field: usize, cell: CellId) -> bool {
47        if self.focus != field {
48            return false;
49        }
50        match self.fields.get(field).map(|field| &field.widget) {
51            Some(Widget::Splits(splits)) => splits.focused_cell() == cell,
52            Some(Widget::Rows(rows)) => rows.focused_cell() == cell,
53            _ => false,
54        }
55    }
56}
57
58#[cfg(test)]
59mod tests;