use crate::{event::Event, layout::Rect, render::Frame, style::Style};
use crossterm::event::KeyCode;
pub struct Button {
label: String,
style: Style,
active_style: Style,
is_pressed: bool,
on_press: Option<Box<dyn Fn()>>,
}
impl Button {
pub fn new(label: &str) -> Self {
Self {
label: label.to_string(),
style: Style::new(),
active_style: Style::new().reversed(),
is_pressed: false,
on_press: None,
}
}
pub fn style(mut self, style: Style) -> Self {
self.style = style;
self
}
pub fn active_style(mut self, style: Style) -> Self {
self.active_style = style;
self
}
pub fn on_press<F: Fn() + 'static>(mut self, f: F) -> Self {
self.on_press = Some(Box::new(f));
self
}
pub fn press(&mut self) {
self.is_pressed = true;
if let Some(callback) = &self.on_press {
callback();
}
}
}
impl super::Component for Button {
fn render(&self, frame: &mut Frame, area: Rect) {
let style = if self.is_pressed { self.active_style.clone() } else { self.style.clone() };
frame.render_button(&self.label, area, style);
}
fn handle_event(&mut self, event: &Event) -> bool {
match event {
Event::Key(key_event) => {
if key_event.code == KeyCode::Enter {
self.press();
true
}
else {
false
}
}
_ => false,
}
}
}