index : nmrs-tui
A fast, Vim-friendly NetworkManager TUI built in Rust.
about summary refs log tree commit diff
nmrs-tui / src / ui / input.rs
-rw-r--r-- blob f39e582a589283730fa0b7166cca0be5bac7d988 2547 bytes (plain)
1
#[derive(PartialEq)]
2
pub enum InputMode {
3
    Normal,
4
    Editing,
5
}
6
7
pub struct Input {
8
    pub mode: InputMode,
9
    pub value: String,
10
    // cursor postion x.
11
    pub cx: usize,
12
}
13
14
impl Input {
15
    pub fn new() -> Self {
16
        Self {
17
            mode: InputMode::Normal,
18
            value: String::new(),
19
            cx: 0,
20
        }
21
    }
22
    pub fn move_cursor_left(&mut self) {
23
        let cursor_moved_left = self.cx.saturating_sub(1);
24
        self.cx = self.clamp_cursor(cursor_moved_left);
25
    }
26
27
    pub fn move_cursor_right(&mut self) {
28
        let cursor_moved_right = self.cx.saturating_add(1);
29
        self.cx = self.clamp_cursor(cursor_moved_right);
30
    }
31
32
    pub fn enter_char(&mut self, new_char: char) {
33
        let index = self.byte_index();
34
        self.value.insert(index, new_char);
35
        self.move_cursor_right();
36
    }
37
38
    // Returns the byte index based on the character position.
39
    // Since each character in a string can contain multiple bytes, it's necessary to calculate
40
    // the byte index based on the index of the character.
41
    fn byte_index(&mut self) -> usize {
42
        self.value
43
            .char_indices()
44
            .map(|(i, _)| i)
45
            .nth(self.cx)
46
            .unwrap_or(self.value.len())
47
    }
48
49
    pub fn delete_char(&mut self) {
50
        let is_not_cursor_leftmost = self.cx != 0;
51
        if is_not_cursor_leftmost {
52
            // Method "remove" is not used on the saved text for deleting the selected char.
53
            // Reason: Using remove on String works on bytes instead of the chars.
54
            // Using remove would require special care because of char boundaries.
55
56
            let current_index = self.cx;
57
            let from_left_to_current_index = current_index - 1;
58
59
            // Getting all characters before the selected character.
60
            let before_char_to_delete = self.value.chars().take(from_left_to_current_index);
61
            // Getting all characters after selected character.
62
            let after_char_to_delete = self.value.chars().skip(current_index);
63
64
            // Put all characters together except the selected one.
65
            // By leaving the selected one out, it is forgotten and therefore deleted.
66
            self.value = before_char_to_delete.chain(after_char_to_delete).collect();
67
            self.move_cursor_left();
68
        }
69
    }
70
71
    fn clamp_cursor(&self, new_cursor_pos: usize) -> usize {
72
        new_cursor_pos.clamp(0, self.value.chars().count())
73
    }
74
75
    pub const fn reset_cursor(&mut self) {
76
        self.cx = 0;
77
    }
78
}