elm model is in an ok state now

This commit is contained in:
2026-03-21 16:30:42 +00:00
parent 79c77faf3e
commit dfb0c1aede
3 changed files with 47 additions and 4 deletions

View File

@@ -1,3 +1,4 @@
use crossterm::event::Event;
use ratatui::{layout::Rect, Frame}; use ratatui::{layout::Rect, Frame};
pub trait Component { pub trait Component {
@@ -7,6 +8,8 @@ pub trait Component {
/// Update the state based on a message /// Update the state based on a message
fn update(&mut self, msg: Self::Msg); fn update(&mut self, msg: Self::Msg);
fn handle_event(&mut self, event: Event);
/// Render the component to the screen /// Render the component to the screen
fn view(&self, frame: &mut Frame); fn view(&self, frame: &mut Frame);
} }

View File

@@ -10,12 +10,31 @@ pub enum MenuMsg {
} }
#[derive(Default, Debug)] #[derive(Default, Debug)]
pub struct Menu; pub struct Menu {
counter: i32,
}
impl Component for Menu { impl Component for Menu {
type Msg = MenuMsg; type Msg = MenuMsg;
fn update(&mut self, msg: MenuMsg) {} fn update(&mut self, msg: MenuMsg) {
match msg {
MenuMsg::MoveUp => self.counter += 1,
MenuMsg::MoveDown => self.counter -= 1,
_ => {}
}
}
fn view(&self, f: &mut Frame) { fn view(&self, f: &mut Frame) {
let text = Text::raw("meow"); let text_raw = format!("meow - {}", self.counter);
let text = Text::raw(text_raw);
f.render_widget(text, f.area()); f.render_widget(text, f.area());
} }
fn handle_event(&mut self, event: Event) {
match event {
Event::Key(x) => match x.code {
crossterm::event::KeyCode::Up => self.update(MenuMsg::MoveUp),
crossterm::event::KeyCode::Down => self.update(MenuMsg::MoveDown),
_ => {}
},
_ => {}
}
}
} }

View File

@@ -26,9 +26,16 @@ enum AppMsg {
GlobalQuit, GlobalQuit,
} }
#[derive(Default, Debug)]
enum Screen {
#[default]
Menu,
}
#[derive(Default, Debug)] #[derive(Default, Debug)]
struct App { struct App {
menu: Menu, menu: Menu,
screen: Screen,
should_quit: bool, should_quit: bool,
} }
@@ -46,11 +53,25 @@ impl App {
// Centering logic we discussed earlier! // Centering logic we discussed earlier!
self.menu.view(f); self.menu.view(f);
} }
fn handle_event(&mut self, event: Event) {
match self.screen {
Screen::Menu => self.menu.handle_event(event),
}
}
fn propagate_events(&mut self) {
if crossterm::event::poll(Duration::from_millis(100)).unwrap() {
if let Ok(event) = crossterm::event::read() {
self.handle_event(event);
}
}
}
} }
fn main() { fn main() {
let app: App = App::default(); let mut app: App = App::default();
ratatui::run(|terminal| loop { ratatui::run(|terminal| loop {
terminal.draw(|f| app.view(f)); terminal.draw(|f| app.view(f));
app.propagate_events();
}); });
} }