Skip to main content

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