fresh/view/ui/
menu_input.rs

1//! Input handling for the Menu system.
2//!
3//! Provides InputHandler implementation for menu navigation.
4//! Uses a wrapper struct to bundle MenuState with menu configuration.
5
6use super::menu::MenuState;
7use crate::config::Menu;
8use crate::input::handler::{DeferredAction, InputContext, InputHandler, InputResult};
9use crossterm::event::{KeyCode, KeyEvent};
10
11/// Wrapper that provides InputHandler for MenuState with menu configuration.
12pub struct MenuInputHandler<'a> {
13    pub state: &'a mut MenuState,
14    pub menus: &'a [Menu],
15}
16
17impl<'a> MenuInputHandler<'a> {
18    pub fn new(state: &'a mut MenuState, menus: &'a [Menu]) -> Self {
19        Self { state, menus }
20    }
21}
22
23impl InputHandler for MenuInputHandler<'_> {
24    fn handle_key_event(&mut self, event: &KeyEvent, ctx: &mut InputContext) -> InputResult {
25        // Only handle if menu is active
26        if self.state.active_menu.is_none() {
27            return InputResult::Ignored;
28        }
29
30        match event.code {
31            // Close menu
32            KeyCode::Esc => {
33                ctx.defer(DeferredAction::CloseMenu);
34                InputResult::Consumed
35            }
36
37            // Execute/confirm
38            KeyCode::Enter => {
39                // Check if highlighted item is a submenu - if so, open it
40                if self.state.is_highlighted_submenu(self.menus) {
41                    self.state.open_submenu(self.menus);
42                    return InputResult::Consumed;
43                }
44
45                // Get the action to execute
46                if let Some((action, args)) = self.state.get_highlighted_action(self.menus) {
47                    ctx.defer(DeferredAction::ExecuteMenuAction { action, args });
48                    ctx.defer(DeferredAction::CloseMenu);
49                }
50                InputResult::Consumed
51            }
52
53            // Navigation
54            KeyCode::Up | KeyCode::Char('k') if event.modifiers.is_empty() => {
55                if let Some(active_idx) = self.state.active_menu {
56                    if let Some(menu) = self.menus.get(active_idx) {
57                        self.state.prev_item(menu);
58                    }
59                }
60                InputResult::Consumed
61            }
62            KeyCode::Down | KeyCode::Char('j') if event.modifiers.is_empty() => {
63                if let Some(active_idx) = self.state.active_menu {
64                    if let Some(menu) = self.menus.get(active_idx) {
65                        self.state.next_item(menu);
66                    }
67                }
68                InputResult::Consumed
69            }
70            KeyCode::Left | KeyCode::Char('h') if event.modifiers.is_empty() => {
71                // If in a submenu, close it and go back to parent
72                // Otherwise, go to the previous menu
73                if !self.state.close_submenu() {
74                    self.state.prev_menu(self.menus.len());
75                }
76                InputResult::Consumed
77            }
78            KeyCode::Right | KeyCode::Char('l') if event.modifiers.is_empty() => {
79                // If on a submenu item, open it
80                // Otherwise, go to the next menu
81                if !self.state.open_submenu(self.menus) {
82                    self.state.next_menu(self.menus.len());
83                }
84                InputResult::Consumed
85            }
86
87            // Home/End for quick navigation
88            KeyCode::Home => {
89                self.state.highlighted_item = Some(0);
90                InputResult::Consumed
91            }
92            KeyCode::End => {
93                if let Some(active_idx) = self.state.active_menu {
94                    if let Some(menu) = self.menus.get(active_idx) {
95                        if let Some(items) = self.state.get_current_items_cloned(menu) {
96                            if !items.is_empty() {
97                                self.state.highlighted_item = Some(items.len() - 1);
98                            }
99                        }
100                    }
101                }
102                InputResult::Consumed
103            }
104
105            // Consume all other keys (modal behavior)
106            _ => InputResult::Consumed,
107        }
108    }
109
110    fn is_modal(&self) -> bool {
111        self.state.active_menu.is_some()
112    }
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use crate::config::MenuItem;
119    use crossterm::event::KeyModifiers;
120    use std::collections::HashMap;
121
122    fn key(code: KeyCode) -> KeyEvent {
123        KeyEvent::new(code, KeyModifiers::NONE)
124    }
125
126    fn create_test_menus() -> Vec<Menu> {
127        vec![
128            Menu {
129                id: None,
130                label: "File".to_string(),
131                items: vec![
132                    MenuItem::Action {
133                        label: "New".to_string(),
134                        action: "new_file".to_string(),
135                        args: HashMap::new(),
136                        when: None,
137                        checkbox: None,
138                    },
139                    MenuItem::Separator { separator: true },
140                    MenuItem::Action {
141                        label: "Save".to_string(),
142                        action: "save".to_string(),
143                        args: HashMap::new(),
144                        when: None,
145                        checkbox: None,
146                    },
147                ],
148            },
149            Menu {
150                id: None,
151                label: "Edit".to_string(),
152                items: vec![
153                    MenuItem::Action {
154                        label: "Undo".to_string(),
155                        action: "undo".to_string(),
156                        args: HashMap::new(),
157                        when: None,
158                        checkbox: None,
159                    },
160                    MenuItem::Action {
161                        label: "Redo".to_string(),
162                        action: "redo".to_string(),
163                        args: HashMap::new(),
164                        when: None,
165                        checkbox: None,
166                    },
167                ],
168            },
169        ]
170    }
171
172    #[test]
173    fn test_menu_navigation_down() {
174        let menus = create_test_menus();
175        let mut state = MenuState::new();
176        state.open_menu(0);
177
178        let mut handler = MenuInputHandler::new(&mut state, &menus);
179        let mut ctx = InputContext::new();
180
181        // Initially at first item
182        assert_eq!(handler.state.highlighted_item, Some(0));
183
184        // Down arrow moves to next (skipping separator)
185        handler.handle_key_event(&key(KeyCode::Down), &mut ctx);
186        assert_eq!(handler.state.highlighted_item, Some(2)); // Skipped separator at 1
187    }
188
189    #[test]
190    fn test_menu_navigation_between_menus() {
191        let menus = create_test_menus();
192        let mut state = MenuState::new();
193        state.open_menu(0);
194
195        let mut handler = MenuInputHandler::new(&mut state, &menus);
196        let mut ctx = InputContext::new();
197
198        // Initially on File menu
199        assert_eq!(handler.state.active_menu, Some(0));
200
201        // Right arrow moves to next menu
202        handler.handle_key_event(&key(KeyCode::Right), &mut ctx);
203        assert_eq!(handler.state.active_menu, Some(1));
204
205        // Left arrow moves back
206        handler.handle_key_event(&key(KeyCode::Left), &mut ctx);
207        assert_eq!(handler.state.active_menu, Some(0));
208    }
209
210    #[test]
211    fn test_menu_escape_closes() {
212        let menus = create_test_menus();
213        let mut state = MenuState::new();
214        state.open_menu(0);
215
216        let mut handler = MenuInputHandler::new(&mut state, &menus);
217        let mut ctx = InputContext::new();
218
219        handler.handle_key_event(&key(KeyCode::Esc), &mut ctx);
220        assert!(ctx
221            .deferred_actions
222            .iter()
223            .any(|a| matches!(a, DeferredAction::CloseMenu)));
224    }
225
226    #[test]
227    fn test_menu_enter_executes() {
228        let menus = create_test_menus();
229        let mut state = MenuState::new();
230        state.open_menu(0);
231        state.highlighted_item = Some(0); // "New" action
232
233        let mut handler = MenuInputHandler::new(&mut state, &menus);
234        let mut ctx = InputContext::new();
235
236        handler.handle_key_event(&key(KeyCode::Enter), &mut ctx);
237        assert!(ctx.deferred_actions.iter().any(|a| matches!(
238            a,
239            DeferredAction::ExecuteMenuAction { action, .. } if action == "new_file"
240        )));
241    }
242
243    #[test]
244    fn test_menu_is_modal_when_active() {
245        let menus = create_test_menus();
246        let mut state = MenuState::new();
247
248        let handler = MenuInputHandler::new(&mut state, &menus);
249        assert!(!handler.is_modal());
250
251        state.open_menu(0);
252        let handler = MenuInputHandler::new(&mut state, &menus);
253        assert!(handler.is_modal());
254    }
255
256    #[test]
257    fn test_menu_ignored_when_inactive() {
258        let menus = create_test_menus();
259        let mut state = MenuState::new();
260
261        let mut handler = MenuInputHandler::new(&mut state, &menus);
262        let mut ctx = InputContext::new();
263
264        let result = handler.handle_key_event(&key(KeyCode::Down), &mut ctx);
265        assert_eq!(result, InputResult::Ignored);
266    }
267}