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