Skip to main content

iced_cube/forms/select/
mod.rs

1//! A dropdown for choosing one value from a list.
2//!
3//! The select opens and closes its own list, so the app only handles the
4//! chosen value. The list floats on the shared
5//! [anchored layer](crate::overlay::anchored) in the
6//! [menu look](crate::overlay::menu), with a check mark on the selected
7//! option. Escape or a click outside closes it.
8//!
9//! A long list shows [`MAX_VISIBLE_ROWS`] rows and scrolls, with a
10//! scrollbar, and is never taller than the room the window has. It opens
11//! with the selected option in the middle, and the highlight stays in view
12//! as the keys move it. A list that fits looks as it always has.
13//!
14//! An enabled select takes keyboard focus from iced's focus operations,
15//! such as a dialog's Tab order, and rings while focused. Space, Enter or
16//! ArrowDown then opens the list with the selected option highlighted.
17//! In the open list the arrow keys, Page Up, Page Down, Home and End move
18//! the highlight, Space or Enter chooses it and closes the list, and Tab
19//! closes it and moves on. Typing letters moves the highlight to the
20//! first option starting with them.
21//!
22//! [`searchable`](Select::searchable) adds a search field that filters the
23//! options as you type, and [`on_custom`](Select::on_custom) lets the user
24//! enter a value that is not in the list.
25
26use std::borrow::Cow;
27
28use iced::advanced::layout;
29use iced::advanced::widget::{Operation, Tree, Widget, tree};
30use iced::advanced::{Clipboard, Layout, Shell, overlay, renderer};
31use iced::keyboard::{self, key::Named};
32use iced::time::Duration;
33use iced::widget::pick_list::{self, Status};
34use iced::widget::{container, row};
35use iced::{
36    Alignment, Background, Border, Color, Element, Event, Length, Rectangle, Renderer, Size, Theme,
37    Vector, mouse, touch,
38};
39
40use crate::data::ellipsis::ellipsis;
41use crate::focus;
42use crate::forms::matching;
43use crate::icon::{opacity, themed};
44use crate::keys::{self, Chord, Keymap};
45use crate::overlay::anchored::{self, Align, Behaviour, Placement, Side};
46use crate::overlay::menu::{self, Parts, ROW_PADDING, RowStatus, Trailing};
47pub use crate::primitives::input::{Shortcut, Shortcuts};
48use crate::theme::{Tokens, fade, mix, radius, space};
49
50mod list;
51mod navigate;
52
53use list::{List, Search};
54
55/// Height of the closed select in logical pixels.
56pub const HEIGHT: f32 = 36.0;
57
58/// Rows the open list shows before it scrolls, unless
59/// [`max_visible_rows`](Select::max_visible_rows) says otherwise.
60pub const MAX_VISIBLE_ROWS: usize = 8;
61
62/// How long a pause in typing starts a new type-ahead search.
63pub const TYPE_AHEAD_PAUSE: Duration = Duration::from_secs(1);
64
65/// Shown in the open list of a select with no options.
66pub const NO_OPTIONS: &str = "No options";
67
68/// Shown when the search matches no option.
69pub const DEFAULT_EMPTY: &str = "No results found.";
70
71/// Shown when the app turns a typed value down.
72pub const DEFAULT_NOT_VALID: &str = "Not valid";
73
74const CHEVRON_SIZE: f32 = 16.0;
75const LINE_HEIGHT: f32 = 20.0;
76
77/// A select builder. Convert it into an [`Element`] to render.
78///
79/// A select without a message is rendered disabled.
80pub struct Select<'a, T: Clone, Message> {
81    options: Cow<'a, [T]>,
82    selected: Option<T>,
83    placeholder: Option<String>,
84    width: Length,
85    on_select: Option<Box<dyn Fn(T) -> Message + 'a>>,
86    leading: Option<Leading<'a, T, Message>>,
87    max_rows: usize,
88    scrollable: bool,
89    searchable: bool,
90    on_custom: Option<OnCustom<'a, Message>>,
91    search_placeholder: Option<String>,
92    shortcuts: Shortcuts,
93    empty: String,
94    not_valid: String,
95    type_ahead_pause: Duration,
96}
97
98type Leading<'a, T, Message> = Box<dyn Fn(&T) -> Option<Element<'a, Message>> + 'a>;
99type OnCustom<'a, Message> = Box<dyn Fn(String) -> Option<Message> + 'a>;
100
101impl<T: Clone + std::fmt::Debug, Message> std::fmt::Debug for Select<'_, T, Message> {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        f.debug_struct("Select")
104            .field("options", &self.options)
105            .field("selected", &self.selected)
106            .field("placeholder", &self.placeholder)
107            .field("enabled", &self.on_select.is_some())
108            .field("leading", &self.leading.is_some())
109            .field("max_rows", &self.max_rows)
110            .field("scrollable", &self.scrollable)
111            .field("searchable", &self.searchable)
112            .field("shortcuts", &self.shortcuts)
113            .field("custom", &self.on_custom.is_some())
114            .finish_non_exhaustive()
115    }
116}
117
118/// Creates a select over `options`, showing `selected` when it is set.
119/// Options are labelled with their `Display` text.
120pub fn select<'a, T, Message>(
121    options: impl Into<Cow<'a, [T]>>,
122    selected: Option<T>,
123) -> Select<'a, T, Message>
124where
125    T: ToString + PartialEq + Clone,
126{
127    Select {
128        options: options.into(),
129        selected,
130        placeholder: None,
131        width: Length::Fixed(200.0),
132        on_select: None,
133        leading: None,
134        max_rows: MAX_VISIBLE_ROWS,
135        scrollable: true,
136        searchable: false,
137        on_custom: None,
138        search_placeholder: None,
139        shortcuts: Shortcuts::all(),
140        empty: DEFAULT_EMPTY.to_owned(),
141        not_valid: DEFAULT_NOT_VALID.to_owned(),
142        type_ahead_pause: TYPE_AHEAD_PAUSE,
143    }
144}
145
146impl<'a, T: Clone, Message> Select<'a, T, Message> {
147    /// Text shown while nothing is selected.
148    pub fn placeholder(mut self, placeholder: impl Into<String>) -> Self {
149        self.placeholder = Some(placeholder.into());
150        self
151    }
152
153    pub fn width(mut self, width: impl Into<Length>) -> Self {
154        self.width = width.into();
155        self
156    }
157
158    /// Sets the message emitted with the chosen option.
159    pub fn on_select(mut self, on_select: impl Fn(T) -> Message + 'a) -> Self {
160        self.on_select = Some(Box::new(on_select));
161        self
162    }
163
164    /// Sets the message emitted with the chosen option. `None` disables the
165    /// select.
166    pub fn on_select_maybe(mut self, on_select: Option<impl Fn(T) -> Message + 'a>) -> Self {
167        self.on_select = on_select.map(|f| Box::new(f) as Box<dyn Fn(T) -> Message + 'a>);
168        self
169    }
170
171    /// Draws an element before an option's label, such as a colour
172    /// [swatch](crate::theme::swatch) or an icon, both in the open list and
173    /// in the field while that option is selected. Options it returns
174    /// `None` for show their label alone.
175    pub fn leading(mut self, leading: impl Fn(&T) -> Option<Element<'a, Message>> + 'a) -> Self {
176        self.leading = Some(Box::new(leading));
177        self
178    }
179
180    /// The most rows the open list shows before it scrolls. Defaults to
181    /// [`MAX_VISIBLE_ROWS`]; at least one row always shows.
182    pub fn max_visible_rows(mut self, rows: usize) -> Self {
183        self.max_rows = rows.max(1);
184        self
185    }
186
187    /// Whether a long list scrolls. On by default. Turned off, the list is
188    /// as tall as its options, however many there are.
189    pub fn scrollable(mut self, scrollable: bool) -> Self {
190        self.scrollable = scrollable;
191        self
192    }
193
194    /// Adds a search field to the open list: typing filters the options by
195    /// their labels, ignoring case, and highlights the first match. The
196    /// query is cleared when the list closes. Off by default.
197    pub fn searchable(mut self, searchable: bool) -> Self {
198        self.searchable = searchable;
199        self
200    }
201
202    /// Lets the user type a value that is not in the list. Enter with text
203    /// that matches no option sends the text, trimmed, to `on_custom`,
204    /// which returns the message for a valid value or `None` to turn it
205    /// down. A value turned down stays in the search field, in red with
206    /// the [`not_valid`](Self::not_valid) text below, until it is edited.
207    ///
208    /// With [`searchable`](Self::searchable) on as well, Enter chooses the
209    /// highlighted match and only sends the text when nothing matches.
210    /// Without it, the list is not filtered and the text only chooses an
211    /// option whose whole label it is.
212    pub fn on_custom(mut self, on_custom: impl Fn(String) -> Option<Message> + 'a) -> Self {
213        self.on_custom = Some(Box::new(on_custom));
214        self
215    }
216
217    /// Text in the empty search field. Defaults to "Search", or "Type a
218    /// value" when the list only takes custom values.
219    pub fn search_placeholder(mut self, placeholder: impl Into<String>) -> Self {
220        self.search_placeholder = Some(placeholder.into());
221        self
222    }
223
224    /// The editing shortcuts of the search field. Defaults to
225    /// [`Shortcuts::all`]; Escape always closes the list instead of
226    /// leaving the field.
227    pub fn shortcuts(mut self, shortcuts: Shortcuts) -> Self {
228        self.shortcuts = shortcuts;
229        self
230    }
231
232    /// Shown in place of rows when the search matches nothing. Defaults
233    /// to [`DEFAULT_EMPTY`].
234    pub fn empty(mut self, empty: impl Into<String>) -> Self {
235        self.empty = empty.into();
236        self
237    }
238
239    /// Shown in place of rows when [`on_custom`](Self::on_custom) turns the
240    /// typed value down, such as the format expected. Defaults to
241    /// [`DEFAULT_NOT_VALID`].
242    pub fn not_valid(mut self, text: impl Into<String>) -> Self {
243        self.not_valid = text.into();
244        self
245    }
246
247    /// How long a pause in typing starts a new type-ahead search. Defaults
248    /// to [`TYPE_AHEAD_PAUSE`].
249    pub fn type_ahead_pause(mut self, pause: Duration) -> Self {
250        self.type_ahead_pause = pause;
251        self
252    }
253
254    pub fn is_enabled(&self) -> bool {
255        self.on_select.is_some()
256    }
257}
258
259impl<'a, T, Message> From<Select<'a, T, Message>> for Element<'a, Message>
260where
261    T: ToString + PartialEq + Clone + 'a,
262    Message: Clone + 'a,
263{
264    fn from(select: Select<'a, T, Message>) -> Self {
265        let Select {
266            options,
267            selected,
268            placeholder,
269            width,
270            on_select,
271            leading,
272            max_rows,
273            scrollable,
274            searchable,
275            on_custom,
276            search_placeholder,
277            shortcuts,
278            empty,
279            not_valid,
280            type_ahead_pause,
281        } = select;
282        let enabled = on_select.is_some();
283        let leading_of = |option: &T| leading.as_ref().and_then(|leading| leading(option));
284        let label = selected.as_ref().map(ToString::to_string);
285        let has_value = label.is_some();
286
287        let text_colour = move |theme: &Theme| {
288            let style = style(&Tokens::of(theme), Status::Active, enabled);
289            if has_value {
290                style.text_color
291            } else {
292                style.placeholder_color
293            }
294        };
295        let chevron = themed(
296            crate::lucide!(ChevronDown),
297            CHEVRON_SIZE,
298            opacity(enabled),
299            move |theme| style(&Tokens::of(theme), Status::Active, enabled).handle_color,
300        );
301        let selected_leading = selected.as_ref().and_then(leading_of);
302        // A long label ends in an ellipsis rather than running under the chevron.
303        let field = row![]
304            .push(selected_leading)
305            .push(ellipsis(label.or(placeholder).unwrap_or_default()).colour(text_colour))
306            .push(chevron)
307            .spacing(space::SM)
308            .align_y(Alignment::Center)
309            .padding([(HEIGHT - LINE_HEIGHT) / 2.0, space::MD])
310            .width(width)
311            .height(HEIGHT);
312
313        let rows = options
314            .iter()
315            .map(|option| {
316                let is_selected = selected.as_ref() == Some(option);
317                option_row(&option.to_string(), leading_of(option), is_selected)
318            })
319            .collect();
320        let choices = options
321            .iter()
322            .map(|option| {
323                on_select
324                    .as_deref()
325                    .map(|on_select| on_select(option.clone()))
326            })
327            .collect();
328        let search = (searchable || on_custom.is_some()).then(|| {
329            let placeholder = search_placeholder
330                .unwrap_or_else(|| if searchable { "Search" } else { "Type a value" }.to_owned());
331            Search {
332                filters: searchable,
333                on_custom,
334                placeholder,
335                shortcuts,
336            }
337        });
338        let max_rows = scrollable.then_some(max_rows);
339        let list = List {
340            rows,
341            labels: matching::lowercase(&options),
342            choices,
343            selected: selected
344                .as_ref()
345                .and_then(|value| options.iter().position(|option| option == value)),
346            max_rows,
347            search,
348            pause: type_ahead_pause,
349            empty: NO_OPTIONS.to_owned(),
350            no_results: empty,
351            not_valid,
352        };
353        let list = menu::surface(Element::new(list)).width(Length::Fill).into();
354
355        Element::new(Picker {
356            field: field.into(),
357            list,
358            enabled,
359            behaviour: Behaviour {
360                placement: Placement::new(Side::Bottom, Align::Start),
361                match_width: true,
362                fit_height: max_rows.is_some(),
363                closes_itself: true,
364                ..Behaviour::default()
365            },
366        })
367    }
368}
369
370/// One option in the open list. The list draws the highlight behind it
371/// and sets the text colour.
372fn option_row<'a, Message: 'a>(
373    label: &str,
374    leading: Option<Element<'a, Message>>,
375    selected: bool,
376) -> Element<'a, Message> {
377    let trailing = if selected {
378        Trailing::Check
379    } else {
380        Trailing::None
381    };
382    let parts = Parts {
383        trailing,
384        ..Parts::label(label)
385    };
386    let content = menu::content(parts, RowStatus::Idle, false);
387    let content = match leading {
388        Some(leading) => row![leading, content]
389            .spacing(space::SM)
390            .align_y(Alignment::Center),
391        None => content,
392    };
393    menu::inset(container(content).padding(ROW_PADDING).width(Length::Fill))
394}
395
396/// The select widget: draws the field and floats the list while open.
397struct Picker<'a, Message> {
398    field: Element<'a, Message>,
399    list: Element<'a, Message>,
400    enabled: bool,
401    behaviour: Behaviour<'a, Message>,
402}
403
404#[derive(Debug, Default)]
405struct PickerState {
406    panel: anchored::State,
407    hovered: bool,
408    focus: focus::State,
409}
410
411/// Whether a key press opens the list of a focused, closed select.
412fn opens_list(key: Named) -> bool {
413    matches!(key, Named::Space | Named::Enter | Named::ArrowDown)
414}
415
416/// Whether a key press chooses the highlighted option of an open list.
417fn chooses(key: Named) -> bool {
418    matches!(key, Named::Space | Named::Enter)
419}
420
421impl<Message> Picker<'_, Message> {
422    /// Opens the list with a fresh highlight on the selected option.
423    fn open(&self, tree: &mut Tree) {
424        if let Some(list) = tree.children.get_mut(1) {
425            *list = Tree::new(&self.list);
426        }
427        let panel = &mut tree.state.downcast_mut::<PickerState>().panel;
428        panel.open = true;
429        panel.side = None;
430    }
431}
432
433impl<Message: Clone> Widget<Message, Theme, Renderer> for Picker<'_, Message> {
434    fn tag(&self) -> tree::Tag {
435        tree::Tag::of::<PickerState>()
436    }
437
438    fn state(&self) -> tree::State {
439        tree::State::new(PickerState::default())
440    }
441
442    fn children(&self) -> Vec<Tree> {
443        vec![Tree::new(&self.field), Tree::new(&self.list)]
444    }
445
446    fn diff(&self, tree: &mut Tree) {
447        tree.diff_children(&[&self.field, &self.list]);
448    }
449
450    fn size(&self) -> Size<Length> {
451        self.field.as_widget().size()
452    }
453
454    fn layout(
455        &mut self,
456        tree: &mut Tree,
457        renderer: &Renderer,
458        limits: &layout::Limits,
459    ) -> layout::Node {
460        self.field
461            .as_widget_mut()
462            .layout(&mut tree.children[0], renderer, limits)
463    }
464
465    fn draw(
466        &self,
467        tree: &Tree,
468        renderer: &mut Renderer,
469        theme: &Theme,
470        style: &renderer::Style,
471        layout: Layout<'_>,
472        cursor: mouse::Cursor,
473        viewport: &Rectangle,
474    ) {
475        let state = tree.state.downcast_ref::<PickerState>();
476        let bounds = layout.bounds();
477        let hovered = self.enabled && cursor.is_over(bounds);
478        let status = field_status(state.panel.open, hovered);
479        let field = self::style(&Tokens::of(theme), status, self.enabled);
480        <Renderer as renderer::Renderer>::fill_quad(
481            renderer,
482            renderer::Quad {
483                bounds,
484                border: field.border,
485                ..renderer::Quad::default()
486            },
487            field.background,
488        );
489        self.field.as_widget().draw(
490            &tree.children[0],
491            renderer,
492            theme,
493            style,
494            layout,
495            cursor,
496            viewport,
497        );
498        if self.enabled && state.focus.is_focused() {
499            focus::draw_ring(renderer, theme, bounds, radius::MD);
500        }
501    }
502
503    fn operate(
504        &mut self,
505        tree: &mut Tree,
506        layout: Layout<'_>,
507        renderer: &Renderer,
508        operation: &mut dyn Operation,
509    ) {
510        if self.enabled {
511            let state = tree.state.downcast_mut::<PickerState>();
512            focus::report(operation, None, layout.bounds(), &mut state.focus);
513        }
514        self.field
515            .as_widget_mut()
516            .operate(&mut tree.children[0], layout, renderer, operation);
517    }
518
519    fn update(
520        &mut self,
521        tree: &mut Tree,
522        event: &Event,
523        layout: Layout<'_>,
524        cursor: mouse::Cursor,
525        _renderer: &Renderer,
526        _clipboard: &mut dyn Clipboard,
527        shell: &mut Shell<'_, Message>,
528        _viewport: &Rectangle,
529    ) {
530        if !self.enabled {
531            return;
532        }
533        let state = tree.state.downcast_mut::<PickerState>();
534        if state.focus.update(event) {
535            shell.request_redraw();
536        }
537        // An open list keeps every key press its panel leaves, so keymaps
538        // behind it do not act while it is open. The list sends the
539        // highlighted option on Space or Enter and leaves the key here,
540        // where it closes the list. Tab closes it and goes on to move focus.
541        if let Event::Keyboard(keyboard::Event::KeyPressed { key, .. }) = event
542            && state.panel.open
543        {
544            if *key == keyboard::Key::Named(Named::Tab) {
545                state.panel.open = false;
546                shell.request_redraw();
547                return;
548            }
549            if focus::named_press(event).is_some_and(chooses) {
550                state.panel.open = false;
551                shell.request_redraw();
552            }
553            shell.capture_event();
554            return;
555        }
556        if state.focus.is_focused() && focus::named_press(event).is_some_and(opens_list) {
557            self.open(tree);
558            shell.capture_event();
559            shell.request_redraw();
560            return;
561        }
562        let over = cursor.is_over(layout.bounds());
563        if over != state.hovered {
564            state.hovered = over;
565            shell.request_redraw();
566        }
567        let pressed = matches!(
568            event,
569            Event::Mouse(mouse::Event::ButtonPressed(mouse::Button::Left))
570                | Event::Touch(touch::Event::FingerPressed { .. })
571        );
572        if !pressed || !over {
573            return;
574        }
575        if state.panel.open {
576            state.panel.open = false;
577        } else {
578            self.open(tree);
579        }
580        shell.capture_event();
581        shell.request_redraw();
582    }
583
584    fn mouse_interaction(
585        &self,
586        _tree: &Tree,
587        layout: Layout<'_>,
588        cursor: mouse::Cursor,
589        _viewport: &Rectangle,
590        _renderer: &Renderer,
591    ) -> mouse::Interaction {
592        if self.enabled && cursor.is_over(layout.bounds()) {
593            mouse::Interaction::Pointer
594        } else {
595            mouse::Interaction::default()
596        }
597    }
598
599    fn overlay<'b>(
600        &'b mut self,
601        tree: &'b mut Tree,
602        layout: Layout<'b>,
603        _renderer: &Renderer,
604        _viewport: &Rectangle,
605        translation: Vector,
606    ) -> Option<overlay::Element<'b, Message, Theme, Renderer>> {
607        let Tree {
608            state, children, ..
609        } = tree;
610        let state = state.downcast_mut::<PickerState>();
611        if !self.enabled || !state.panel.open {
612            return None;
613        }
614        let list_tree = children.get_mut(1)?;
615        Some(anchored::floating(
616            &mut self.list,
617            list_tree,
618            &mut state.panel,
619            &self.behaviour,
620            layout.bounds() + translation,
621        ))
622    }
623}
624
625/// The field's status: opened while the list shows, hovered under the
626/// pointer, active otherwise.
627fn field_status(open: bool, hovered: bool) -> Status {
628    match (open, hovered) {
629        (true, is_hovered) => Status::Opened { is_hovered },
630        (false, true) => Status::Hovered,
631        (false, false) => Status::Active,
632    }
633}
634
635/// The iced pick list style for a status.
636pub fn style(tokens: &Tokens, status: Status, enabled: bool) -> pick_list::Style {
637    let border = match status {
638        Status::Active => tokens.border,
639        Status::Hovered => mix(tokens.border, tokens.foreground, 0.3),
640        Status::Opened { .. } => mix(tokens.border, tokens.foreground, 0.6),
641    };
642    let style = pick_list::Style {
643        text_color: tokens.foreground,
644        placeholder_color: tokens.muted_foreground,
645        handle_color: tokens.muted_foreground,
646        // Transparent so the trigger takes the colour of its surface.
647        background: Background::Color(Color::TRANSPARENT),
648        border: Border {
649            color: border,
650            width: 1.0,
651            radius: radius::MD.into(),
652        },
653    };
654
655    if enabled {
656        return style;
657    }
658    pick_list::Style {
659        text_color: fade(tokens.foreground, 0.5),
660        placeholder_color: fade(tokens.muted_foreground, 0.5),
661        handle_color: fade(tokens.muted_foreground, 0.5),
662        background: Background::Color(tokens.disabled_field()),
663        border: Border {
664            color: fade(tokens.border, 0.5),
665            ..style.border
666        },
667    }
668}
669
670/// What a select keyboard shortcut does.
671#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
672pub enum Action {
673    Next,
674    Previous,
675}
676
677impl Action {
678    /// The option to select after this action, to send through the
679    /// select's `on_select` message. Stops at the ends of the list, and
680    /// returns `None` when the selection would not change. With nothing
681    /// selected, `Next` picks the first option and `Previous` the last.
682    pub fn apply<T: PartialEq + Clone>(self, options: &[T], selected: Option<&T>) -> Option<T> {
683        let current = selected.and_then(|value| options.iter().position(|option| option == value));
684        let target = match (self, current) {
685            (Action::Next, None) => 0,
686            (Action::Previous, None) => options.len().checked_sub(1)?,
687            (Action::Next, Some(index)) => index + 1,
688            (Action::Previous, Some(index)) => index.checked_sub(1)?,
689        };
690        options.get(target).cloned()
691    }
692}
693
694impl keys::Action for Action {
695    const ALL: &'static [Self] = &[Action::Next, Action::Previous];
696
697    fn defaults() -> Keymap<Self> {
698        default_keymap()
699    }
700
701    fn name(self) -> &'static str {
702        match self {
703            Action::Next => "Next",
704            Action::Previous => "Previous",
705        }
706    }
707
708    fn description(self) -> &'static str {
709        match self {
710            Action::Next => "Selects the next option, stopping at the last.",
711            Action::Previous => "Selects the previous option, stopping at the first.",
712        }
713    }
714}
715
716/// The default select shortcuts:
717///
718/// | Keys | Action |
719/// | --- | --- |
720/// | `ArrowDown` | [`Action::Next`] |
721/// | `ArrowUp` | [`Action::Previous`] |
722///
723/// These change the value without opening the menu. Shortcuts are
724/// app-wide, so an app with several selects routes them to the one it
725/// considers current. A select with keyboard focus keeps ArrowDown, which
726/// opens its list instead.
727pub fn default_keymap() -> Keymap<Action> {
728    Keymap::new()
729        .bind(Chord::named(Named::ArrowDown), Action::Next)
730        .bind(Chord::named(Named::ArrowUp), Action::Previous)
731}
732
733#[cfg(test)]
734mod tests {
735    use super::*;
736    use crate::theme::{dark, light};
737
738    fn press(keymap: &Keymap<Action>, chord: &str) -> Option<Action> {
739        let chord: Chord = chord.parse().unwrap();
740        keymap.resolve(chord.key(), chord.modifiers())
741    }
742
743    #[test]
744    fn default_keymap_and_overrides() {
745        let keymap = default_keymap();
746        assert_eq!(press(&keymap, "ArrowDown"), Some(Action::Next));
747        assert_eq!(press(&keymap, "ArrowUp"), Some(Action::Previous));
748        let custom = keymap
749            .bind("J".parse().unwrap(), Action::Next)
750            .unbind(&"ArrowDown".parse().unwrap());
751        assert_eq!(press(&custom, "j"), Some(Action::Next));
752        assert_eq!(press(&custom, "ArrowDown"), None);
753    }
754
755    #[test]
756    fn next_and_previous_stop_at_the_ends() {
757        let options = ["a", "b", "c"];
758        assert_eq!(Action::Next.apply(&options, Some(&"a")), Some("b"));
759        assert_eq!(Action::Next.apply(&options, Some(&"c")), None);
760        assert_eq!(Action::Previous.apply(&options, Some(&"b")), Some("a"));
761        assert_eq!(Action::Previous.apply(&options, Some(&"a")), None);
762    }
763
764    #[test]
765    fn without_a_selection_next_and_previous_pick_an_end() {
766        let options = ["a", "b", "c"];
767        assert_eq!(Action::Next.apply(&options, None), Some("a"));
768        assert_eq!(Action::Previous.apply(&options, None), Some("c"));
769        assert_eq!(Action::Next.apply(&options, Some(&"z")), Some("a"));
770        let empty: [&str; 0] = [];
771        assert_eq!(Action::Next.apply(&empty, None), None);
772        assert_eq!(Action::Previous.apply(&empty, None), None);
773    }
774
775    const STATES: [Status; 4] = [
776        Status::Active,
777        Status::Hovered,
778        Status::Opened { is_hovered: false },
779        Status::Opened { is_hovered: true },
780    ];
781
782    #[test]
783    fn default_builder_has_no_selection_and_is_disabled() {
784        let s: Select<'_, &str, ()> = select(vec!["a", "b"], None);
785        assert_eq!(s.options.len(), 2);
786        assert!(s.selected.is_none());
787        assert!(s.placeholder.is_none());
788        assert_eq!(s.width, Length::Fixed(200.0));
789        assert!(!s.is_enabled());
790        assert!(s.leading.is_none());
791    }
792
793    #[test]
794    fn leading_is_asked_per_option() {
795        let s: Select<'_, &str, ()> = select(vec!["red", "plain"], None).leading(|option| {
796            (*option == "red")
797                .then(|| crate::theme::swatch_color(Color::from_rgb(1.0, 0.0, 0.0)).into())
798        });
799        let Some(leading) = s.leading.as_ref() else {
800            panic!("leading is set");
801        };
802        assert!(leading(&"red").is_some());
803        assert!(leading(&"plain").is_none());
804    }
805
806    #[test]
807    fn builder_sets_placeholder_and_message() {
808        const OPTIONS: &[u8] = &[1, 2, 3];
809        let s: Select<'_, u8, u8> = select(OPTIONS, Some(2))
810            .placeholder("Pick a number")
811            .on_select(|v| v);
812        assert_eq!(s.placeholder.as_deref(), Some("Pick a number"));
813        assert!(s.is_enabled());
814        assert!(matches!(s.options, Cow::Borrowed(_)));
815    }
816
817    #[test]
818    fn on_select_maybe_enables_only_with_a_message() {
819        let enabled: Select<'_, u8, u8> = select(vec![1, 2], None).on_select_maybe(Some(|v| v));
820        assert!(enabled.is_enabled());
821        let disabled: Select<'_, u8, u8> =
822            select(vec![1, 2], None).on_select_maybe(None::<fn(u8) -> u8>);
823        assert!(!disabled.is_enabled());
824    }
825
826    #[test]
827    fn hover_and_open_strengthen_the_border() {
828        for theme in [light(), dark()] {
829            let tokens = Tokens::of(&theme);
830            let borders = STATES.map(|status| style(&tokens, status, true).border.color);
831            assert_ne!(borders[0], borders[1]);
832            assert_ne!(borders[1], borders[2]);
833            assert_eq!(borders[2], borders[3]);
834        }
835    }
836
837    #[test]
838    fn placeholder_is_muted() {
839        for theme in [light(), dark()] {
840            let tokens = Tokens::of(&theme);
841            let style = style(&tokens, Status::Active, true);
842            assert_eq!(style.placeholder_color, tokens.muted_foreground);
843            assert_ne!(style.placeholder_color, style.text_color);
844        }
845    }
846
847    #[test]
848    fn disabled_fades_text_and_uses_the_disabled_field_background() {
849        for theme in [light(), dark()] {
850            let tokens = Tokens::of(&theme);
851            for status in STATES {
852                let disabled = style(&tokens, status, false);
853                assert!((disabled.text_color.a - tokens.foreground.a * 0.5).abs() < 1e-6);
854                assert_eq!(
855                    disabled.background,
856                    Background::Color(tokens.disabled_field())
857                );
858            }
859        }
860    }
861
862    #[test]
863    fn an_enabled_trigger_takes_the_colour_of_its_surface() {
864        for theme in [light(), dark()] {
865            let tokens = Tokens::of(&theme);
866            for status in STATES {
867                let enabled = style(&tokens, status, true);
868                assert_eq!(enabled.background, Background::Color(Color::TRANSPARENT));
869            }
870        }
871    }
872
873    #[test]
874    fn long_lists_scroll_by_default_and_search_and_custom_values_are_off() {
875        let s: Select<'_, &str, ()> = select(vec!["a", "b"], None);
876        assert_eq!(s.max_rows, MAX_VISIBLE_ROWS);
877        assert!(s.scrollable);
878        assert!(!s.searchable);
879        assert!(s.on_custom.is_none());
880        assert_eq!(s.shortcuts, Shortcuts::all());
881        assert_eq!(s.empty, DEFAULT_EMPTY);
882        assert_eq!(s.not_valid, DEFAULT_NOT_VALID);
883        assert_eq!(s.type_ahead_pause, TYPE_AHEAD_PAUSE);
884    }
885
886    #[test]
887    fn the_row_limit_and_scrolling_are_set_in_any_order() {
888        let s: Select<'_, &str, ()> = select(vec!["a"], None).max_visible_rows(0);
889        assert_eq!(s.max_rows, 1, "at least one row");
890        let s: Select<'_, &str, ()> = select(vec!["a"], None)
891            .scrollable(false)
892            .max_visible_rows(5);
893        assert!(!s.scrollable, "a row limit does not turn scrolling back on");
894        let s: Select<'_, &str, ()> = select(vec!["a"], None)
895            .max_visible_rows(5)
896            .scrollable(false)
897            .scrollable(true);
898        assert_eq!(s.max_rows, 5, "the limit is kept");
899        assert!(s.scrollable);
900    }
901
902    #[test]
903    fn search_and_custom_values_are_set_by_the_builder() {
904        let s: Select<'_, &str, String> = select(vec!["a"], None)
905            .searchable(true)
906            .on_custom(|text| (!text.is_empty()).then_some(text))
907            .search_placeholder("Find a time")
908            .empty("Nothing")
909            .not_valid("Use hh:mm")
910            .shortcuts(Shortcuts::none())
911            .type_ahead_pause(Duration::from_millis(500));
912        assert!(s.searchable);
913        assert_eq!(s.search_placeholder.as_deref(), Some("Find a time"));
914        assert_eq!(s.empty, "Nothing");
915        assert_eq!(s.not_valid, "Use hh:mm");
916        assert_eq!(s.shortcuts, Shortcuts::none());
917        assert_eq!(s.type_ahead_pause, Duration::from_millis(500));
918        let Some(on_custom) = s.on_custom.as_ref() else {
919            panic!("on_custom is set");
920        };
921        assert_eq!(on_custom("x".to_owned()), Some("x".to_owned()));
922        assert_eq!(on_custom(String::new()), None);
923    }
924
925    #[test]
926    fn keys_that_open_and_choose() {
927        for key in [Named::Space, Named::Enter, Named::ArrowDown] {
928            assert!(opens_list(key), "{key:?}");
929        }
930        assert!(!opens_list(Named::ArrowUp));
931        assert!(!opens_list(Named::Escape));
932        assert!(chooses(Named::Space) && chooses(Named::Enter));
933        assert!(!chooses(Named::ArrowDown));
934    }
935
936    #[test]
937    fn field_status_follows_the_list_and_the_pointer() {
938        assert_eq!(field_status(false, false), Status::Active);
939        assert_eq!(field_status(false, true), Status::Hovered);
940        assert_eq!(
941            field_status(true, false),
942            Status::Opened { is_hovered: false }
943        );
944        assert_eq!(
945            field_status(true, true),
946            Status::Opened { is_hovered: true }
947        );
948    }
949}