Merge pull request #106 from afonsofrancof/cleanup

Fix crash when scrolling on empty results
This commit is contained in:
Chris Titus 2024-07-30 17:06:44 -05:00 committed by GitHub
commit e8b38c3121
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 21 additions and 6 deletions

View File

@ -168,7 +168,9 @@ impl CustomList {
} }
items items
} else { } else {
self.filtered_items let mut sorted_items = self.filtered_items.clone();
sorted_items.sort_by(|a, b| a.name.cmp(b.name));
sorted_items
.iter() .iter()
.map(|node| { .map(|node| {
Line::from(format!("{} {}", state.theme.cmd_icon, node.name)) Line::from(format!("{} {}", state.theme.cmd_icon, node.name))
@ -238,6 +240,15 @@ impl CustomList {
} }
} }
/// Resets the selection to the first item
pub fn reset_selection(&mut self) {
if !self.filtered_items.is_empty() {
self.list_state.select(Some(0));
} else {
self.list_state.select(None);
}
}
/// Handle key events, we are only interested in `Press` and `Repeat` events /// Handle key events, we are only interested in `Press` and `Repeat` events
pub fn handle_key(&mut self, event: KeyEvent, state: &AppState) -> Option<Command> { pub fn handle_key(&mut self, event: KeyEvent, state: &AppState) -> Option<Command> {
if event.kind == KeyEventKind::Release { if event.kind == KeyEventKind::Release {
@ -310,8 +321,11 @@ impl CustomList {
} }
fn try_scroll_up(&mut self) { fn try_scroll_up(&mut self) {
self.list_state if let Some(selected) = self.list_state.selected() {
.select(Some(self.list_state.selected().unwrap().saturating_sub(1))); if selected > 0 {
self.list_state.select(Some(selected.saturating_sub(1)));
}
}
} }
fn try_scroll_down(&mut self) { fn try_scroll_down(&mut self) {
@ -335,8 +349,6 @@ impl CustomList {
self.list_state self.list_state
.select(Some((curr_selection + 1).min(count))); .select(Some((curr_selection + 1).min(count)));
} }
} else if count > 0 {
self.list_state.select(Some(0));
} }
} }

View File

@ -162,7 +162,10 @@ fn run<B: Backend>(terminal: &mut Terminal<B>, state: &AppState) -> io::Result<(
search_input = String::new(); search_input = String::new();
in_search_mode = false in_search_mode = false
} }
KeyCode::Enter => in_search_mode = false, KeyCode::Enter => {
in_search_mode = false;
custom_list.reset_selection();
}
_ => {} _ => {}
} }
} else if let Some(cmd) = custom_list.handle_key(key, state) { } else if let Some(cmd) = custom_list.handle_key(key, state) {