p2p_chat/ui/state/
input.rs

1//! This module contains input buffer manipulation functionalities for the `UIState`.
2use super::UIState;
3
4impl UIState {
5    /// Inserts a character safely into the input buffer at the current cursor position.
6    ///
7    /// Handles multi-byte characters correctly.
8    ///
9    /// # Arguments
10    ///
11    /// * `c` - The character to insert.
12    pub fn safe_insert_char(&mut self, c: char) {
13        let char_indices: Vec<_> = self.input_buffer.char_indices().collect();
14        let byte_pos = if self.cursor_pos >= char_indices.len() {
15            self.input_buffer.len()
16        } else {
17            char_indices[self.cursor_pos].0
18        };
19
20        self.input_buffer.insert(byte_pos, c);
21        self.cursor_pos += 1;
22    }
23
24    /// Removes the character before the current cursor position safely.
25    ///
26    /// Handles multi-byte characters correctly.
27    ///
28    /// # Returns
29    ///
30    /// `true` if a character was removed, `false` otherwise.
31    pub fn safe_remove_char_before(&mut self) -> bool {
32        if self.cursor_pos > 0 {
33            let char_indices: Vec<_> = self.input_buffer.char_indices().collect();
34            if self.cursor_pos <= char_indices.len() {
35                let byte_pos = char_indices[self.cursor_pos - 1].0;
36                self.input_buffer.remove(byte_pos);
37                self.cursor_pos -= 1;
38                return true;
39            }
40        }
41        false
42    }
43
44    /// Removes the character at the current cursor position safely.
45    ///
46    /// Handles multi-byte characters correctly.
47    ///
48    /// # Returns
49    ///
50    /// `true` if a character was removed, `false` otherwise.
51    pub fn safe_remove_char_at(&mut self) -> bool {
52        let char_indices: Vec<_> = self.input_buffer.char_indices().collect();
53        if self.cursor_pos < char_indices.len() {
54            let byte_pos = char_indices[self.cursor_pos].0;
55            self.input_buffer.remove(byte_pos);
56            return true;
57        }
58        false
59    }
60
61    /// Moves the cursor one position to the left.
62    pub fn safe_cursor_left(&mut self) {
63        if self.cursor_pos > 0 {
64            self.cursor_pos -= 1;
65        }
66    }
67
68    /// Moves the cursor one position to the right.
69    pub fn safe_cursor_right(&mut self) {
70        let char_count = self.input_buffer.chars().count();
71        if self.cursor_pos < char_count {
72            self.cursor_pos += 1;
73        }
74    }
75
76    /// Moves the cursor to the beginning of the input buffer.
77    pub fn safe_cursor_home(&mut self) {
78        self.cursor_pos = 0;
79    }
80
81    /// Moves the cursor to the end of the input buffer.
82    pub fn safe_cursor_end(&mut self) {
83        self.cursor_pos = self.input_buffer.chars().count();
84    }
85}