use crate::app::App;
use crate::app::AppError;
use crate::app::Theme;
use crate::app::input;
use crate::app::ui;
use ratatui::DefaultTerminal;
use ratatui::crossterm::event;
use ratatui::crossterm::event::Event;
pub fn run(app: App) -> Result<(), AppError> {
run_with_theme(app, &Theme::default())
}
pub fn run_with_theme(mut app: App, theme: &Theme) -> Result<(), AppError> {
let mut terminal = ratatui::try_init().map_err(AppError::TerminalSetup)?;
let outcome = play(&mut app, &mut terminal, theme);
let restored = ratatui::try_restore().map_err(AppError::TerminalRestore);
outcome.and(restored)
}
fn play(app: &mut App, terminal: &mut DefaultTerminal, theme: &Theme) -> Result<(), AppError> {
while app.is_running() {
draw(app, terminal, theme)?;
if let Event::Key(key) = event::read().map_err(AppError::Input)?
&& let Some(action) = input::action_for(key)
{
app.handle(action);
}
}
Ok(())
}
fn draw(app: &App, terminal: &mut DefaultTerminal, theme: &Theme) -> Result<(), AppError> {
terminal
.draw(|frame| ui::render(app, theme, frame.area(), frame.buffer_mut()))
.map(|_| ())
.map_err(AppError::Draw)
}