Skip to main content

lumen_dioxus/inputs/
list_box.rs

1//! `ListBox`: an always-visible single or multiple selection list.
2
3// cspell:words multiselectable oninvalid optgroup rposition
4
5use std::cell::Cell;
6use std::rc::Rc;
7use std::time::Duration;
8
9use dioxus::prelude::*;
10
11use super::select_keyboard::{Typeahead, extend_typeahead, is_space, printable_key};
12use crate::SelectOption;
13use crate::class::compose;
14use crate::hooks::use_unique_id;
15use crate::overlay::focus_element;
16
17const DEFAULT_EMPTY_MESSAGE: &str = "No options available";
18const DEFAULT_LOADING_MESSAGE: &str = "Loading options";
19/// Lumen's web runtime skips roots that carry `data-ui-owner`; it only checks that the attribute
20/// exists. lumen-react's value keeps the markup identical.
21const OWNER: &str = "react";
22
23/// A labelled run of options in a [`ListBox`], like consecutive lumen-react options that share a
24/// `section`.
25///
26/// ```
27/// use lumen_dioxus::{ListBoxGroup, SelectOption};
28///
29/// let groups = vec![
30///     ListBoxGroup::new("Fruit", ["Apple", "Pear"]),
31///     ListBoxGroup::ungrouped([SelectOption::new("water", "Water")]),
32/// ];
33///
34/// assert_eq!(groups[0].label.as_deref(), Some("Fruit"));
35/// assert_eq!(groups[1].options[0].value, "water");
36/// ```
37#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
38pub struct ListBoxGroup {
39    /// The section heading. `None` (or an empty label) renders the options without a group.
40    pub label: Option<String>,
41    /// The options in the group.
42    pub options: Vec<SelectOption>,
43}
44
45impl ListBoxGroup {
46    /// A labelled group.
47    pub fn new<T: Into<SelectOption>>(
48        label: impl Into<String>,
49        options: impl IntoIterator<Item = T>,
50    ) -> Self {
51        Self {
52            label: Some(label.into()),
53            options: options.into_iter().map(Into::into).collect(),
54        }
55    }
56
57    /// Options shown without a section heading.
58    pub fn ungrouped<T: Into<SelectOption>>(options: impl IntoIterator<Item = T>) -> Self {
59        Self {
60            label: None,
61            options: options.into_iter().map(Into::into).collect(),
62        }
63    }
64}
65
66/// Props for [`ListBox`].
67// The flags mirror lumen-react's boolean `ListBox` props one to one, so the API stays the same
68// across Lumen adapters.
69#[allow(clippy::struct_excessive_bools)]
70#[derive(Props, Clone, PartialEq)]
71pub struct ListBoxProps {
72    /// Options without a section heading, shown before `groups`.
73    #[props(default)]
74    pub options: Vec<SelectOption>,
75    /// Options under section headings, shown after `options`.
76    #[props(default)]
77    pub groups: Vec<ListBoxGroup>,
78    /// Controlled selected values. Leave unset to let the list manage itself.
79    pub value: Option<Vec<String>>,
80    /// Initially selected values when uncontrolled.
81    #[props(default)]
82    pub default_value: Vec<String>,
83    /// Called with every selected value after each selection change.
84    pub on_value_change: Option<EventHandler<Vec<String>>>,
85    /// Lets the person select several options; activating an option toggles it.
86    #[props(default)]
87    pub multiple: bool,
88    /// Selects the active option as the arrow keys, Home, End, or typeahead move it.
89    #[props(default)]
90    pub selection_follows_focus: bool,
91    /// Disables selection and removes the list from the tab order.
92    #[props(default)]
93    pub disabled: bool,
94    /// Shows `loading_message` instead of the options and blocks selection.
95    #[props(default)]
96    pub loading: bool,
97    /// Marks the selection as required for form validation.
98    #[props(default)]
99    pub required: bool,
100    /// Visible label rendered above the list; it names the list.
101    #[props(into)]
102    pub label: Option<String>,
103    /// Text shown when there are no options. Defaults to "No options available".
104    #[props(into)]
105    pub empty_message: Option<String>,
106    /// Status text while `loading`. Defaults to "Loading options".
107    #[props(into)]
108    pub loading_message: Option<String>,
109    /// Id of the native control; option ids are `{id}-option-{index}`. Generated when unset.
110    #[props(into)]
111    pub id: Option<String>,
112    /// Form field name. When set, hidden inputs submit the selected values.
113    #[props(into)]
114    pub name: Option<String>,
115    /// Id of the form that owns the field when it is outside that form.
116    #[props(into)]
117    pub form: Option<String>,
118    /// Accessible name of the list.
119    #[props(into)]
120    pub aria_label: Option<String>,
121    /// Id of the element that names the list. Wins over `aria_label` and `label`.
122    #[props(into)]
123    pub aria_labelledby: Option<String>,
124    /// Ids of elements that describe the list.
125    #[props(into)]
126    pub aria_describedby: Option<String>,
127    /// `aria-invalid` of the list, such as `"true"`.
128    #[props(into)]
129    pub aria_invalid: Option<String>,
130    /// Id of the error message of the list.
131    #[props(into)]
132    pub aria_errormessage: Option<String>,
133    /// Extra classes appended to the root after the Lumen class.
134    #[props(into)]
135    pub class: Option<String>,
136    /// Any other `<select>` or global attribute. They go to the hidden native control, like the
137    /// rest props of lumen-react's `ListBox`.
138    #[props(extends = GlobalAttributes, extends = select)]
139    pub attributes: Vec<Attribute>,
140}
141
142/// One rendered group: its heading and the flat indexes of its options.
143#[derive(Clone, Debug, PartialEq, Eq)]
144pub(crate) struct ListBoxRun {
145    pub(crate) label: Option<String>,
146    pub(crate) indexes: Vec<usize>,
147}
148
149/// Flattens `options` and `groups` into one option list and the runs to render, merging adjacent
150/// runs with the same heading like lumen-react's section grouping.
151pub(crate) fn list_box_runs(
152    options: &[SelectOption],
153    groups: &[ListBoxGroup],
154) -> (Vec<SelectOption>, Vec<ListBoxRun>) {
155    let mut flat = Vec::new();
156    let mut runs: Vec<ListBoxRun> = Vec::new();
157    let sources = std::iter::once((None, options)).chain(
158        groups
159            .iter()
160            .map(|group| (group.label.as_deref(), group.options.as_slice())),
161    );
162
163    for (label, group_options) in sources {
164        let label = label.filter(|text| !text.is_empty());
165
166        for option in group_options {
167            let index = flat.len();
168            flat.push(option.clone());
169
170            match runs.last_mut() {
171                Some(run) if run.label.as_deref() == label => run.indexes.push(index),
172                _ => runs.push(ListBoxRun {
173                    label: label.map(str::to_string),
174                    indexes: vec![index],
175                }),
176            }
177        }
178    }
179
180    (flat, runs)
181}
182
183/// The id of a group heading, like lumen-react: `{id}-group-{label}:{values}` with every UTF-16
184/// code unit outside `[A-Za-z0-9_-]` replaced by `-`.
185pub(crate) fn list_box_group_label_id(
186    control_id: &str,
187    label: &str,
188    values: impl IntoIterator<Item = impl AsRef<str>>,
189) -> String {
190    let mut key = format!("{label}:");
191
192    for (position, value) in values.into_iter().enumerate() {
193        if position > 0 {
194            key.push('|');
195        }
196
197        key.push_str(value.as_ref());
198    }
199
200    let mut id = format!("{control_id}-group-");
201
202    for character in key.chars() {
203        if character.is_ascii_alphanumeric() || character == '_' || character == '-' {
204            id.push(character);
205        } else {
206            for _ in 0..character.len_utf16() {
207                id.push('-');
208            }
209        }
210    }
211
212    id
213}
214
215fn is_enabled(options: &[SelectOption], index: usize) -> bool {
216    options.get(index).is_some_and(|option| !option.disabled)
217}
218
219fn first_enabled(options: &[SelectOption]) -> Option<usize> {
220    options.iter().position(|option| !option.disabled)
221}
222
223fn last_enabled(options: &[SelectOption]) -> Option<usize> {
224    options.iter().rposition(|option| !option.disabled)
225}
226
227/// The active option: the remembered one while it exists and is enabled, then the first selected
228/// enabled option, then the first enabled one. It never rests on a missing or disabled option.
229pub(crate) fn resolve_active(
230    options: &[SelectOption],
231    active: Option<usize>,
232    selected: &[String],
233) -> Option<usize> {
234    if let Some(index) = active.filter(|index| is_enabled(options, *index)) {
235        return Some(index);
236    }
237
238    options
239        .iter()
240        .position(|option| !option.disabled && selected.contains(&option.value))
241        .or_else(|| first_enabled(options))
242}
243
244/// The next enabled option in `forward` or backward direction from `resolved`, wrapping.
245pub(crate) fn move_active(
246    options: &[SelectOption],
247    resolved: Option<usize>,
248    forward: bool,
249) -> Option<usize> {
250    let len = options.len();
251    let mut next = resolved.unwrap_or(0);
252
253    for _ in 0..len {
254        next = if forward {
255            (next + 1) % len
256        } else {
257            (next + len - 1) % len
258        };
259
260        if !options[next].disabled {
261            return Some(next);
262        }
263    }
264
265    None
266}
267
268/// The selection after activating `index`, or `None` when the option is missing or disabled.
269pub(crate) fn toggle_selection(
270    options: &[SelectOption],
271    selected: &[String],
272    index: usize,
273    multiple: bool,
274) -> Option<Vec<String>> {
275    let option = options.get(index).filter(|option| !option.disabled)?;
276
277    if !multiple {
278        return Some(vec![option.value.clone()]);
279    }
280
281    if selected.contains(&option.value) {
282        Some(
283            selected
284                .iter()
285                .filter(|value| **value != option.value)
286                .cloned()
287                .collect(),
288        )
289    } else {
290        let mut next = selected.to_vec();
291        next.push(option.value.clone());
292        Some(next)
293    }
294}
295
296/// The first enabled option whose lowercase label starts with `query`.
297pub(crate) fn list_box_typeahead(options: &[SelectOption], query: &str) -> Option<usize> {
298    options
299        .iter()
300        .position(|option| !option.disabled && option.label.to_lowercase().starts_with(query))
301}
302
303/// The value the hidden native `<select>` holds in single mode.
304fn native_single_value(selected: &[String]) -> &str {
305    selected.first().map_or("", String::as_str)
306}
307
308/// The values a native `<select>` with the same options and selection would submit: enabled
309/// selected options in option order, and in single mode the empty choice when nothing matches.
310pub(crate) fn list_box_submitted(
311    options: &[SelectOption],
312    selected: &[String],
313    multiple: bool,
314) -> Vec<String> {
315    if multiple {
316        return options
317            .iter()
318            .filter(|option| !option.disabled && selected.contains(&option.value))
319            .map(|option| option.value.clone())
320            .collect();
321    }
322
323    let value = native_single_value(selected);
324
325    match options.iter().find(|option| option.value == value) {
326        Some(option) if option.disabled => Vec::new(),
327        Some(option) => vec![option.value.clone()],
328        None => vec![String::new()],
329    }
330}
331
332/// Whether the native `<select>` satisfies `required`.
333fn selection_is_valid(options: &[SelectOption], selected: &[String], multiple: bool) -> bool {
334    if multiple {
335        options
336            .iter()
337            .any(|option| selected.contains(&option.value))
338    } else {
339        let value = native_single_value(selected);
340        options.iter().any(|option| option.value == value)
341    }
342}
343
344thread_local! {
345    /// Set while one invalid list already took focus during the current validation pass.
346    static INVALID_FOCUS_CLAIMED: Cell<bool> = const { Cell::new(false) };
347}
348
349/// Whether activating an option replaces the selection or toggles the option.
350#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
351enum ListBoxSelection {
352    #[default]
353    Single,
354    Multiple,
355}
356
357/// Values the list needs in its event handlers, refreshed on every render.
358#[derive(Clone, Default, PartialEq)]
359struct ListBoxSnapshot {
360    options: Vec<SelectOption>,
361    selected: Vec<String>,
362    selection: ListBoxSelection,
363    controlled: bool,
364    unavailable: bool,
365    follows_focus: bool,
366    on_value_change: Option<EventHandler<Vec<String>>>,
367}
368
369#[derive(Clone, Copy)]
370struct ListBoxMachine {
371    snapshot: CopyValue<ListBoxSnapshot>,
372    internal: Signal<Vec<String>>,
373    active: Signal<Option<usize>>,
374    typeahead: CopyValue<Typeahead>,
375    invalid: Signal<bool>,
376    list_node: CopyValue<Option<Rc<MountedData>>>,
377}
378
379impl ListBoxMachine {
380    fn resolved_active(self) -> Option<usize> {
381        let snapshot = self.snapshot.peek();
382        resolve_active(&snapshot.options, *self.active.peek(), &snapshot.selected)
383    }
384
385    fn select(self, index: usize) {
386        let (next, controlled, handler) = {
387            let snapshot = self.snapshot.peek();
388
389            if snapshot.unavailable {
390                return;
391            }
392
393            let multiple = snapshot.selection == ListBoxSelection::Multiple;
394            let Some(next) =
395                toggle_selection(&snapshot.options, &snapshot.selected, index, multiple)
396            else {
397                return;
398            };
399
400            (next, snapshot.controlled, snapshot.on_value_change)
401        };
402
403        if !controlled {
404            let mut internal = self.internal;
405            internal.set(next.clone());
406        }
407
408        if let Some(handler) = handler {
409            handler.call(next);
410        }
411    }
412
413    fn activate(self, index: Option<usize>) {
414        let Some(index) = index else {
415            return;
416        };
417
418        let mut active = self.active;
419        active.set(Some(index));
420
421        if self.snapshot.peek().follows_focus {
422            self.select(index);
423        }
424    }
425
426    fn navigation_key(self, key: &Key) -> bool {
427        let options = self.snapshot.peek().options.clone();
428
429        match key {
430            Key::ArrowDown | Key::ArrowUp => {
431                if !options.is_empty() {
432                    let next =
433                        move_active(&options, self.resolved_active(), *key == Key::ArrowDown);
434                    self.activate(next);
435                }
436            }
437            Key::Home => self.activate(first_enabled(&options)),
438            Key::End => self.activate(last_enabled(&options)),
439            key if *key == Key::Enter || is_space(key) => {
440                if let Some(index) = self.resolved_active() {
441                    self.select(index);
442                }
443            }
444            _ => return false,
445        }
446
447        true
448    }
449
450    fn typeahead_key(self, event: &KeyboardEvent) -> bool {
451        let Some(text) = printable_key(event) else {
452            return false;
453        };
454
455        let query = extend_typeahead(self.typeahead, &text);
456        let target = list_box_typeahead(&self.snapshot.peek().options, &query);
457        self.activate(target);
458        true
459    }
460
461    fn keydown(self, event: &KeyboardEvent) {
462        if self.snapshot.peek().unavailable || event.is_composing() {
463            return;
464        }
465
466        if self.navigation_key(&event.key()) || self.typeahead_key(event) {
467            event.prevent_default();
468        }
469    }
470
471    fn click(self, index: usize) {
472        let usable = {
473            let snapshot = self.snapshot.peek();
474            !snapshot.unavailable && is_enabled(&snapshot.options, index)
475        };
476
477        if usable {
478            let mut active = self.active;
479            active.set(Some(index));
480            self.select(index);
481        }
482    }
483
484    /// The hidden native control failed validation: mark the list invalid and focus the first
485    /// invalid list of the pass, as lumen-react does.
486    fn invalid(self, event: &FormEvent) {
487        event.prevent_default();
488
489        let mut invalid = self.invalid;
490        invalid.set(true);
491
492        if INVALID_FOCUS_CLAIMED.with(|claimed| claimed.replace(true)) {
493            return;
494        }
495
496        focus_element(self.list_node.peek().clone());
497
498        // Release the claim after the validation pass, even if this list unmounts first.
499        dioxus::core::spawn_forever(async {
500            crate::time::sleep(Duration::ZERO).await;
501            INVALID_FOCUS_CLAIMED.with(|claimed| claimed.set(false));
502        });
503    }
504}
505
506/// An always-visible list of options with single or multiple selection, following the WAI-ARIA
507/// listbox pattern: the list is one focus stop and `aria-activedescendant` marks the active option.
508///
509/// Arrow keys, Home, and End move the active option past disabled ones; Enter and Space select it
510/// (toggle in `multiple` mode); printable keys jump to the first matching label. A named list
511/// submits its selection through hidden inputs on every renderer.
512#[component]
513pub fn ListBox(props: ListBoxProps) -> Element {
514    let generated = use_unique_id();
515    let control_id = props
516        .id
517        .clone()
518        .unwrap_or_else(|| format!("ui-list-box-{generated}"));
519    let (options, runs) = list_box_runs(&props.options, &props.groups);
520    let internal = use_signal(|| props.default_value.clone());
521    let selected = props.value.clone().unwrap_or_else(|| internal.cloned());
522    let unavailable = props.disabled || props.loading;
523    let multiple = props.multiple;
524
525    let mut snapshot = use_hook(|| CopyValue::new(ListBoxSnapshot::default()));
526    snapshot.set(ListBoxSnapshot {
527        options: options.clone(),
528        selected: selected.clone(),
529        selection: if multiple {
530            ListBoxSelection::Multiple
531        } else {
532            ListBoxSelection::Single
533        },
534        controlled: props.value.is_some(),
535        unavailable,
536        follows_focus: props.selection_follows_focus,
537        on_value_change: props.on_value_change,
538    });
539
540    let machine = ListBoxMachine {
541        snapshot,
542        internal,
543        active: use_signal(|| None),
544        typeahead: use_hook(|| CopyValue::new(Typeahead::default())),
545        invalid: use_signal(|| false),
546        list_node: use_hook(|| CopyValue::new(None)),
547    };
548
549    // Lumen only clears the invalid state it generated, once the selection satisfies the control.
550    let valid = unavailable || !props.required || selection_is_valid(&options, &selected, multiple);
551    use_effect(use_reactive((&valid,), move |(valid,)| {
552        let mut invalid = machine.invalid;
553
554        if valid && *invalid.peek() {
555            invalid.set(false);
556        }
557    }));
558
559    let resolved = resolve_active(&options, *machine.active.read(), &selected);
560    let generated_invalid = *machine.invalid.read() && !valid;
561    let aria_invalid = props
562        .aria_invalid
563        .clone()
564        .or_else(|| generated_invalid.then(|| "true".to_string()));
565    let label_id = format!("{control_id}-label");
566    // An explicit `aria-labelledby` wins, then `aria-label`, then the `label` prop.
567    let labelled_by = if props.aria_labelledby.is_some() {
568        props.aria_labelledby.clone()
569    } else if props.aria_label.is_some() {
570        None
571    } else {
572        props.label.as_ref().map(|_| label_id.clone())
573    };
574    let active_id = resolved
575        .filter(|_| !props.loading)
576        .map(|index| format!("{control_id}-option-{index}"));
577    let submitted = props
578        .name
579        .clone()
580        .filter(|_| !unavailable)
581        .map(|name| (name, list_box_submitted(&options, &selected, multiple)));
582    let single_value = native_single_value(&selected).to_string();
583    let is_native_selected = |value: &str| {
584        if multiple {
585            selected.iter().any(|entry| entry == value)
586        } else {
587            single_value == value
588        }
589    };
590    let class = compose([Some("ui-list-box"), props.class.as_deref()]);
591    let empty_message = props
592        .empty_message
593        .clone()
594        .unwrap_or_else(|| DEFAULT_EMPTY_MESSAGE.to_string());
595    let loading_message = props
596        .loading_message
597        .clone()
598        .unwrap_or_else(|| DEFAULT_LOADING_MESSAGE.to_string());
599    let option_view = |index: usize| {
600        let option = &options[index];
601        let is_active = resolved == Some(index);
602
603        rsx! {
604            div {
605                aria_disabled: option.disabled.then_some("true"),
606                aria_selected: if selected.contains(&option.value) { "true" } else { "false" },
607                class: compose([
608                    Some("ui-list-box__option"),
609                    is_active.then_some("ui-list-box__option--active"),
610                ]),
611                "data-active": is_active.then_some("true"),
612                "data-ui-list-box-option": "true",
613                "data-value": option.value.clone(),
614                id: "{control_id}-option-{index}",
615                role: "option",
616                onclick: move |_| machine.click(index),
617                "{option.label}"
618            }
619        }
620    };
621
622    rsx! {
623        div {
624            class,
625            "data-multiple": multiple.then_some("true"),
626            "data-ui-list-box": "true",
627            "data-ui-owner": OWNER,
628            if let Some(text) = props.label.clone() {
629                label { class: "ui-label", r#for: control_id.clone(), id: label_id, "{text}" }
630            }
631            select {
632                aria_describedby: props.aria_describedby.clone(),
633                aria_errormessage: props.aria_errormessage.clone(),
634                aria_hidden: "true",
635                aria_invalid: props.aria_invalid.clone(),
636                aria_label: props.aria_label.clone(),
637                aria_labelledby: props.aria_labelledby.clone(),
638                class: "ui-list-box__native",
639                "data-ui-enhanced": "true",
640                "data-ui-list-box-native": "true",
641                disabled: unavailable,
642                form: props.form.clone(),
643                id: control_id.clone(),
644                multiple,
645                required: props.required,
646                tabindex: "-1",
647                // The visible list is the only focus stop; label clicks land here first.
648                onfocus: move |_| focus_element(machine.list_node.peek().clone()),
649                oninvalid: move |event| machine.invalid(&event),
650                ..props.attributes,
651                // An empty choice keeps a single selection empty until the person picks an option.
652                if !multiple {
653                    option { selected: single_value.is_empty(), value: "" }
654                }
655                for run in runs.iter() {
656                    if let Some(heading) = run.label.clone() {
657                        optgroup { label: heading,
658                            for index in run.indexes.iter().copied() {
659                                option {
660                                    disabled: options[index].disabled,
661                                    selected: is_native_selected(&options[index].value),
662                                    value: options[index].value.clone(),
663                                    "{options[index].label}"
664                                }
665                            }
666                        }
667                    } else {
668                        for index in run.indexes.iter().copied() {
669                            option {
670                                disabled: options[index].disabled,
671                                selected: is_native_selected(&options[index].value),
672                                value: options[index].value.clone(),
673                                "{options[index].label}"
674                            }
675                        }
676                    }
677                }
678            }
679            if let Some((name, values)) = submitted {
680                for value in values {
681                    input { form: props.form.clone(), name: name.clone(), r#type: "hidden", value }
682                }
683            }
684            div {
685                aria_activedescendant: active_id,
686                aria_busy: props.loading.then_some("true"),
687                aria_describedby: props.aria_describedby.clone(),
688                aria_disabled: unavailable.then_some("true"),
689                aria_errormessage: props.aria_errormessage.clone(),
690                aria_invalid,
691                aria_label: props.aria_label.clone(),
692                aria_labelledby: labelled_by,
693                aria_multiselectable: multiple.then_some("true"),
694                aria_required: props.required.then_some("true"),
695                class: "ui-list-box__list",
696                "data-ui-list-box-list": "true",
697                role: "listbox",
698                tabindex: (!unavailable).then_some("0"),
699                onkeydown: move |event| machine.keydown(&event),
700                onmounted: move |event| {
701                    let mut node = machine.list_node;
702                    node.set(Some(event.data()));
703                },
704                if !props.loading {
705                    if options.is_empty() {
706                        div {
707                            aria_disabled: "true",
708                            class: "ui-list-box__empty",
709                            role: "option",
710                            "{empty_message}"
711                        }
712                    }
713                    for run in runs.iter() {
714                        if let Some(heading) = run.label.as_deref() {
715                            div {
716                                aria_labelledby: list_box_group_label_id(
717                                    &control_id,
718                                    heading,
719                                    run.indexes.iter().map(|index| options[*index].value.as_str()),
720                                ),
721                                role: "group",
722                                div {
723                                    class: "ui-list-box__section",
724                                    id: list_box_group_label_id(
725                                        &control_id,
726                                        heading,
727                                        run.indexes.iter().map(|index| options[*index].value.as_str()),
728                                    ),
729                                    "{heading}"
730                                }
731                                for index in run.indexes.iter().copied() {
732                                    {option_view(index)}
733                                }
734                            }
735                        } else {
736                            for index in run.indexes.iter().copied() {
737                                {option_view(index)}
738                            }
739                        }
740                    }
741                }
742            }
743            if props.loading {
744                p { class: "ui-list-box__status", role: "status", "{loading_message}" }
745            }
746        }
747    }
748}
749
750#[cfg(test)]
751mod tests {
752    use super::{
753        ListBoxGroup, list_box_group_label_id, list_box_runs, list_box_submitted,
754        list_box_typeahead, move_active, resolve_active, selection_is_valid, toggle_selection,
755    };
756    use crate::SelectOption;
757
758    fn reviewers() -> Vec<SelectOption> {
759        vec![
760            SelectOption::new("amina", "Amina").disabled(true),
761            SelectOption::new("bruno", "Bruno"),
762            SelectOption::new("chen", "Chen"),
763        ]
764    }
765
766    fn strings(values: &[&str]) -> Vec<String> {
767        values.iter().map(ToString::to_string).collect()
768    }
769
770    #[test]
771    fn the_active_option_starts_on_the_selection_and_never_rests_on_disabled_ones() {
772        let options = reviewers();
773
774        assert_eq!(resolve_active(&options, None, &strings(&["chen"])), Some(2));
775        assert_eq!(resolve_active(&options, None, &[]), Some(1));
776        // A remembered disabled or missing option falls back.
777        assert_eq!(
778            resolve_active(&options, Some(0), &strings(&["chen"])),
779            Some(2)
780        );
781        assert_eq!(resolve_active(&options, Some(9), &[]), Some(1));
782        assert_eq!(
783            resolve_active(&options, Some(1), &strings(&["chen"])),
784            Some(1)
785        );
786
787        let disabled: Vec<SelectOption> = options
788            .into_iter()
789            .map(|option| option.disabled(true))
790            .collect();
791        assert_eq!(resolve_active(&disabled, None, &strings(&["chen"])), None);
792        assert_eq!(resolve_active(&[], None, &[]), None);
793    }
794
795    #[test]
796    fn arrow_keys_wrap_and_skip_disabled_options() {
797        let options = reviewers();
798
799        assert_eq!(move_active(&options, Some(1), true), Some(2));
800        assert_eq!(move_active(&options, Some(2), true), Some(1));
801        assert_eq!(move_active(&options, Some(1), false), Some(2));
802        assert_eq!(move_active(&options, None, true), Some(1));
803        assert_eq!(move_active(&[], None, true), None);
804
805        let disabled = vec![SelectOption::new("x", "X").disabled(true)];
806        assert_eq!(move_active(&disabled, None, true), None);
807    }
808
809    #[test]
810    fn activation_replaces_or_toggles_the_selection() {
811        let options = reviewers();
812        let selected = strings(&["bruno"]);
813
814        assert_eq!(
815            toggle_selection(&options, &selected, 2, false),
816            Some(strings(&["chen"]))
817        );
818        assert_eq!(
819            toggle_selection(&options, &selected, 1, false),
820            Some(strings(&["bruno"]))
821        );
822        assert_eq!(
823            toggle_selection(&options, &selected, 2, true),
824            Some(strings(&["bruno", "chen"]))
825        );
826        assert_eq!(
827            toggle_selection(&options, &selected, 1, true),
828            Some(Vec::new())
829        );
830        assert_eq!(toggle_selection(&options, &selected, 0, true), None);
831        assert_eq!(toggle_selection(&options, &selected, 7, false), None);
832    }
833
834    #[test]
835    fn typeahead_finds_the_first_enabled_label_from_the_top() {
836        let options = vec![
837            SelectOption::new("a", "Apple").disabled(true),
838            SelectOption::new("b", "Avocado"),
839            SelectOption::new("c", "Banana"),
840        ];
841
842        assert_eq!(list_box_typeahead(&options, "a"), Some(1));
843        assert_eq!(list_box_typeahead(&options, "ba"), Some(2));
844        assert_eq!(list_box_typeahead(&options, "z"), None);
845
846        let many: Vec<SelectOption> = (0..5_000)
847            .map(|index| format!("Item {index}").into())
848            .collect();
849        assert_eq!(list_box_typeahead(&many, &"i".repeat(20_000)), None);
850    }
851
852    #[test]
853    fn submitted_values_match_a_native_select() {
854        let options = reviewers();
855
856        assert_eq!(list_box_submitted(&options, &[], false), strings(&[""]));
857        assert_eq!(
858            list_box_submitted(&options, &strings(&["chen"]), false),
859            strings(&["chen"])
860        );
861        assert_eq!(
862            list_box_submitted(&options, &strings(&["missing"]), false),
863            strings(&[""])
864        );
865        assert_eq!(
866            list_box_submitted(&options, &strings(&["amina"]), false),
867            strings(&[])
868        );
869        assert_eq!(
870            list_box_submitted(&options, &strings(&["chen", "amina", "bruno"]), true),
871            strings(&["bruno", "chen"])
872        );
873        assert_eq!(list_box_submitted(&options, &[], true), strings(&[]));
874    }
875
876    #[test]
877    fn required_validity_follows_the_native_select() {
878        let options = reviewers();
879
880        assert!(!selection_is_valid(&options, &[], false));
881        assert!(!selection_is_valid(&options, &strings(&["missing"]), false));
882        assert!(selection_is_valid(&options, &strings(&["bruno"]), false));
883        assert!(!selection_is_valid(&options, &[], true));
884        assert!(selection_is_valid(&options, &strings(&["chen"]), true));
885    }
886
887    #[test]
888    fn groups_flatten_in_order_and_merge_adjacent_headings() {
889        let (flat, runs) = list_box_runs(
890            &[SelectOption::from("Loose")],
891            &[
892                ListBoxGroup::new("Fruit", ["Apple"]),
893                ListBoxGroup::new("Fruit", ["Pear"]),
894                ListBoxGroup::new("", ["Water"]),
895                ListBoxGroup::ungrouped(["Tea"]),
896                ListBoxGroup::new("Empty", Vec::<SelectOption>::new()),
897            ],
898        );
899
900        let labels: Vec<&str> = flat.iter().map(|option| option.label.as_str()).collect();
901        assert_eq!(labels, ["Loose", "Apple", "Pear", "Water", "Tea"]);
902        assert_eq!(runs.len(), 3);
903        assert_eq!(runs[0].label, None);
904        assert_eq!(runs[1].label.as_deref(), Some("Fruit"));
905        assert_eq!(runs[1].indexes, [1, 2]);
906        assert_eq!(runs[2].label, None);
907        assert_eq!(runs[2].indexes, [3, 4]);
908    }
909
910    #[test]
911    fn group_ids_replace_each_utf16_unit_outside_the_safe_set() {
912        assert_eq!(
913            list_box_group_label_id("food", "Leafy greens", ["kale"]),
914            "food-group-Leafy-greens-kale"
915        );
916        assert_eq!(
917            list_box_group_label_id("food", "Fruits é", ["a b", "c"]),
918            "food-group-Fruits---a-b-c"
919        );
920        assert_eq!(list_box_group_label_id("x", "😀", ["v"]), "x-group----v");
921
922        let long = "é".repeat(50_000);
923        assert_eq!(
924            list_box_group_label_id("x", &long, ["v"]).len(),
925            "x-group-".len() + 50_000 + 2
926        );
927    }
928}