use super::ComboBoxOption;
use crate::Id;
use winit::keyboard::KeyCode;
pub(super) struct Navigable<'s, T> {
options: &'s [ComboBoxOption<T>],
indices: Vec<usize>,
}
pub(super) struct Navigation {
pub(super) moved: bool,
pub(super) chosen: Option<usize>,
}
impl<'s, T> Navigable<'s, T> {
pub(super) fn new(options: &'s [ComboBoxOption<T>], listed: &[usize]) -> Self {
let indices = listed
.iter()
.copied()
.filter(|&i| options[i].enabled)
.collect();
Self { options, indices }
}
fn position(&self, active: Option<Id>) -> Option<usize> {
self.indices
.iter()
.position(|&i| Some(self.options[i].id) == active)
}
pub(super) fn restore(&self, active: &mut Option<Id>) -> bool {
if self.position(*active).is_some() {
return false;
}
*active = self.indices.first().map(|&i| self.options[i].id);
true
}
pub(super) fn navigate(
&self,
keys: &[KeyCode],
page: usize,
active: &mut Option<Id>,
) -> Navigation {
let mut navigation = Navigation {
moved: false,
chosen: None,
};
for key in keys {
if matches!(key, KeyCode::Enter | KeyCode::Space) {
navigation.chosen = self.position(*active).map(|at| self.indices[at]);
break;
}
let current = self.position(*active).unwrap_or(0);
let last = self.indices.len().saturating_sub(1);
let next = match key {
KeyCode::ArrowDown => (current + 1).min(last),
KeyCode::ArrowUp => current.saturating_sub(1),
KeyCode::Home => 0,
KeyCode::End => last,
KeyCode::PageDown => (current + page).min(last),
KeyCode::PageUp => current.saturating_sub(page),
_ => current,
};
*active = self.indices.get(next).map(|&i| self.options[i].id);
navigation.moved = true;
}
navigation
}
}