use crate::components::Box as RnkBox;
use crate::components::navigation::{NavigationConfig, handle_list_navigation};
use crate::components::selection_list::{ListStyle, indicator_padding, render_list};
use crate::components::{InteractionMode, InteractionOutcome};
use crate::core::{AccessibilityProps, AccessibilityRole, Color, Element};
use crate::hooks::{Signal, use_input, use_signal};
#[derive(Debug, Clone)]
pub struct SelectItem<T: Clone> {
pub label: String,
pub value: T,
}
impl<T: Clone> SelectItem<T> {
pub fn new(label: impl Into<String>, value: T) -> Self {
Self {
label: label.into(),
value,
}
}
}
impl<T: Clone + ToString> From<T> for SelectItem<T> {
fn from(value: T) -> Self {
Self {
label: value.to_string(),
value,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SelectInputState {
highlighted: usize,
submitted: Option<usize>,
cancelled: bool,
}
impl SelectInputState {
pub fn new(highlighted: usize) -> Self {
Self {
highlighted,
submitted: None,
cancelled: false,
}
}
pub fn highlighted(&self) -> usize {
self.highlighted
}
pub fn set_highlighted(&mut self, index: usize, item_count: usize) {
self.highlighted = index.min(item_count.saturating_sub(1));
}
pub fn submitted(&self) -> Option<usize> {
self.submitted
}
pub fn is_cancelled(&self) -> bool {
self.cancelled
}
}
#[derive(Debug, Clone)]
pub struct SelectInputStyle {
pub highlight_color: Option<Color>,
pub highlight_bg: Option<Color>,
pub highlight_bold: bool,
pub indicator: String,
pub indicator_padding: String,
pub item_color: Option<Color>,
}
impl Default for SelectInputStyle {
fn default() -> Self {
Self {
highlight_color: Some(Color::Cyan),
highlight_bg: None,
highlight_bold: true,
indicator: "❯ ".to_string(),
indicator_padding: " ".to_string(),
item_color: None,
}
}
}
impl SelectInputStyle {
pub fn new() -> Self {
Self::default()
}
pub fn highlight_color(mut self, color: Color) -> Self {
self.highlight_color = Some(color);
self
}
pub fn highlight_bg(mut self, color: Color) -> Self {
self.highlight_bg = Some(color);
self
}
pub fn highlight_bold(mut self, bold: bool) -> Self {
self.highlight_bold = bold;
self
}
pub fn indicator(mut self, indicator: impl Into<String>) -> Self {
let ind = indicator.into();
self.indicator_padding = indicator_padding(&ind);
self.indicator = ind;
self
}
pub fn item_color(mut self, color: Color) -> Self {
self.item_color = Some(color);
self
}
}
pub struct SelectInput<T: Clone + 'static> {
items: Vec<SelectItem<T>>,
highlighted: usize,
limit: Option<usize>,
style: SelectInputStyle,
is_focused: bool,
vim_navigation: bool,
number_shortcuts: bool,
mode: InteractionMode,
}
impl<T: Clone + 'static> SelectInput<T> {
pub fn new(items: Vec<SelectItem<T>>) -> Self {
Self {
items,
highlighted: 0,
limit: None,
style: SelectInputStyle::default(),
is_focused: true,
vim_navigation: true,
number_shortcuts: true,
mode: InteractionMode::Enabled,
}
}
pub fn from_items<I>(iter: I) -> Self
where
I: IntoIterator<Item = SelectItem<T>>,
{
Self::new(iter.into_iter().collect())
}
pub fn highlighted(mut self, index: usize) -> Self {
self.highlighted = index.min(self.items.len().saturating_sub(1));
self
}
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn style(mut self, style: SelectInputStyle) -> Self {
self.style = style;
self
}
pub fn focused(mut self, focused: bool) -> Self {
self.is_focused = focused;
self
}
pub fn vim_navigation(mut self, enabled: bool) -> Self {
self.vim_navigation = enabled;
self
}
pub fn number_shortcuts(mut self, enabled: bool) -> Self {
self.number_shortcuts = enabled;
self
}
pub fn enabled(mut self) -> Self {
self.mode = InteractionMode::Enabled;
self
}
pub fn disabled(mut self) -> Self {
self.mode = InteractionMode::Disabled;
self
}
pub fn read_only(mut self) -> Self {
self.mode = InteractionMode::ReadOnly;
self
}
pub fn highlight_color(mut self, color: Color) -> Self {
self.style.highlight_color = Some(color);
self
}
pub fn indicator(mut self, indicator: impl Into<String>) -> Self {
self.style = self.style.indicator(indicator);
self
}
pub fn len(&self) -> usize {
self.items.len()
}
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
pub fn into_element(self) -> Element {
let mode = self.mode;
if self.items.is_empty() {
return RnkBox::new().into_element().with_accessibility(
AccessibilityProps::new(AccessibilityRole::Select)
.label("Select input")
.description("No options")
.disabled(mode.is_disabled())
.read_only(mode.is_read_only())
.focusable(false),
);
}
let items = self.items.clone();
let initial_highlighted = self.highlighted;
let limit = self.limit;
let style = self.style.clone();
let is_focused = self.is_focused;
let vim_navigation = self.vim_navigation;
let number_shortcuts = self.number_shortcuts;
let state_signal = use_signal(|| SelectInputState::new(initial_highlighted));
if is_focused {
let items_len = items.len();
let state_for_input = state_signal.clone();
use_input(move |input, key| {
let config = NavigationConfig::new()
.vim_navigation(vim_navigation)
.number_shortcuts(number_shortcuts);
let mut next = state_for_input.get();
let outcome = handle_select_input(&mut next, items_len, input, key, &config, mode);
if outcome.is_handled() {
state_for_input.set(next);
}
});
}
let highlighted = state_signal.get().highlighted();
let mut accessibility = AccessibilityProps::new(AccessibilityRole::Select)
.label("Select input")
.description(format!("{} options", items.len()))
.disabled(mode.is_disabled())
.read_only(mode.is_read_only())
.focusable(is_focused && !mode.is_disabled());
if let Some(item) = items.get(highlighted) {
accessibility = accessibility.value(item.label.clone());
}
render_select_list(&items, state_signal, limit, &style).with_accessibility(accessibility)
}
}
pub fn handle_select_input(
state: &mut SelectInputState,
item_count: usize,
input: &str,
key: &crate::hooks::Key,
config: &NavigationConfig,
mode: InteractionMode,
) -> InteractionOutcome<usize> {
if mode.is_disabled() || item_count == 0 {
return InteractionOutcome::Ignored;
}
state.set_highlighted(state.highlighted, item_count);
if key.escape {
state.cancelled = true;
return InteractionOutcome::Cancelled;
}
let current = state.highlighted;
let result = handle_list_navigation(current, item_count, input, *key, config);
if result.is_moved() {
let new_pos = result.unwrap_or(current);
if new_pos != current {
state.highlighted = new_pos;
}
return InteractionOutcome::Handled;
}
if mode.is_read_only() {
return InteractionOutcome::Ignored;
}
if key.return_key || key.space {
state.submitted = Some(state.highlighted);
return InteractionOutcome::Submitted(state.highlighted);
}
InteractionOutcome::Ignored
}
impl ListStyle for SelectInputStyle {
fn highlight_color(&self) -> Option<Color> {
self.highlight_color
}
fn highlight_bg(&self) -> Option<Color> {
self.highlight_bg
}
fn highlight_bold(&self) -> bool {
self.highlight_bold
}
fn indicator(&self) -> &str {
&self.indicator
}
fn indicator_padding(&self) -> &str {
&self.indicator_padding
}
fn item_color(&self) -> Option<Color> {
self.item_color
}
}
fn render_select_list<T: Clone + 'static>(
items: &[SelectItem<T>],
state_signal: Signal<SelectInputState>,
limit: Option<usize>,
style: &SelectInputStyle,
) -> Element {
let highlighted = state_signal.get().highlighted();
render_list(
items,
highlighted,
limit,
style,
|item, _idx, _is_highlighted, prefix| format!("{}{}", prefix, item.label),
|_item, _idx, style, _is_highlighted, mut text| {
if let Some(color) = style.item_color() {
text = text.color(color);
}
text
},
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_select_item_creation() {
let item = SelectItem::new("Test", 42);
assert_eq!(item.label, "Test");
assert_eq!(item.value, 42);
}
#[test]
fn test_select_input_creation() {
let items = vec![
SelectItem::new("One", 1),
SelectItem::new("Two", 2),
SelectItem::new("Three", 3),
];
let select = SelectInput::new(items);
assert_eq!(select.len(), 3);
assert!(!select.is_empty());
}
#[test]
fn test_select_input_empty() {
let select: SelectInput<i32> = SelectInput::new(vec![]);
assert!(select.is_empty());
assert_eq!(select.len(), 0);
}
#[test]
fn test_select_input_highlighted() {
let items = vec![
SelectItem::new("One", 1),
SelectItem::new("Two", 2),
SelectItem::new("Three", 3),
];
let select = SelectInput::new(items).highlighted(1);
assert_eq!(select.highlighted, 1);
}
#[test]
fn test_select_input_highlighted_bounds() {
let items = vec![SelectItem::new("One", 1), SelectItem::new("Two", 2)];
let select = SelectInput::new(items).highlighted(10);
assert_eq!(select.highlighted, 1); }
#[test]
fn test_select_input_style() {
let style = SelectInputStyle::new()
.highlight_color(Color::Green)
.indicator("> ");
assert_eq!(style.highlight_color, Some(Color::Green));
assert_eq!(style.indicator, "> ");
assert_eq!(style.indicator_padding, " ");
}
#[test]
fn test_select_input_limit() {
let items = vec![
SelectItem::new("One", 1),
SelectItem::new("Two", 2),
SelectItem::new("Three", 3),
SelectItem::new("Four", 4),
SelectItem::new("Five", 5),
];
let select = SelectInput::new(items).limit(3);
assert_eq!(select.limit, Some(3));
}
#[test]
fn test_select_input_builder_chain() {
let items = vec![SelectItem::new("Test", 1)];
let select = SelectInput::new(items)
.highlighted(0)
.limit(5)
.focused(true)
.vim_navigation(true)
.number_shortcuts(false)
.highlight_color(Color::Yellow)
.indicator("→ ");
assert_eq!(select.highlighted, 0);
assert_eq!(select.limit, Some(5));
assert!(select.is_focused);
assert!(select.vim_navigation);
assert!(!select.number_shortcuts);
}
#[test]
fn test_select_input_from_items() {
let items = vec![SelectItem::new("A", 'a'), SelectItem::new("B", 'b')];
let select = SelectInput::from_items(items);
assert_eq!(select.len(), 2);
}
#[test]
fn test_handle_select_input_navigation_submit_and_cancel() {
let mut state = SelectInputState::new(0);
let config = NavigationConfig::new().vim_navigation(true);
let outcome = handle_select_input(
&mut state,
3,
"j",
&crate::hooks::Key::default(),
&config,
InteractionMode::Enabled,
);
assert_eq!(outcome, InteractionOutcome::Handled);
assert_eq!(state.highlighted(), 1);
let outcome = handle_select_input(
&mut state,
3,
"",
&crate::hooks::Key {
return_key: true,
..Default::default()
},
&config,
InteractionMode::Enabled,
);
assert_eq!(outcome, InteractionOutcome::Submitted(1));
assert_eq!(state.submitted(), Some(1));
let outcome = handle_select_input(
&mut state,
3,
"",
&crate::hooks::Key {
escape: true,
..Default::default()
},
&config,
InteractionMode::Enabled,
);
assert_eq!(outcome, InteractionOutcome::Cancelled);
assert!(state.is_cancelled());
}
#[test]
fn test_handle_select_input_modes() {
let config = NavigationConfig::new().vim_navigation(true);
let mut state = SelectInputState::new(0);
let outcome = handle_select_input(
&mut state,
3,
"j",
&crate::hooks::Key::default(),
&config,
InteractionMode::Disabled,
);
assert_eq!(outcome, InteractionOutcome::Ignored);
assert_eq!(state.highlighted(), 0);
let outcome = handle_select_input(
&mut state,
3,
"j",
&crate::hooks::Key::default(),
&config,
InteractionMode::ReadOnly,
);
assert_eq!(outcome, InteractionOutcome::Handled);
assert_eq!(state.highlighted(), 1);
let outcome = handle_select_input(
&mut state,
3,
"",
&crate::hooks::Key {
return_key: true,
..Default::default()
},
&config,
InteractionMode::ReadOnly,
);
assert_eq!(outcome, InteractionOutcome::Ignored);
assert_eq!(state.submitted(), None);
}
}