diff --git a/editor-challenge/src/main.rs b/editor-challenge/src/main.rs index 4631cb0..f56ad64 100644 --- a/editor-challenge/src/main.rs +++ b/editor-challenge/src/main.rs @@ -7,8 +7,7 @@ use crossterm::{ }; use state::AppState; use std::{ - env, - io, + env, io, sync::mpsc, thread, time::{Duration, Instant}, @@ -21,7 +20,7 @@ use tui::{ Terminal, }; -const TITLE: &str = "Text Editor Challenge"; +// const TITLE: &str = "Text Editor Challenge"; const COPYRIGHT: &str = "(c) Savanni D'Gerinel - all rights reserved"; const TICK_RATE_MS: u64 = 200; @@ -48,7 +47,7 @@ where app_state .path .clone() - .map(|path| path.to_string_lossy().to_owned().into()) + .map(|path| path.to_string_lossy().into_owned()) .unwrap_or("No file opened".to_owned()), ) .style(Style::default().fg(Color::LightCyan)) @@ -106,10 +105,8 @@ fn handle_input(tx: mpsc::Sender>, tick_rate: Duration) { } } - if last_tick.elapsed() >= tick_rate { - if let Ok(_) = tx.send(Event::Tick) { - last_tick = Instant::now(); - } + if last_tick.elapsed() >= tick_rate && tx.send(Event::Tick).is_ok() { + last_tick = Instant::now(); } } } @@ -125,26 +122,13 @@ where loop { render(&app_state, terminal)?; - let event = rx.recv()?; - - match event { - Event::Input(KeyEvent { code, modifiers }) - if code == KeyCode::Char('x') && modifiers == KeyModifiers::CONTROL => + match rx.recv()? { + Event::Input(event) + if event.code == KeyCode::Char('x') && event.modifiers == KeyModifiers::CONTROL => { break; } - Event::Input(KeyEvent { code, .. }) if code == KeyCode::Down => { - app_state.cursor_down(); - } - Event::Input(KeyEvent { code, .. }) if code == KeyCode::Up => { - app_state.cursor_up(); - } - Event::Input(KeyEvent { code, .. }) if code == KeyCode::Right => { - app_state.cursor_right(); - } - Event::Input(KeyEvent { code, .. }) if code == KeyCode::Left => { - app_state.cursor_left(); - } + Event::Input(event) => app_state.handle_event(event), _ => {} } } @@ -173,7 +157,7 @@ fn main() -> Result<(), anyhow::Error> { let stdout = io::stdout(); let backend = CrosstermBackend::new(stdout); let mut terminal = Terminal::new(backend)?; - let _ = terminal.clear()?; + terminal.clear()?; let result = app_loop(app_state, &mut terminal, rx); diff --git a/editor-challenge/src/state.rs b/editor-challenge/src/state.rs index 3c3c46f..803adb7 100644 --- a/editor-challenge/src/state.rs +++ b/editor-challenge/src/state.rs @@ -1,3 +1,5 @@ +use crossterm::event::{KeyCode, KeyEvent}; + use crate::types::{Cursor, Document}; use std::{fs::File, io::{BufRead, BufReader}, path::PathBuf}; @@ -39,4 +41,23 @@ impl AppState { pub fn cursor_left(&mut self) { self.cursor.cursor_left(); } + + pub fn handle_event(&mut self, event: KeyEvent) { + let KeyEvent { code, .. }: KeyEvent = event; + match code { + KeyCode::Down => { + self.cursor_down(); + } + KeyCode::Up => { + self.cursor_up(); + } + KeyCode::Right => { + self.cursor_right(); + } + KeyCode::Left => { + self.cursor_left(); + } + _ => {} + }; + } }