use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;
use dioxus::prelude::*;
use super::select_keyboard::{Typeahead, extend_typeahead, is_space, printable_key};
use crate::SelectOption;
use crate::class::compose;
use crate::hooks::use_unique_id;
use crate::overlay::focus_element;
const DEFAULT_EMPTY_MESSAGE: &str = "No options available";
const DEFAULT_LOADING_MESSAGE: &str = "Loading options";
const OWNER: &str = "react";
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct ListBoxGroup {
pub label: Option<String>,
pub options: Vec<SelectOption>,
}
impl ListBoxGroup {
pub fn new<T: Into<SelectOption>>(
label: impl Into<String>,
options: impl IntoIterator<Item = T>,
) -> Self {
Self {
label: Some(label.into()),
options: options.into_iter().map(Into::into).collect(),
}
}
pub fn ungrouped<T: Into<SelectOption>>(options: impl IntoIterator<Item = T>) -> Self {
Self {
label: None,
options: options.into_iter().map(Into::into).collect(),
}
}
}
#[allow(clippy::struct_excessive_bools)]
#[derive(Props, Clone, PartialEq)]
pub struct ListBoxProps {
#[props(default)]
pub options: Vec<SelectOption>,
#[props(default)]
pub groups: Vec<ListBoxGroup>,
pub value: Option<Vec<String>>,
#[props(default)]
pub default_value: Vec<String>,
pub on_value_change: Option<EventHandler<Vec<String>>>,
#[props(default)]
pub multiple: bool,
#[props(default)]
pub selection_follows_focus: bool,
#[props(default)]
pub disabled: bool,
#[props(default)]
pub loading: bool,
#[props(default)]
pub required: bool,
#[props(into)]
pub label: Option<String>,
#[props(into)]
pub empty_message: Option<String>,
#[props(into)]
pub loading_message: Option<String>,
#[props(into)]
pub id: Option<String>,
#[props(into)]
pub name: Option<String>,
#[props(into)]
pub form: Option<String>,
#[props(into)]
pub aria_label: Option<String>,
#[props(into)]
pub aria_labelledby: Option<String>,
#[props(into)]
pub aria_describedby: Option<String>,
#[props(into)]
pub aria_invalid: Option<String>,
#[props(into)]
pub aria_errormessage: Option<String>,
#[props(into)]
pub class: Option<String>,
#[props(extends = GlobalAttributes, extends = select)]
pub attributes: Vec<Attribute>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ListBoxRun {
pub(crate) label: Option<String>,
pub(crate) indexes: Vec<usize>,
}
pub(crate) fn list_box_runs(
options: &[SelectOption],
groups: &[ListBoxGroup],
) -> (Vec<SelectOption>, Vec<ListBoxRun>) {
let mut flat = Vec::new();
let mut runs: Vec<ListBoxRun> = Vec::new();
let sources = std::iter::once((None, options)).chain(
groups
.iter()
.map(|group| (group.label.as_deref(), group.options.as_slice())),
);
for (label, group_options) in sources {
let label = label.filter(|text| !text.is_empty());
for option in group_options {
let index = flat.len();
flat.push(option.clone());
match runs.last_mut() {
Some(run) if run.label.as_deref() == label => run.indexes.push(index),
_ => runs.push(ListBoxRun {
label: label.map(str::to_string),
indexes: vec![index],
}),
}
}
}
(flat, runs)
}
pub(crate) fn list_box_group_label_id(
control_id: &str,
label: &str,
values: impl IntoIterator<Item = impl AsRef<str>>,
) -> String {
let mut key = format!("{label}:");
for (position, value) in values.into_iter().enumerate() {
if position > 0 {
key.push('|');
}
key.push_str(value.as_ref());
}
let mut id = format!("{control_id}-group-");
for character in key.chars() {
if character.is_ascii_alphanumeric() || character == '_' || character == '-' {
id.push(character);
} else {
for _ in 0..character.len_utf16() {
id.push('-');
}
}
}
id
}
fn is_enabled(options: &[SelectOption], index: usize) -> bool {
options.get(index).is_some_and(|option| !option.disabled)
}
fn first_enabled(options: &[SelectOption]) -> Option<usize> {
options.iter().position(|option| !option.disabled)
}
fn last_enabled(options: &[SelectOption]) -> Option<usize> {
options.iter().rposition(|option| !option.disabled)
}
pub(crate) fn resolve_active(
options: &[SelectOption],
active: Option<usize>,
selected: &[String],
) -> Option<usize> {
if let Some(index) = active.filter(|index| is_enabled(options, *index)) {
return Some(index);
}
options
.iter()
.position(|option| !option.disabled && selected.contains(&option.value))
.or_else(|| first_enabled(options))
}
pub(crate) fn move_active(
options: &[SelectOption],
resolved: Option<usize>,
forward: bool,
) -> Option<usize> {
let len = options.len();
let mut next = resolved.unwrap_or(0);
for _ in 0..len {
next = if forward {
(next + 1) % len
} else {
(next + len - 1) % len
};
if !options[next].disabled {
return Some(next);
}
}
None
}
pub(crate) fn toggle_selection(
options: &[SelectOption],
selected: &[String],
index: usize,
multiple: bool,
) -> Option<Vec<String>> {
let option = options.get(index).filter(|option| !option.disabled)?;
if !multiple {
return Some(vec![option.value.clone()]);
}
if selected.contains(&option.value) {
Some(
selected
.iter()
.filter(|value| **value != option.value)
.cloned()
.collect(),
)
} else {
let mut next = selected.to_vec();
next.push(option.value.clone());
Some(next)
}
}
pub(crate) fn list_box_typeahead(options: &[SelectOption], query: &str) -> Option<usize> {
options
.iter()
.position(|option| !option.disabled && option.label.to_lowercase().starts_with(query))
}
fn native_single_value(selected: &[String]) -> &str {
selected.first().map_or("", String::as_str)
}
pub(crate) fn list_box_submitted(
options: &[SelectOption],
selected: &[String],
multiple: bool,
) -> Vec<String> {
if multiple {
return options
.iter()
.filter(|option| !option.disabled && selected.contains(&option.value))
.map(|option| option.value.clone())
.collect();
}
let value = native_single_value(selected);
match options.iter().find(|option| option.value == value) {
Some(option) if option.disabled => Vec::new(),
Some(option) => vec![option.value.clone()],
None => vec![String::new()],
}
}
fn selection_is_valid(options: &[SelectOption], selected: &[String], multiple: bool) -> bool {
if multiple {
options
.iter()
.any(|option| selected.contains(&option.value))
} else {
let value = native_single_value(selected);
options.iter().any(|option| option.value == value)
}
}
thread_local! {
static INVALID_FOCUS_CLAIMED: Cell<bool> = const { Cell::new(false) };
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum ListBoxSelection {
#[default]
Single,
Multiple,
}
#[derive(Clone, Default, PartialEq)]
struct ListBoxSnapshot {
options: Vec<SelectOption>,
selected: Vec<String>,
selection: ListBoxSelection,
controlled: bool,
unavailable: bool,
follows_focus: bool,
on_value_change: Option<EventHandler<Vec<String>>>,
}
#[derive(Clone, Copy)]
struct ListBoxMachine {
snapshot: CopyValue<ListBoxSnapshot>,
internal: Signal<Vec<String>>,
active: Signal<Option<usize>>,
typeahead: CopyValue<Typeahead>,
invalid: Signal<bool>,
list_node: CopyValue<Option<Rc<MountedData>>>,
}
impl ListBoxMachine {
fn resolved_active(self) -> Option<usize> {
let snapshot = self.snapshot.peek();
resolve_active(&snapshot.options, *self.active.peek(), &snapshot.selected)
}
fn select(self, index: usize) {
let (next, controlled, handler) = {
let snapshot = self.snapshot.peek();
if snapshot.unavailable {
return;
}
let multiple = snapshot.selection == ListBoxSelection::Multiple;
let Some(next) =
toggle_selection(&snapshot.options, &snapshot.selected, index, multiple)
else {
return;
};
(next, snapshot.controlled, snapshot.on_value_change)
};
if !controlled {
let mut internal = self.internal;
internal.set(next.clone());
}
if let Some(handler) = handler {
handler.call(next);
}
}
fn activate(self, index: Option<usize>) {
let Some(index) = index else {
return;
};
let mut active = self.active;
active.set(Some(index));
if self.snapshot.peek().follows_focus {
self.select(index);
}
}
fn navigation_key(self, key: &Key) -> bool {
let options = self.snapshot.peek().options.clone();
match key {
Key::ArrowDown | Key::ArrowUp => {
if !options.is_empty() {
let next =
move_active(&options, self.resolved_active(), *key == Key::ArrowDown);
self.activate(next);
}
}
Key::Home => self.activate(first_enabled(&options)),
Key::End => self.activate(last_enabled(&options)),
key if *key == Key::Enter || is_space(key) => {
if let Some(index) = self.resolved_active() {
self.select(index);
}
}
_ => return false,
}
true
}
fn typeahead_key(self, event: &KeyboardEvent) -> bool {
let Some(text) = printable_key(event) else {
return false;
};
let query = extend_typeahead(self.typeahead, &text);
let target = list_box_typeahead(&self.snapshot.peek().options, &query);
self.activate(target);
true
}
fn keydown(self, event: &KeyboardEvent) {
if self.snapshot.peek().unavailable || event.is_composing() {
return;
}
if self.navigation_key(&event.key()) || self.typeahead_key(event) {
event.prevent_default();
}
}
fn click(self, index: usize) {
let usable = {
let snapshot = self.snapshot.peek();
!snapshot.unavailable && is_enabled(&snapshot.options, index)
};
if usable {
let mut active = self.active;
active.set(Some(index));
self.select(index);
}
}
fn invalid(self, event: &FormEvent) {
event.prevent_default();
let mut invalid = self.invalid;
invalid.set(true);
if INVALID_FOCUS_CLAIMED.with(|claimed| claimed.replace(true)) {
return;
}
focus_element(self.list_node.peek().clone());
dioxus::core::spawn_forever(async {
crate::time::sleep(Duration::ZERO).await;
INVALID_FOCUS_CLAIMED.with(|claimed| claimed.set(false));
});
}
}
#[component]
pub fn ListBox(props: ListBoxProps) -> Element {
let generated = use_unique_id();
let control_id = props
.id
.clone()
.unwrap_or_else(|| format!("ui-list-box-{generated}"));
let (options, runs) = list_box_runs(&props.options, &props.groups);
let internal = use_signal(|| props.default_value.clone());
let selected = props.value.clone().unwrap_or_else(|| internal.cloned());
let unavailable = props.disabled || props.loading;
let multiple = props.multiple;
let mut snapshot = use_hook(|| CopyValue::new(ListBoxSnapshot::default()));
snapshot.set(ListBoxSnapshot {
options: options.clone(),
selected: selected.clone(),
selection: if multiple {
ListBoxSelection::Multiple
} else {
ListBoxSelection::Single
},
controlled: props.value.is_some(),
unavailable,
follows_focus: props.selection_follows_focus,
on_value_change: props.on_value_change,
});
let machine = ListBoxMachine {
snapshot,
internal,
active: use_signal(|| None),
typeahead: use_hook(|| CopyValue::new(Typeahead::default())),
invalid: use_signal(|| false),
list_node: use_hook(|| CopyValue::new(None)),
};
let valid = unavailable || !props.required || selection_is_valid(&options, &selected, multiple);
use_effect(use_reactive((&valid,), move |(valid,)| {
let mut invalid = machine.invalid;
if valid && *invalid.peek() {
invalid.set(false);
}
}));
let resolved = resolve_active(&options, *machine.active.read(), &selected);
let generated_invalid = *machine.invalid.read() && !valid;
let aria_invalid = props
.aria_invalid
.clone()
.or_else(|| generated_invalid.then(|| "true".to_string()));
let label_id = format!("{control_id}-label");
let labelled_by = if props.aria_labelledby.is_some() {
props.aria_labelledby.clone()
} else if props.aria_label.is_some() {
None
} else {
props.label.as_ref().map(|_| label_id.clone())
};
let active_id = resolved
.filter(|_| !props.loading)
.map(|index| format!("{control_id}-option-{index}"));
let submitted = props
.name
.clone()
.filter(|_| !unavailable)
.map(|name| (name, list_box_submitted(&options, &selected, multiple)));
let single_value = native_single_value(&selected).to_string();
let is_native_selected = |value: &str| {
if multiple {
selected.iter().any(|entry| entry == value)
} else {
single_value == value
}
};
let class = compose([Some("ui-list-box"), props.class.as_deref()]);
let empty_message = props
.empty_message
.clone()
.unwrap_or_else(|| DEFAULT_EMPTY_MESSAGE.to_string());
let loading_message = props
.loading_message
.clone()
.unwrap_or_else(|| DEFAULT_LOADING_MESSAGE.to_string());
let option_view = |index: usize| {
let option = &options[index];
let is_active = resolved == Some(index);
rsx! {
div {
aria_disabled: option.disabled.then_some("true"),
aria_selected: if selected.contains(&option.value) { "true" } else { "false" },
class: compose([
Some("ui-list-box__option"),
is_active.then_some("ui-list-box__option--active"),
]),
"data-active": is_active.then_some("true"),
"data-ui-list-box-option": "true",
"data-value": option.value.clone(),
id: "{control_id}-option-{index}",
role: "option",
onclick: move |_| machine.click(index),
"{option.label}"
}
}
};
rsx! {
div {
class,
"data-multiple": multiple.then_some("true"),
"data-ui-list-box": "true",
"data-ui-owner": OWNER,
if let Some(text) = props.label.clone() {
label { class: "ui-label", r#for: control_id.clone(), id: label_id, "{text}" }
}
select {
aria_describedby: props.aria_describedby.clone(),
aria_errormessage: props.aria_errormessage.clone(),
aria_hidden: "true",
aria_invalid: props.aria_invalid.clone(),
aria_label: props.aria_label.clone(),
aria_labelledby: props.aria_labelledby.clone(),
class: "ui-list-box__native",
"data-ui-enhanced": "true",
"data-ui-list-box-native": "true",
disabled: unavailable,
form: props.form.clone(),
id: control_id.clone(),
multiple,
required: props.required,
tabindex: "-1",
onfocus: move |_| focus_element(machine.list_node.peek().clone()),
oninvalid: move |event| machine.invalid(&event),
..props.attributes,
if !multiple {
option { selected: single_value.is_empty(), value: "" }
}
for run in runs.iter() {
if let Some(heading) = run.label.clone() {
optgroup { label: heading,
for index in run.indexes.iter().copied() {
option {
disabled: options[index].disabled,
selected: is_native_selected(&options[index].value),
value: options[index].value.clone(),
"{options[index].label}"
}
}
}
} else {
for index in run.indexes.iter().copied() {
option {
disabled: options[index].disabled,
selected: is_native_selected(&options[index].value),
value: options[index].value.clone(),
"{options[index].label}"
}
}
}
}
}
if let Some((name, values)) = submitted {
for value in values {
input { form: props.form.clone(), name: name.clone(), r#type: "hidden", value }
}
}
div {
aria_activedescendant: active_id,
aria_busy: props.loading.then_some("true"),
aria_describedby: props.aria_describedby.clone(),
aria_disabled: unavailable.then_some("true"),
aria_errormessage: props.aria_errormessage.clone(),
aria_invalid,
aria_label: props.aria_label.clone(),
aria_labelledby: labelled_by,
aria_multiselectable: multiple.then_some("true"),
aria_required: props.required.then_some("true"),
class: "ui-list-box__list",
"data-ui-list-box-list": "true",
role: "listbox",
tabindex: (!unavailable).then_some("0"),
onkeydown: move |event| machine.keydown(&event),
onmounted: move |event| {
let mut node = machine.list_node;
node.set(Some(event.data()));
},
if !props.loading {
if options.is_empty() {
div {
aria_disabled: "true",
class: "ui-list-box__empty",
role: "option",
"{empty_message}"
}
}
for run in runs.iter() {
if let Some(heading) = run.label.as_deref() {
div {
aria_labelledby: list_box_group_label_id(
&control_id,
heading,
run.indexes.iter().map(|index| options[*index].value.as_str()),
),
role: "group",
div {
class: "ui-list-box__section",
id: list_box_group_label_id(
&control_id,
heading,
run.indexes.iter().map(|index| options[*index].value.as_str()),
),
"{heading}"
}
for index in run.indexes.iter().copied() {
{option_view(index)}
}
}
} else {
for index in run.indexes.iter().copied() {
{option_view(index)}
}
}
}
}
}
if props.loading {
p { class: "ui-list-box__status", role: "status", "{loading_message}" }
}
}
}
}
#[cfg(test)]
mod tests {
use super::{
ListBoxGroup, list_box_group_label_id, list_box_runs, list_box_submitted,
list_box_typeahead, move_active, resolve_active, selection_is_valid, toggle_selection,
};
use crate::SelectOption;
fn reviewers() -> Vec<SelectOption> {
vec![
SelectOption::new("amina", "Amina").disabled(true),
SelectOption::new("bruno", "Bruno"),
SelectOption::new("chen", "Chen"),
]
}
fn strings(values: &[&str]) -> Vec<String> {
values.iter().map(ToString::to_string).collect()
}
#[test]
fn the_active_option_starts_on_the_selection_and_never_rests_on_disabled_ones() {
let options = reviewers();
assert_eq!(resolve_active(&options, None, &strings(&["chen"])), Some(2));
assert_eq!(resolve_active(&options, None, &[]), Some(1));
assert_eq!(
resolve_active(&options, Some(0), &strings(&["chen"])),
Some(2)
);
assert_eq!(resolve_active(&options, Some(9), &[]), Some(1));
assert_eq!(
resolve_active(&options, Some(1), &strings(&["chen"])),
Some(1)
);
let disabled: Vec<SelectOption> = options
.into_iter()
.map(|option| option.disabled(true))
.collect();
assert_eq!(resolve_active(&disabled, None, &strings(&["chen"])), None);
assert_eq!(resolve_active(&[], None, &[]), None);
}
#[test]
fn arrow_keys_wrap_and_skip_disabled_options() {
let options = reviewers();
assert_eq!(move_active(&options, Some(1), true), Some(2));
assert_eq!(move_active(&options, Some(2), true), Some(1));
assert_eq!(move_active(&options, Some(1), false), Some(2));
assert_eq!(move_active(&options, None, true), Some(1));
assert_eq!(move_active(&[], None, true), None);
let disabled = vec![SelectOption::new("x", "X").disabled(true)];
assert_eq!(move_active(&disabled, None, true), None);
}
#[test]
fn activation_replaces_or_toggles_the_selection() {
let options = reviewers();
let selected = strings(&["bruno"]);
assert_eq!(
toggle_selection(&options, &selected, 2, false),
Some(strings(&["chen"]))
);
assert_eq!(
toggle_selection(&options, &selected, 1, false),
Some(strings(&["bruno"]))
);
assert_eq!(
toggle_selection(&options, &selected, 2, true),
Some(strings(&["bruno", "chen"]))
);
assert_eq!(
toggle_selection(&options, &selected, 1, true),
Some(Vec::new())
);
assert_eq!(toggle_selection(&options, &selected, 0, true), None);
assert_eq!(toggle_selection(&options, &selected, 7, false), None);
}
#[test]
fn typeahead_finds_the_first_enabled_label_from_the_top() {
let options = vec![
SelectOption::new("a", "Apple").disabled(true),
SelectOption::new("b", "Avocado"),
SelectOption::new("c", "Banana"),
];
assert_eq!(list_box_typeahead(&options, "a"), Some(1));
assert_eq!(list_box_typeahead(&options, "ba"), Some(2));
assert_eq!(list_box_typeahead(&options, "z"), None);
let many: Vec<SelectOption> = (0..5_000)
.map(|index| format!("Item {index}").into())
.collect();
assert_eq!(list_box_typeahead(&many, &"i".repeat(20_000)), None);
}
#[test]
fn submitted_values_match_a_native_select() {
let options = reviewers();
assert_eq!(list_box_submitted(&options, &[], false), strings(&[""]));
assert_eq!(
list_box_submitted(&options, &strings(&["chen"]), false),
strings(&["chen"])
);
assert_eq!(
list_box_submitted(&options, &strings(&["missing"]), false),
strings(&[""])
);
assert_eq!(
list_box_submitted(&options, &strings(&["amina"]), false),
strings(&[])
);
assert_eq!(
list_box_submitted(&options, &strings(&["chen", "amina", "bruno"]), true),
strings(&["bruno", "chen"])
);
assert_eq!(list_box_submitted(&options, &[], true), strings(&[]));
}
#[test]
fn required_validity_follows_the_native_select() {
let options = reviewers();
assert!(!selection_is_valid(&options, &[], false));
assert!(!selection_is_valid(&options, &strings(&["missing"]), false));
assert!(selection_is_valid(&options, &strings(&["bruno"]), false));
assert!(!selection_is_valid(&options, &[], true));
assert!(selection_is_valid(&options, &strings(&["chen"]), true));
}
#[test]
fn groups_flatten_in_order_and_merge_adjacent_headings() {
let (flat, runs) = list_box_runs(
&[SelectOption::from("Loose")],
&[
ListBoxGroup::new("Fruit", ["Apple"]),
ListBoxGroup::new("Fruit", ["Pear"]),
ListBoxGroup::new("", ["Water"]),
ListBoxGroup::ungrouped(["Tea"]),
ListBoxGroup::new("Empty", Vec::<SelectOption>::new()),
],
);
let labels: Vec<&str> = flat.iter().map(|option| option.label.as_str()).collect();
assert_eq!(labels, ["Loose", "Apple", "Pear", "Water", "Tea"]);
assert_eq!(runs.len(), 3);
assert_eq!(runs[0].label, None);
assert_eq!(runs[1].label.as_deref(), Some("Fruit"));
assert_eq!(runs[1].indexes, [1, 2]);
assert_eq!(runs[2].label, None);
assert_eq!(runs[2].indexes, [3, 4]);
}
#[test]
fn group_ids_replace_each_utf16_unit_outside_the_safe_set() {
assert_eq!(
list_box_group_label_id("food", "Leafy greens", ["kale"]),
"food-group-Leafy-greens-kale"
);
assert_eq!(
list_box_group_label_id("food", "Fruits é", ["a b", "c"]),
"food-group-Fruits---a-b-c"
);
assert_eq!(list_box_group_label_id("x", "😀", ["v"]), "x-group----v");
let long = "é".repeat(50_000);
assert_eq!(
list_box_group_label_id("x", &long, ["v"]).len(),
"x-group-".len() + 50_000 + 2
);
}
}