From c8e2ba3c5c77c7e68cb59b1e9e7a3b2a99ba87ae Mon Sep 17 00:00:00 2001 From: Silas Bartha Date: Thu, 27 Mar 2025 19:06:53 -0400 Subject: [PATCH] Widget focus --- src/lib.rs | 50 +++++++++++++++++++++++++++++++++----------------- 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 6547fe6..79ba6f1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -8,13 +8,27 @@ use bevy_terminal_display::{ crossterm::event::{Event, KeyCode, KeyEventKind}, input::events::TerminalInputEvent, ratatui::{ - layout::Rect, style::{Color, Modifier, Style}, widgets::{Block, Borders, Clear, HighlightSpacing, List, ListItem, ListState} + layout::Rect, + style::{Color, Modifier, Style}, + widgets::{Block, Borders, Clear, HighlightSpacing, List, ListItem, ListState}, }, widgets::TerminalWidget, }; +pub enum MenuControlData { + Button { + label: String, + event: E, + }, +} + +pub struct MenuControl { + pub enabled: Arc, + pub data: MenuControlData, +} + pub struct MenuWidget { - pub items: Vec>, + pub items: Vec>, pub state: ListState, pub enabled_color: Color, pub disabled_color: Color, @@ -37,12 +51,6 @@ impl Default for MenuWidget { } } -pub struct MenuOption { - pub enabled: Arc, - pub label: String, - pub event: E, -} - impl TerminalWidget for MenuWidget { fn render( &mut self, @@ -67,7 +75,7 @@ impl TerminalWidget for MenuWidget { let list = List::new(items) .block(block) .highlight_style(self.selected_style) - .highlight_symbol(">") + .highlight_symbol("> ") .highlight_spacing(HighlightSpacing::Always); let area = if let Some(area) = &self.area_function { @@ -91,11 +99,15 @@ impl TerminalWidget for MenuWidget { if let Some(selected) = self.state.selected() { if let Some(item) = self.items.get(selected) { if item.enabled.load(Ordering::Relaxed) { - commands.send_event(item.event.clone()); + match &item.data { + MenuControlData::Button { event, .. } => { + commands.send_event(event.clone()); + }, + } } } } - }, + } KeyCode::Up => self.state.select_previous(), KeyCode::Down => self.state.select_next(), _ => (), @@ -109,10 +121,12 @@ impl FromIterator<(&'static str, E)> for MenuWidget fn from_iter>(iter: I) -> Self { let items = iter .into_iter() - .map(|(label, event)| MenuOption { + .map(|(label, event)| MenuControl { enabled: Arc::new(true.into()), - label: label.into(), - event, + data: MenuControlData::Button { + label: label.into(), + event, + }, }) .collect(); Self { @@ -122,8 +136,10 @@ impl FromIterator<(&'static str, E)> for MenuWidget } } -impl From<&MenuOption> for ListItem<'_> { - fn from(value: &MenuOption) -> Self { - ListItem::new(value.label.clone()) +impl From<&MenuControl> for ListItem<'_> { + fn from(value: &MenuControl) -> Self { + match &value.data { + MenuControlData::Button { label, .. } => ListItem::new(label.clone()), + } } }