Introduce helper methods for input key safeguards

pull/154/head
sebashwa 2 years ago
parent a55f0fe3e7
commit 221d10ee91

@ -31,6 +31,13 @@ impl Input {
self.cursor_position = 0;
}
fn cannot_go_left(&self) -> bool {
self.value.is_empty() || self.cursor_index == 0 || self.value_width() == 0
}
fn cannot_go_right(&self) -> bool {
self.cursor_index == self.value.len()
}
fn cursor_index_backwards_to_whitespace(&self) -> usize {
let mut result = 0;
@ -46,8 +53,6 @@ impl Input {
}
pub fn handle_key(&mut self, key: Key) -> (Option<Key>, bool) {
let value_str: String = self.value.iter().collect();
match key {
Key::Char(c) => {
self.value.insert(self.cursor_index, c);
@ -57,7 +62,7 @@ impl Input {
return (Some(key), true);
}
Key::Delete | Key::Backspace => {
if value_str.width() == 0 || self.value.is_empty() || self.cursor_index == 0 {
if self.cannot_go_left() {
return (Some(key), false);
}
@ -66,47 +71,47 @@ impl Input {
self.cursor_position -= compute_character_width(last_c);
return (Some(key), true);
}
Key::Left => {
if self.value.is_empty() || self.cursor_index == 0 {
Key::Right => {
if self.cannot_go_right() {
return (Some(key), false);
}
self.cursor_index -= 1;
self.cursor_position = self
.cursor_position
.saturating_sub(compute_character_width(self.value[self.cursor_index]));
let next_c = self.value[self.cursor_index];
self.cursor_index += 1;
self.cursor_position += compute_character_width(next_c);
return (Some(key), true);
}
Key::Right => {
if self.cursor_index == self.value.len() {
Key::Ctrl('e') => {
if self.cannot_go_right() {
return (Some(key), false);
}
let next_c = self.value[self.cursor_index];
self.cursor_index += 1;
self.cursor_position += compute_character_width(next_c);
self.cursor_index = self.value.len();
self.cursor_position = self.value_width();
return (Some(key), true);
}
Key::Ctrl('a') => {
if self.value.is_empty() || self.cursor_index == 0 {
Key::Left => {
if self.cannot_go_left() {
return (Some(key), false);
}
self.cursor_index = 0;
self.cursor_position = 0;
self.cursor_index -= 1;
self.cursor_position = self
.cursor_position
.saturating_sub(compute_character_width(self.value[self.cursor_index]));
return (Some(key), true);
}
Key::Ctrl('e') => {
if self.cursor_index == self.value.len() {
Key::Ctrl('a') => {
if self.cannot_go_left() {
return (Some(key), false);
}
self.cursor_index = self.value.len();
self.cursor_position = self.value_width();
self.cursor_index = 0;
self.cursor_position = 0;
return (Some(key), true);
}
Key::Ctrl('w') => {
if self.value.is_empty() || self.cursor_index == 0 {
if self.cannot_go_left() {
return (Some(key), false);
}

Loading…
Cancel
Save