Code cleanups

This commit is contained in:
Savanni D'Gerinel 2024-05-06 01:10:23 -04:00
parent 4a62372fd3
commit 8f4d424d1d
2 changed files with 31 additions and 26 deletions

View File

@ -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<Event<KeyEvent>>, 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);

View File

@ -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();
}
_ => {}
};
}
}