rustlings/src/list.rs

71 lines
2.2 KiB
Rust
Raw Normal View History

2024-04-07 04:03:37 +03:00
use anyhow::Result;
use crossterm::{
2024-04-07 04:38:18 +03:00
event::{self, Event, KeyCode, KeyEventKind},
2024-04-07 04:03:37 +03:00
terminal::{disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen},
ExecutableCommand,
};
2024-04-07 20:05:29 +03:00
use ratatui::{backend::CrosstermBackend, Terminal};
2024-04-07 04:38:18 +03:00
use std::io;
2024-04-07 04:03:37 +03:00
2024-04-07 20:05:29 +03:00
mod state;
2024-04-07 17:33:00 +03:00
2024-04-07 20:05:29 +03:00
use crate::{exercise::Exercise, state_file::StateFile};
2024-04-07 17:33:00 +03:00
2024-04-07 20:05:29 +03:00
use self::state::UiState;
2024-04-07 04:03:37 +03:00
2024-04-07 20:01:08 +03:00
pub fn list(state_file: &mut StateFile, exercises: &[Exercise]) -> Result<()> {
2024-04-07 04:38:18 +03:00
let mut stdout = io::stdout().lock();
stdout.execute(EnterAlternateScreen)?;
enable_raw_mode()?;
let mut terminal = Terminal::new(CrosstermBackend::new(&mut stdout))?;
terminal.clear()?;
2024-04-07 20:01:08 +03:00
let mut ui_state = UiState::new(state_file, exercises);
2024-04-07 04:38:18 +03:00
'outer: loop {
2024-04-07 17:33:00 +03:00
terminal.draw(|frame| ui_state.draw(frame))?;
2024-04-07 04:03:37 +03:00
2024-04-07 04:38:18 +03:00
let key = loop {
match event::read()? {
2024-04-07 04:41:23 +03:00
Event::Key(key) => {
if key.kind != KeyEventKind::Press {
continue;
}
break key;
}
2024-04-07 04:38:18 +03:00
// Redraw
Event::Resize(_, _) => continue 'outer,
// Ignore
Event::FocusGained | Event::FocusLost | Event::Mouse(_) | Event::Paste(_) => (),
}
};
match key.code {
KeyCode::Char('q') => break,
2024-04-07 17:33:00 +03:00
KeyCode::Down | KeyCode::Char('j') => ui_state.select_next(),
KeyCode::Up | KeyCode::Char('k') => ui_state.select_previous(),
KeyCode::Home | KeyCode::Char('g') => ui_state.select_first(),
KeyCode::End | KeyCode::Char('G') => ui_state.select_last(),
2024-04-07 23:43:59 +03:00
KeyCode::Char('r') => {
let selected = ui_state.selected();
exercises[selected].reset()?;
state_file.reset(selected)?;
ui_state.table = ui_state.table.rows(UiState::rows(state_file, exercises));
}
2024-04-07 05:59:22 +03:00
KeyCode::Char('c') => {
2024-04-07 20:05:29 +03:00
state_file.set_next_exercise_ind(ui_state.selected())?;
2024-04-07 20:01:08 +03:00
ui_state.table = ui_state.table.rows(UiState::rows(state_file, exercises));
2024-04-07 05:59:22 +03:00
}
2024-04-07 04:38:18 +03:00
_ => (),
2024-04-07 04:03:37 +03:00
}
}
drop(terminal);
stdout.execute(LeaveAlternateScreen)?;
disable_raw_mode()?;
Ok(())
}