use crossterm::event::{
KeyCode,
KeyEvent,
};
#[derive(Default, Debug, PartialEq, Clone)]
pub struct InputBuffer {
content: String,
cursor_loc: usize,
}
impl InputBuffer {
pub fn new() -> Self {
InputBuffer {
content: String::new(),
cursor_loc: 0,
}
}
pub fn new_with_value<S: ToString>(value: S) -> Self {
let value = value.to_string();
let value_len = value.len();
InputBuffer {
content: value,
cursor_loc: value_len,
}
}
pub fn get_content(&self) -> &str {
&self.content
}
pub fn get_cursor_location(&self) -> usize {
self.cursor_loc
}
fn add_char(&mut self, c: char) {
self.content.insert(self.cursor_loc, c);
self.cursor_loc += 1;
}
fn backspace(&mut self) {
if self.content.len() > 0 && self.cursor_loc > 0 {
self.cursor_loc -= 1;
self.content.remove(self.cursor_loc);
}
}
fn left(&mut self) {
if self.cursor_loc > 0 {
self.cursor_loc -= 1;
}
}
fn right(&mut self) {
if self.cursor_loc < self.content.len() {
self.cursor_loc += 1;
}
}
fn home(&mut self) {
self.cursor_loc = 0;
}
fn end(&mut self) {
self.cursor_loc = self.content.len();
}
pub fn set_cursor_loc(&mut self, x: usize) {
if x < self.content.len() {
self.cursor_loc = x;
}
}
fn delete(&mut self) {
if self.cursor_loc < self.content.len() {
self.content.remove(self.cursor_loc);
}
}
pub fn process_key_event(
&mut self,
KeyEvent { code, modifiers: _ }: KeyEvent,
) {
match code {
KeyCode::Char(c) => {
self.add_char(c);
}
KeyCode::Backspace => {
self.backspace();
}
KeyCode::Left => {
self.left();
}
KeyCode::Right => {
self.right();
}
KeyCode::Home => {
self.home();
}
KeyCode::End => {
self.end();
}
KeyCode::Delete => {
self.delete();
}
_ => (),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn add_char() {
let mut input1 = InputBuffer::new();
input1.add_char('a');
assert_eq!(String::from("a"), input1.content);
assert_eq!(input1.cursor_loc, 1);
input1.add_char('b');
assert_eq!(String::from("ab"), input1.content);
assert_eq!(input1.cursor_loc, 2);
input1.backspace();
assert_eq!(String::from("a"), input1.content);
assert_eq!(input1.cursor_loc, 1);
input1.left(); assert_eq!(input1.cursor_loc, 0);
input1.left(); assert_eq!(input1.cursor_loc, 0);
input1.right(); assert_eq!(input1.cursor_loc, 1);
input1.right(); assert_eq!(input1.cursor_loc, 1);
input1.add_char('b');
input1.add_char('c');
assert_eq!("abc", input1.content);
assert_eq!(3, input1.cursor_loc);
input1.home(); assert_eq!("abc", input1.content); assert_eq!(0, input1.cursor_loc); input1.end();
assert_eq!("abc", input1.content); assert_eq!(3, input1.cursor_loc); }
}