Skip to main content

lumen_dioxus/inputs/
select.rs

1//! `Select`: Lumen's default styled option list, backed by a hidden native `<select>`.
2
3// cspell:words focusin focusout onfocusin onfocusout onmousedown
4
5use std::rc::Rc;
6use std::time::Duration;
7
8use dioxus::prelude::*;
9
10use super::select_keyboard::{Typeahead, extend_typeahead, is_space, printable_key};
11use crate::class::{Glass, compose};
12use crate::hooks::use_unique_id;
13use crate::overlay::{DismissLayer, focus_element};
14use crate::{ControlSize, SelectOption};
15
16/// Trigger text while nothing is selected and no placeholder is set.
17const DEFAULT_TRIGGER_TEXT: &str = "Select an option";
18/// Listbox text when there are no options and no `empty_message` is set.
19const DEFAULT_EMPTY_MESSAGE: &str = "No options available";
20/// Lumen's web runtime skips roots that carry `data-ui-owner`; it only checks that the attribute
21/// exists. lumen-react's value keeps the markup identical.
22const OWNER: &str = "react";
23/// How long a `focusout` waits for a `focusin` inside the select before it closes the list. Dioxus
24/// focus events carry no `relatedTarget`, so the move is detected by the event that follows.
25const FOCUS_EXIT_DELAY: Duration = Duration::from_millis(30);
26
27/// Props for [`Select`].
28#[derive(Props, Clone, PartialEq)]
29pub struct SelectProps {
30    /// The choices, in order. A first option with an empty value is the placeholder choice: it
31    /// stays selectable and takes `placeholder` as its label when its own label is empty.
32    #[props(default)]
33    pub options: Vec<SelectOption>,
34    /// Controlled value. Leave unset to let the select manage itself.
35    #[props(into)]
36    pub value: Option<String>,
37    /// Initial value when uncontrolled. Defaults to no selection.
38    #[props(default, into)]
39    pub default_value: String,
40    /// Called with the option value every time the person picks an option.
41    pub on_value_change: Option<EventHandler<String>>,
42    /// Trigger text while nothing is selected. Defaults to "Select an option".
43    #[props(into)]
44    pub placeholder: Option<String>,
45    /// Listbox text when there are no options. Defaults to "No options available".
46    #[props(into)]
47    pub empty_message: Option<String>,
48    /// Disables the trigger and the native control.
49    #[props(default)]
50    pub disabled: bool,
51    /// Marks the value as required for form validation.
52    #[props(default)]
53    pub required: bool,
54    /// Id of the native control. The trigger is `{id}-trigger` and the listbox `{id}-listbox`.
55    /// Generated when unset.
56    #[props(into)]
57    pub id: Option<String>,
58    /// Form field name. When set, a hidden input submits the selected value.
59    #[props(into)]
60    pub name: Option<String>,
61    /// Id of the form that owns the field when it is outside that form.
62    #[props(into)]
63    pub form: Option<String>,
64    /// Trigger height.
65    #[props(default)]
66    pub visual_size: ControlSize,
67    /// Glass intensity of the field and its listbox.
68    #[props(default, into)]
69    pub glass: Glass,
70    /// Accessible name of the trigger and its listbox.
71    #[props(into)]
72    pub aria_label: Option<String>,
73    /// Id of the element that names the trigger and its listbox.
74    #[props(into)]
75    pub aria_labelledby: Option<String>,
76    /// Ids of elements that describe the trigger.
77    #[props(into)]
78    pub aria_describedby: Option<String>,
79    /// `aria-invalid` of the trigger, such as `"true"`.
80    #[props(into)]
81    pub aria_invalid: Option<String>,
82    /// Id of the error message of the trigger.
83    #[props(into)]
84    pub aria_errormessage: Option<String>,
85    /// Extra classes appended to the field after the Lumen classes.
86    #[props(into)]
87    pub class: Option<String>,
88    /// Any other `<select>` or global attribute. They go to the hidden native control, like the
89    /// rest props of lumen-react's `Select`.
90    #[props(extends = GlobalAttributes, extends = select)]
91    pub attributes: Vec<Attribute>,
92}
93
94/// Options after the placeholder choice takes the `placeholder` text, like lumen-react's
95/// `useSelectSourceOptions` for the `options` prop.
96fn source_options(options: &[SelectOption], placeholder: Option<&str>) -> Vec<SelectOption> {
97    let mut source = options.to_vec();
98
99    if let (Some(first), Some(placeholder)) = (source.first_mut(), placeholder)
100        && first.value.is_empty()
101        && first.label.is_empty()
102        && !placeholder.is_empty()
103    {
104        first.label = placeholder.to_string();
105    }
106
107    source
108}
109
110/// One of the keys that move between options.
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub(crate) enum SelectNavKey {
113    /// `ArrowDown`: the next option, looping.
114    Down,
115    /// `ArrowUp`: the previous option, looping.
116    Up,
117    /// `Home`: the first option.
118    Home,
119    /// `End`: the last option.
120    End,
121}
122
123impl SelectNavKey {
124    fn from_key(key: &Key) -> Option<Self> {
125        match key {
126            Key::ArrowDown => Some(Self::Down),
127            Key::ArrowUp => Some(Self::Up),
128            Key::Home => Some(Self::Home),
129            Key::End => Some(Self::End),
130            _ => None,
131        }
132    }
133}
134
135/// Indexes of the options that can take focus.
136fn enabled_indexes(options: &[SelectOption]) -> Vec<usize> {
137    options
138        .iter()
139        .enumerate()
140        .filter(|(_, option)| !option.disabled)
141        .map(|(index, _)| index)
142        .collect()
143}
144
145/// Position in `items` of the option navigation starts from: `current`, then the selected enabled
146/// option, then the first enabled one. Like `indexOf`, a missing `current` counts as the first.
147fn start_position(
148    options: &[SelectOption],
149    items: &[usize],
150    selected: &str,
151    current: Option<usize>,
152) -> Option<usize> {
153    let selected_item = items
154        .iter()
155        .copied()
156        .find(|index| options[*index].value == selected);
157    let current = current
158        .or(selected_item)
159        .or_else(|| items.first().copied())?;
160
161    items.iter().position(|index| *index == current)
162}
163
164/// The option a navigation key focuses, like lumen-react's `focusOption`.
165pub(crate) fn select_step(
166    options: &[SelectOption],
167    selected: &str,
168    current: Option<usize>,
169    key: SelectNavKey,
170) -> Option<usize> {
171    let items = enabled_indexes(options);
172    let len = items.len();
173
174    if len == 0 {
175        return None;
176    }
177
178    let position = start_position(options, &items, selected, current).unwrap_or(0);
179    let next = match key {
180        SelectNavKey::Home => 0,
181        SelectNavKey::End => len - 1,
182        SelectNavKey::Down => (position + 1) % len,
183        SelectNavKey::Up => (position + len - 1) % len,
184    };
185
186    items.get(next).copied()
187}
188
189/// The option Enter or Space focuses when they open the list: the selected enabled option, then
190/// the first enabled one.
191pub(crate) fn select_open_target(options: &[SelectOption], selected: &str) -> Option<usize> {
192    let items = enabled_indexes(options);
193
194    items
195        .iter()
196        .copied()
197        .find(|index| options[*index].value == selected)
198        .or_else(|| items.first().copied())
199}
200
201/// The option a typeahead query focuses, like lumen-react's `focusTypeaheadOption`: the search
202/// starts after the current option and wraps, and compares trimmed lowercase labels.
203pub(crate) fn select_typeahead(
204    options: &[SelectOption],
205    selected: &str,
206    current: Option<usize>,
207    query: &str,
208) -> Option<usize> {
209    let items = enabled_indexes(options);
210
211    if items.is_empty() || query.is_empty() {
212        return None;
213    }
214
215    let start =
216        start_position(options, &items, selected, current).map_or(0, |position| position + 1);
217    let start = start.min(items.len());
218
219    items[start..]
220        .iter()
221        .chain(&items[..start])
222        .copied()
223        .find(|index| {
224            options[*index]
225                .label
226                .trim()
227                .to_lowercase()
228                .starts_with(query)
229        })
230}
231
232/// Values the select needs in its event handlers, refreshed on every render.
233#[derive(Clone, Default, PartialEq)]
234struct SelectSnapshot {
235    options: Vec<SelectOption>,
236    value: String,
237    controlled: bool,
238    disabled: bool,
239    on_value_change: Option<EventHandler<String>>,
240}
241
242/// The open state, focus target, and typeahead of one select. It is `Copy`, so every handler can
243/// capture it.
244#[derive(Clone, Copy)]
245struct SelectMachine {
246    snapshot: CopyValue<SelectSnapshot>,
247    internal: Signal<String>,
248    open: Signal<bool>,
249    /// The option keyboard focus is on. Dioxus Native cannot move focus, so keys that reach the
250    /// trigger while an option is active act on that option.
251    active: Signal<Option<usize>>,
252    /// An option to focus once the list is visible.
253    pending_focus: Signal<Option<usize>>,
254    typeahead: CopyValue<Typeahead>,
255    focus_generation: CopyValue<u64>,
256    option_nodes: CopyValue<Vec<Option<Rc<MountedData>>>>,
257    trigger_node: CopyValue<Option<Rc<MountedData>>>,
258}
259
260fn set_if_changed<T: PartialEq + 'static>(mut signal: Signal<T>, next: T) {
261    if *signal.peek() != next {
262        signal.set(next);
263    }
264}
265
266impl SelectMachine {
267    fn is_open(self) -> bool {
268        *self.open.peek()
269    }
270
271    fn close(self) {
272        set_if_changed(self.open, false);
273        set_if_changed(self.active, None);
274        set_if_changed(self.pending_focus, None);
275    }
276
277    fn reset_typeahead(mut self) {
278        self.typeahead.write().reset();
279    }
280
281    fn toggle(self) {
282        if self.snapshot.peek().disabled {
283            return;
284        }
285
286        self.reset_typeahead();
287
288        if self.is_open() {
289            self.close();
290        } else {
291            set_if_changed(self.open, true);
292        }
293    }
294
295    /// Opens the list and focuses `target` once it is visible.
296    fn open_and_focus(self, target: Option<usize>) {
297        set_if_changed(self.open, true);
298        self.focus_option(target);
299    }
300
301    fn focus_option(mut self, target: Option<usize>) {
302        if let Some(index) = target {
303            set_if_changed(self.active, Some(index));
304            self.pending_focus.set(Some(index));
305        }
306    }
307
308    fn focus_trigger(self) {
309        focus_element(self.trigger_node.peek().clone());
310    }
311
312    fn commit(self, value: String) {
313        let (controlled, handler) = {
314            let snapshot = self.snapshot.peek();
315            (snapshot.controlled, snapshot.on_value_change)
316        };
317
318        if !controlled {
319            let mut internal = self.internal;
320            internal.set(value.clone());
321        }
322
323        if let Some(handler) = handler {
324            handler.call(value);
325        }
326    }
327
328    /// Picks an option, closes the list, and returns focus to the trigger.
329    fn choose(self, index: usize) {
330        let value = {
331            let snapshot = self.snapshot.peek();
332
333            match snapshot.options.get(index) {
334                Some(option) if !option.disabled && !snapshot.disabled => option.value.clone(),
335                _ => return,
336            }
337        };
338
339        self.commit(value);
340        self.close();
341        self.focus_trigger();
342    }
343
344    /// Printable keys build a query that opens the list and focuses the next matching option.
345    fn typeahead_key(self, event: &KeyboardEvent, current: Option<usize>) -> bool {
346        let Some(text) = printable_key(event) else {
347            return false;
348        };
349
350        // Space only extends an active query; otherwise it opens or selects like Enter.
351        if text == " " && (self.typeahead.peek().is_empty() || !self.is_open()) {
352            return false;
353        }
354
355        event.prevent_default();
356
357        let query = extend_typeahead(self.typeahead, &text);
358        let target = {
359            let snapshot = self.snapshot.peek();
360            select_typeahead(&snapshot.options, &snapshot.value, current, &query)
361        };
362
363        self.open_and_focus(target);
364        true
365    }
366
367    fn trigger_key(self, event: &KeyboardEvent) {
368        if event.is_composing() {
369            return;
370        }
371
372        let key = event.key();
373
374        // Tab leaves the select; close it here because Dioxus Native has no focus events.
375        if key == Key::Tab {
376            if self.is_open() {
377                self.reset_typeahead();
378                self.close();
379            }
380
381            return;
382        }
383
384        let active = *self.active.peek();
385
386        if self.is_open()
387            && let Some(active) = active
388        {
389            self.option_key(active, event);
390            return;
391        }
392
393        if self.typeahead_key(event, None) {
394            return;
395        }
396
397        if key == Key::Escape && self.is_open() {
398            event.prevent_default();
399            event.stop_propagation();
400            self.close();
401            return;
402        }
403
404        let nav = SelectNavKey::from_key(&key);
405
406        if nav.is_none() && key != Key::Enter && !is_space(&key) {
407            return;
408        }
409
410        event.prevent_default();
411        self.reset_typeahead();
412
413        let target = {
414            let snapshot = self.snapshot.peek();
415
416            match nav {
417                Some(nav) => select_step(&snapshot.options, &snapshot.value, None, nav),
418                None => select_open_target(&snapshot.options, &snapshot.value),
419            }
420        };
421
422        self.open_and_focus(target);
423    }
424
425    fn option_key(self, index: usize, event: &KeyboardEvent) {
426        if event.is_composing() || self.typeahead_key(event, Some(index)) {
427            return;
428        }
429
430        let key = event.key();
431
432        if key == Key::Escape && self.is_open() {
433            event.prevent_default();
434            event.stop_propagation();
435            self.close();
436            self.focus_trigger();
437            return;
438        }
439
440        if key == Key::Enter || is_space(&key) {
441            event.prevent_default();
442            self.choose(index);
443            return;
444        }
445
446        let Some(nav) = SelectNavKey::from_key(&key) else {
447            return;
448        };
449
450        event.prevent_default();
451        self.reset_typeahead();
452
453        let target = {
454            let snapshot = self.snapshot.peek();
455            select_step(&snapshot.options, &snapshot.value, Some(index), nav)
456        };
457
458        self.focus_option(target);
459    }
460
461    fn focus_entered(mut self) {
462        let next = self.focus_generation.peek().wrapping_add(1);
463        self.focus_generation.set(next);
464    }
465
466    /// Closes the list when focus leaves the select instead of moving inside it.
467    fn focus_left(mut self) {
468        let generation = self.focus_generation.peek().wrapping_add(1);
469        self.focus_generation.set(generation);
470
471        spawn(async move {
472            crate::time::sleep(FOCUS_EXIT_DELAY).await;
473
474            if *self.focus_generation.peek() == generation {
475                self.reset_typeahead();
476                self.close();
477            }
478        });
479    }
480
481    fn store_option(mut self, index: usize, node: Rc<MountedData>) {
482        let mut nodes = self.option_nodes.write();
483
484        if nodes.len() <= index {
485            nodes.resize(index + 1, None);
486        }
487
488        nodes[index] = Some(node);
489    }
490}
491
492fn size_class(size: ControlSize) -> Option<&'static str> {
493    match size {
494        ControlSize::Default => None,
495        ControlSize::Sm => Some("ui-select--sm"),
496        ControlSize::Lg => Some("ui-select--lg"),
497    }
498}
499
500/// Lumen's default option list: a `combobox` trigger that opens a `listbox` of options, with
501/// keyboard navigation and typeahead, plus a hidden native `<select>` for labels and validation.
502///
503/// Arrow keys, Home, and End open the list and move between enabled options; Enter and Space
504/// pick; Escape closes and returns focus to the trigger; printable keys search option labels.
505/// A named select submits its value through a hidden input on every renderer.
506#[component]
507pub fn Select(props: SelectProps) -> Element {
508    let generated = use_unique_id();
509    let select_id = props
510        .id
511        .clone()
512        .unwrap_or_else(|| format!("ui-select-{generated}"));
513    let list_id = format!("{select_id}-listbox");
514    let trigger_id = format!("{select_id}-trigger");
515
516    let internal = use_signal(|| props.default_value.clone());
517    let value = props.value.clone().unwrap_or_else(|| internal.cloned());
518    let options = source_options(&props.options, props.placeholder.as_deref());
519    let has_placeholder_option = props
520        .options
521        .first()
522        .is_some_and(|option| option.value.is_empty());
523    let selected = options.iter().find(|option| option.value == value);
524    let has_selection = selected.is_some() && !value.is_empty();
525    let trigger_text = selected
526        .map(|option| option.label.clone())
527        .or_else(|| props.placeholder.clone())
528        .unwrap_or_else(|| DEFAULT_TRIGGER_TEXT.to_string());
529    // The native value stays empty while nothing matches, so forms never submit an option the
530    // person did not choose and `required` reports a missing value.
531    let native_value = if selected.is_some() {
532        value.clone()
533    } else {
534        String::new()
535    };
536    let submitted = props
537        .name
538        .clone()
539        .filter(|_| !props.disabled && selected.is_some_and(|option| !option.disabled));
540    let placeholder = props.placeholder.clone().filter(|text| !text.is_empty());
541    let unmatched = selected.is_none();
542
543    let mut snapshot = use_hook(|| CopyValue::new(SelectSnapshot::default()));
544    snapshot.set(SelectSnapshot {
545        options: options.clone(),
546        value: value.clone(),
547        controlled: props.value.is_some(),
548        disabled: props.disabled,
549        on_value_change: props.on_value_change,
550    });
551
552    let machine = SelectMachine {
553        snapshot,
554        internal,
555        open: use_signal(|| false),
556        active: use_signal(|| None),
557        pending_focus: use_signal(|| None),
558        typeahead: use_hook(|| CopyValue::new(Typeahead::default())),
559        focus_generation: use_hook(|| CopyValue::new(0)),
560        option_nodes: use_hook(|| CopyValue::new(Vec::new())),
561        trigger_node: use_hook(|| CopyValue::new(None)),
562    };
563
564    // Options are hidden until the open render is applied, so focus moves after it.
565    use_effect(move || {
566        let Some(index) = *machine.pending_focus.read() else {
567            return;
568        };
569
570        if !*machine.open.read() {
571            return;
572        }
573
574        let node = machine.option_nodes.peek().get(index).cloned().flatten();
575        focus_element(node);
576
577        let mut pending = machine.pending_focus;
578        pending.set(None);
579    });
580
581    let open = *machine.open.read();
582    let active = *machine.active.read();
583    let sizes = size_class(props.visual_size);
584    let glass = props.glass.class("ui-select-field");
585    let class = compose([
586        Some("ui-select-field"),
587        glass.as_deref(),
588        props.class.as_deref(),
589    ]);
590    let native_class = compose([Some("ui-select ui-select__native"), sizes]);
591    let trigger_class = compose([Some("ui-select ui-select__trigger"), sizes]);
592    let empty_message = props
593        .empty_message
594        .clone()
595        .unwrap_or_else(|| DEFAULT_EMPTY_MESSAGE.to_string());
596
597    rsx! {
598        div {
599            class,
600            "data-placeholder": if has_selection { "false" } else { "true" },
601            "data-ui-select": "true",
602            "data-ui-owner": OWNER,
603            "data-ui-glass-track": (props.glass != Glass::Off).then_some("true"),
604            onfocusin: move |_| machine.focus_entered(),
605            onfocusout: move |_| machine.focus_left(),
606            select {
607                aria_describedby: props.aria_describedby.clone(),
608                aria_errormessage: props.aria_errormessage.clone(),
609                aria_hidden: "true",
610                aria_invalid: props.aria_invalid.clone(),
611                aria_label: props.aria_label.clone(),
612                aria_labelledby: props.aria_labelledby.clone(),
613                class: native_class,
614                "data-ui-enhanced": "true",
615                "data-ui-select-native": "true",
616                disabled: props.disabled,
617                form: props.form.clone(),
618                id: select_id,
619                required: props.required,
620                tabindex: "-1",
621                // Labels and validation focus the hidden control; show focus on the trigger.
622                onfocus: move |_| machine.focus_trigger(),
623                onchange: move |event| machine.commit(event.value()),
624                ..props.attributes,
625                if !has_placeholder_option {
626                    if let Some(text) = placeholder.clone() {
627                        option {
628                            "data-ui-select-placeholder": "true",
629                            disabled: true,
630                            selected: native_value.is_empty(),
631                            value: "",
632                            "{text}"
633                        }
634                    } else if unmatched {
635                        option {
636                            "data-ui-select-placeholder": "true",
637                            disabled: true,
638                            hidden: true,
639                            selected: native_value.is_empty(),
640                            value: "",
641                        }
642                    }
643                }
644                for choice in options.iter() {
645                    option {
646                        disabled: choice.disabled,
647                        selected: choice.value == native_value,
648                        value: choice.value.clone(),
649                        "{choice.label}"
650                    }
651                }
652            }
653            if let Some(name) = submitted {
654                input {
655                    form: props.form.clone(),
656                    name,
657                    r#type: "hidden",
658                    value: native_value.clone(),
659                }
660            }
661            div { class: "ui-select__control", "data-ui-select-control": "true",
662                button {
663                    aria_controls: list_id.clone(),
664                    aria_describedby: props.aria_describedby.clone(),
665                    aria_errormessage: props.aria_errormessage.clone(),
666                    aria_expanded: if open { "true" } else { "false" },
667                    aria_haspopup: "listbox",
668                    aria_invalid: props.aria_invalid.clone(),
669                    aria_label: props.aria_label.clone(),
670                    aria_labelledby: props.aria_labelledby.clone(),
671                    aria_required: props.required.then_some("true"),
672                    class: trigger_class,
673                    "data-ui-select-trigger": "true",
674                    disabled: props.disabled,
675                    id: trigger_id,
676                    role: "combobox",
677                    r#type: "button",
678                    onclick: move |_| machine.toggle(),
679                    onkeydown: move |event| machine.trigger_key(&event),
680                    onfocus: move |_| set_if_changed(machine.active, None),
681                    onmounted: move |event| {
682                        let mut node = machine.trigger_node;
683                        node.set(Some(event.data()));
684                    },
685                    span { "data-ui-select-value": "true", "{trigger_text}" }
686                }
687                if open {
688                    DismissLayer { on_dismiss: move |()| machine.close() }
689                }
690                div {
691                    aria_label: props.aria_label.clone(),
692                    aria_labelledby: props.aria_labelledby.clone(),
693                    class: "ui-select__list",
694                    "data-state": if open { "open" } else { "closed" },
695                    "data-ui-select-list": "true",
696                    hidden: !open,
697                    id: list_id,
698                    role: "listbox",
699                    // A press keeps focus where it is, so browsers that do not focus buttons on
700                    // click (Safari) never close the list through a focus change before the click.
701                    onmousedown: move |event| event.prevent_default(),
702                    if options.is_empty() {
703                        div {
704                            aria_disabled: "true",
705                            class: "ui-select__empty",
706                            "data-ui-select-empty": "true",
707                            role: "option",
708                            "{empty_message}"
709                        }
710                    }
711                    for (index, choice) in options.iter().enumerate() {
712                        button {
713                            aria_disabled: choice.disabled.then_some("true"),
714                            aria_selected: if choice.value == value { "true" } else { "false" },
715                            "data-active": (open && active == Some(index)).then_some("true"),
716                            "data-ui-select-option": "true",
717                            "data-value": choice.value.clone(),
718                            disabled: choice.disabled,
719                            role: "option",
720                            tabindex: "-1",
721                            r#type: "button",
722                            onclick: move |_| machine.choose(index),
723                            onkeydown: move |event| machine.option_key(index, &event),
724                            onmounted: move |event| machine.store_option(index, event.data()),
725                            "{choice.label}"
726                        }
727                    }
728                }
729            }
730        }
731    }
732}
733
734#[cfg(test)]
735mod tests {
736    use super::{SelectNavKey, select_open_target, select_step, select_typeahead, source_options};
737    use crate::SelectOption;
738
739    fn plans() -> Vec<SelectOption> {
740        vec!["Free".into(), "Pro".into(), "Team".into()]
741    }
742
743    #[test]
744    fn opening_keys_start_from_the_selected_option() {
745        let options = plans();
746
747        // lumen-react's `select-keyboard.test.ts` opening matrix with `defaultValue: 'Pro'`.
748        assert_eq!(select_open_target(&options, "Pro"), Some(1));
749        assert_eq!(
750            select_step(&options, "Pro", None, SelectNavKey::Down),
751            Some(2)
752        );
753        assert_eq!(
754            select_step(&options, "Pro", None, SelectNavKey::Up),
755            Some(0)
756        );
757        assert_eq!(
758            select_step(&options, "Pro", None, SelectNavKey::Home),
759            Some(0)
760        );
761        assert_eq!(
762            select_step(&options, "Pro", None, SelectNavKey::End),
763            Some(2)
764        );
765        assert_eq!(select_typeahead(&options, "Pro", None, "t"), Some(2));
766    }
767
768    #[test]
769    fn without_a_selection_navigation_starts_from_the_first_option() {
770        let options = plans();
771
772        assert_eq!(select_open_target(&options, ""), Some(0));
773        assert_eq!(select_step(&options, "", None, SelectNavKey::Down), Some(1));
774        assert_eq!(select_step(&options, "", None, SelectNavKey::Up), Some(2));
775    }
776
777    #[test]
778    fn navigation_loops_and_skips_disabled_options() {
779        let options = vec![
780            SelectOption::from("A"),
781            SelectOption::new("b", "B").disabled(true),
782            SelectOption::from("C"),
783        ];
784
785        assert_eq!(
786            select_step(&options, "", Some(0), SelectNavKey::Down),
787            Some(2)
788        );
789        assert_eq!(
790            select_step(&options, "", Some(2), SelectNavKey::Down),
791            Some(0)
792        );
793        assert_eq!(
794            select_step(&options, "", Some(0), SelectNavKey::Up),
795            Some(2)
796        );
797        // A selected disabled option is not a starting point.
798        assert_eq!(select_open_target(&options, "b"), Some(0));
799        assert_eq!(
800            select_step(&options, "b", None, SelectNavKey::Down),
801            Some(2)
802        );
803
804        let none = vec![SelectOption::new("x", "X").disabled(true)];
805        assert_eq!(select_step(&none, "", None, SelectNavKey::Down), None);
806        assert_eq!(select_open_target(&none, ""), None);
807        assert_eq!(select_typeahead(&none, "", None, "x"), None);
808    }
809
810    #[test]
811    fn typeahead_searches_after_the_current_option_and_wraps() {
812        let options: Vec<SelectOption> =
813            vec!["New Haven".into(), "New York".into(), "Newark".into()];
814
815        // The query sequence of lumen-react's "Space continues an active typeahead query" test.
816        let first = select_typeahead(&options, "", None, "n");
817        assert_eq!(first, Some(1));
818        let second = select_typeahead(&options, "", first, "ne");
819        assert_eq!(second, Some(2));
820        let third = select_typeahead(&options, "", second, "new");
821        assert_eq!(third, Some(0));
822        let fourth = select_typeahead(&options, "", third, "new ");
823        assert_eq!(fourth, Some(1));
824        assert_eq!(select_typeahead(&options, "", fourth, "new y"), Some(1));
825        assert_eq!(select_typeahead(&options, "", None, ""), None);
826        assert_eq!(select_typeahead(&options, "", None, "zz"), None);
827    }
828
829    #[test]
830    fn typeahead_compares_trimmed_lowercase_labels() {
831        let options = vec![
832            SelectOption::new("a", "  Éclair "),
833            SelectOption::new("b", "Beta"),
834        ];
835
836        assert_eq!(select_typeahead(&options, "b", None, "éc"), Some(0));
837    }
838
839    #[test]
840    fn typeahead_handles_long_queries_and_many_options_linearly() {
841        let options: Vec<SelectOption> = (0..5_000)
842            .map(|index| format!("Option {index}").into())
843            .collect();
844        let query = "o".repeat(10_000);
845
846        assert_eq!(select_typeahead(&options, "", None, &query), None);
847        assert_eq!(
848            select_typeahead(&options, "", None, "option 4999"),
849            Some(4_999)
850        );
851    }
852
853    #[test]
854    fn the_placeholder_choice_takes_the_placeholder_text() {
855        let options = vec![SelectOption::new("", ""), "Lima".into()];
856
857        assert_eq!(
858            source_options(&options, Some("Pick a city"))[0].label,
859            "Pick a city"
860        );
861        assert_eq!(source_options(&options, Some(""))[0].label, "");
862        assert_eq!(source_options(&options, None)[0].label, "");
863
864        let labelled = vec![SelectOption::new("", "Any city"), "Lima".into()];
865        assert_eq!(
866            source_options(&labelled, Some("Pick a city"))[0].label,
867            "Any city"
868        );
869    }
870}