From 15f05be46c936b81f014b81039ba7a009aeebe33 Mon Sep 17 00:00:00 2001 From: EdJoPaTo Date: Mon, 26 Feb 2024 18:05:17 +0100 Subject: [PATCH] fix: do not move offset on unselect --- examples/example.rs | 3 +++ src/lib.rs | 34 ++++++++++++++++++---------------- 2 files changed, 21 insertions(+), 16 deletions(-) diff --git a/examples/example.rs b/examples/example.rs index cf11366..0bf78eb 100644 --- a/examples/example.rs +++ b/examples/example.rs @@ -143,6 +143,9 @@ fn run_app(terminal: &mut Terminal, mut app: App) -> std::io::Res KeyCode::Right => app.state.key_right(), KeyCode::Down => app.state.key_down(&app.items), KeyCode::Up => app.state.key_up(&app.items), + KeyCode::Esc => { + app.state.select(Vec::new()); + } KeyCode::Home => { app.state.select_first(&app.items); } diff --git a/src/lib.rs b/src/lib.rs index c33dd9b..ed728b3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -201,20 +201,20 @@ where } let available_height = area.height as usize; - let selected_index = if state.selected.is_empty() { - 0 - } else { - visible - .iter() - .position(|flattened| flattened.identifier == state.selected) - .unwrap_or(0) - }; + let ensure_index_in_view = + if state.ensure_selected_in_view_on_next_render && !state.selected.is_empty() { + visible + .iter() + .position(|flattened| flattened.identifier == state.selected) + } else { + None + }; // Ensure last line is still visible let mut start = state.offset.min(visible.len().saturating_sub(1)); - if state.ensure_selected_in_view_on_next_render { - start = start.min(selected_index); + if let Some(ensure_index_in_view) = ensure_index_in_view { + start = start.min(ensure_index_in_view); } let mut end = start; @@ -231,12 +231,14 @@ where end += 1; } - while state.ensure_selected_in_view_on_next_render && selected_index >= end { - height += visible[end].item.height(); - end += 1; - while height > available_height { - height = height.saturating_sub(visible[start].item.height()); - start += 1; + if let Some(ensure_index_in_view) = ensure_index_in_view { + while ensure_index_in_view >= end { + height += visible[end].item.height(); + end += 1; + while height > available_height { + height = height.saturating_sub(visible[start].item.height()); + start += 1; + } } }