use std::collections::HashMap;
use std::rc::Rc;
use dioxus::html::{ScrollBehavior, ScrollLogicalPosition, ScrollToOptions};
use dioxus::prelude::*;
use super::SelectOption;
use crate::class::compose;
use crate::hooks::{Controllable, use_controllable};
use crate::overlay::{DismissLayer, focus_element, wrap_index};
#[derive(Props, Clone, PartialEq)]
pub struct ComboboxProps {
#[props(into)]
pub list: String,
#[props(into)]
pub label: Option<String>,
#[props(default)]
pub options: Vec<SelectOption>,
#[props(into)]
pub value: Option<String>,
#[props(default, into)]
pub default_value: String,
pub on_value_change: Option<EventHandler<String>>,
#[props(into)]
pub id: Option<String>,
#[props(default = "text".to_string(), into)]
pub r#type: String,
#[props(default)]
pub disabled: bool,
#[props(default)]
pub readonly: bool,
#[props(into)]
pub aria_label: Option<String>,
#[props(into)]
pub aria_labelledby: Option<String>,
pub onkeydown: Option<EventHandler<KeyboardEvent>>,
pub onfocus: Option<EventHandler<FocusEvent>>,
pub onblur: Option<EventHandler<FocusEvent>>,
#[props(into)]
pub class: Option<String>,
#[props(into)]
pub wrapper_class: Option<String>,
#[props(extends = GlobalAttributes, extends = input)]
pub attributes: Vec<Attribute>,
}
fn js_trim(text: &str) -> &str {
text.trim_matches(|c: char| (c.is_whitespace() && c != '\u{85}') || c == '\u{feff}')
}
pub(crate) fn combobox_query(text: &str) -> String {
js_trim(text).to_lowercase()
}
pub(crate) fn combobox_matches(option: &SelectOption, query: &str) -> bool {
query.is_empty()
|| option.label.to_lowercase().contains(query)
|| option.value.to_lowercase().contains(query)
}
pub(crate) fn combobox_visible<'a>(
options: &'a [SelectOption],
text: &str,
) -> Vec<&'a SelectOption> {
let query = combobox_query(text);
options
.iter()
.filter(|option| combobox_matches(option, &query))
.collect()
}
pub(crate) fn combobox_active_index(
visible: &[&SelectOption],
active: Option<&str>,
) -> Option<usize> {
let active = active?;
visible
.iter()
.position(|option| option.value == active)
.filter(|index| !visible[*index].disabled)
}
pub(crate) fn combobox_step(
visible: &[&SelectOption],
current: Option<usize>,
forward: bool,
) -> Option<usize> {
let enabled: Vec<usize> = visible
.iter()
.enumerate()
.filter(|(_, option)| !option.disabled)
.map(|(index, _)| index)
.collect();
let position = current.and_then(|index| enabled.iter().position(|entry| *entry == index));
wrap_index(position, if forward { 1 } else { -1 }, enabled.len()).map(|next| enabled[next])
}
fn has_shortcut_modifier(event: &KeyboardEvent) -> bool {
let modifiers = event.modifiers();
modifiers.contains(Modifiers::ALT)
|| modifiers.contains(Modifiers::CONTROL)
|| modifiers.contains(Modifiers::META)
|| modifiers.contains(Modifiers::SUPER)
}
#[derive(Clone, Copy)]
struct ComboboxState {
value: Controllable<String>,
open: Signal<bool>,
active: Signal<Option<String>>,
composing: Signal<bool>,
input: Signal<Option<Rc<MountedData>>>,
locked: bool,
}
impl ComboboxState {
fn close(mut self) {
if *self.open.peek() {
self.open.set(false);
}
if self.active.peek().is_some() {
self.active.set(None);
}
}
fn open_list(mut self) {
if !self.locked && !*self.open.peek() {
self.open.set(true);
}
}
fn select(self, option: &SelectOption) {
if self.locked || option.disabled {
return;
}
self.value.set(option.value.clone());
focus_element(self.input.peek().clone());
self.close();
}
}
#[component]
pub fn Combobox(props: ComboboxProps) -> Element {
let value = use_controllable(
props.value.clone(),
|| props.default_value.clone(),
props.on_value_change,
);
let open = use_signal(|| false);
let active = use_signal(|| None::<String>);
let composing = use_signal(|| false);
let input = use_signal(|| None::<Rc<MountedData>>);
let mut option_nodes = use_signal(HashMap::<usize, Rc<MountedData>>::new);
let locked = props.disabled || props.readonly;
let state = ComboboxState {
value,
open,
active,
composing,
input,
locked,
};
let list = props.list.clone();
let input_id = props.id.clone().unwrap_or_else(|| format!("{list}-input"));
let label = props.label.clone().filter(|label| !label.is_empty());
let current = value.get();
let visible = combobox_visible(&props.options, ¤t);
let expanded = *open.read() && !locked;
let active_index = combobox_active_index(&visible, active.read().as_deref());
let selected = active_index.filter(|_| expanded);
let active_id = selected.map(|index| format!("{list}-option-{index}"));
let list_labelledby = props
.aria_labelledby
.clone()
.or_else(|| label.as_ref().map(|_| format!("{input_id}-label")));
use_effect(use_reactive((&selected,), move |(target,)| {
let Some(node) = target.and_then(|index| option_nodes.peek().get(&index).cloned()) else {
return;
};
spawn(async move {
let _ = node
.scroll_to_with_options(ScrollToOptions {
behavior: ScrollBehavior::Instant,
vertical: ScrollLogicalPosition::Nearest,
horizontal: ScrollLogicalPosition::Nearest,
})
.await;
});
}));
let options = props.options.clone();
let user_keydown = props.onkeydown;
let user_focus = props.onfocus;
let user_blur = props.onblur;
let input_class = compose([Some("ui-input"), props.class.as_deref()]);
let wrapper_class = compose([Some("ui-combobox"), props.wrapper_class.as_deref()]);
rsx! {
div { class: wrapper_class, "data-ui-combobox": "true",
if expanded {
DismissLayer { on_dismiss: move |()| state.close() }
}
if let Some(label) = label {
label {
class: "ui-label",
r#for: input_id.clone(),
id: "{input_id}-label",
"{label}"
}
}
input {
aria_activedescendant: active_id,
aria_autocomplete: "list",
aria_controls: list.clone(),
aria_expanded: if expanded { "true" } else { "false" },
aria_label: props.aria_label.clone(),
aria_labelledby: props.aria_labelledby.clone(),
class: input_class,
disabled: props.disabled,
id: input_id.clone(),
readonly: props.readonly,
role: "combobox",
r#type: props.r#type.clone(),
value: current,
oninput: move |event: FormEvent| {
let mut active = state.active;
let mut open = state.open;
state.value.set(event.value());
active.set(None);
open.set(true);
},
onfocus: move |event: FocusEvent| {
state.open_list();
if let Some(handler) = user_focus {
handler.call(event);
}
},
onclick: move |_| state.open_list(),
onblur: move |event: FocusEvent| {
state.close();
if let Some(handler) = user_blur {
handler.call(event);
}
},
oncompositionstart: move |_| {
let mut composing = state.composing;
composing.set(true);
},
oncompositionend: move |_| {
let mut composing = state.composing;
composing.set(false);
},
onkeydown: move |event: KeyboardEvent| {
if let Some(handler) = user_keydown {
handler.call(event.clone());
}
if !event.default_action_enabled()
|| event.is_composing()
|| *state.composing.peek()
|| has_shortcut_modifier(&event)
|| state.locked
{
return;
}
let text = state.value.peek();
let visible = combobox_visible(&options, &text);
let expanded = *state.open.peek();
let current = combobox_active_index(&visible, state.active.peek().as_deref())
.filter(|_| expanded);
match event.key() {
Key::Escape => {
if !expanded {
return;
}
event.prevent_default();
event.stop_propagation();
state.close();
}
Key::ArrowDown | Key::ArrowUp => {
event.prevent_default();
let forward = event.key() == Key::ArrowDown;
let next = combobox_step(&visible, current, forward)
.map(|index| visible[index].value.clone());
let mut open = state.open;
let mut active = state.active;
open.set(true);
active.set(next);
}
Key::Enter => {
if let Some(index) = current {
event.prevent_default();
state.select(visible[index]);
}
}
Key::Tab => state.close(),
_ => {}
}
},
onmounted: move |event| {
let mut input = state.input;
input.set(Some(event.data()));
},
..props.attributes,
}
div {
aria_label: props.aria_label.clone(),
aria_labelledby: list_labelledby,
class: "ui-combobox__list",
hidden: !expanded,
id: list.clone(),
role: "listbox",
for (index, option) in visible.into_iter().enumerate() {
button {
key: "{index}",
aria_disabled: option.disabled.then_some("true"),
aria_selected: if selected == Some(index) { "true" } else { "false" },
"data-ui-combobox-option": "true",
"data-value": option.value.clone(),
disabled: option.disabled,
id: "{list}-option-{index}",
role: "option",
tabindex: "-1",
r#type: "button",
onclick: {
let option = option.clone();
move |event: MouseEvent| {
event.prevent_default();
state.select(&option);
}
},
onmousedown: move |event: MouseEvent| event.prevent_default(),
onmounted: move |event| {
option_nodes.write().insert(index, event.data());
},
"{option.label}"
}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::{
SelectOption, combobox_active_index, combobox_matches, combobox_query, combobox_step,
combobox_visible, js_trim,
};
fn options() -> Vec<SelectOption> {
vec![
"Astro".into(),
SelectOption::new("react", "React"),
SelectOption::new("wc", "Web Components").disabled(true),
"Svelte".into(),
]
}
#[test]
fn the_query_is_trimmed_and_lowercase() {
assert_eq!(combobox_query(" ReA \n"), "rea");
assert_eq!(combobox_query("\u{feff}Astro\u{a0}"), "astro");
assert_eq!(js_trim("\u{85}a"), "\u{85}a");
assert_eq!(combobox_query(""), "");
}
#[test]
fn options_match_by_label_or_value() {
let option = SelectOption::new("wc", "Web Components");
assert!(combobox_matches(&option, ""));
assert!(combobox_matches(&option, "comp"));
assert!(combobox_matches(&option, "wc"));
assert!(!combobox_matches(&option, "react"));
}
#[test]
fn visible_options_follow_the_typed_text() {
let options = options();
let labels = |text: &str| -> Vec<String> {
combobox_visible(&options, text)
.into_iter()
.map(|option| option.label.clone())
.collect()
};
assert_eq!(labels(""), ["Astro", "React", "Web Components", "Svelte"]);
assert_eq!(labels(" RE "), ["React"]);
assert_eq!(labels("e"), ["React", "Web Components", "Svelte"]);
assert_eq!(labels("zzz"), Vec::<String>::new());
}
#[test]
fn arrow_keys_wrap_and_skip_disabled_options() {
let options = options();
let visible = combobox_visible(&options, "");
assert_eq!(combobox_step(&visible, None, true), Some(0));
assert_eq!(combobox_step(&visible, None, false), Some(3));
assert_eq!(combobox_step(&visible, Some(1), true), Some(3));
assert_eq!(combobox_step(&visible, Some(3), true), Some(0));
assert_eq!(combobox_step(&visible, Some(3), false), Some(1));
assert_eq!(combobox_step(&visible, Some(0), false), Some(3));
assert_eq!(combobox_step(&[], None, true), None);
let only_disabled = [SelectOption::from("x").disabled(true)];
let visible: Vec<&SelectOption> = only_disabled.iter().collect();
assert_eq!(combobox_step(&visible, None, true), None);
}
#[test]
fn the_active_option_must_stay_visible_and_enabled() {
let options = options();
let visible = combobox_visible(&options, "");
assert_eq!(combobox_active_index(&visible, Some("react")), Some(1));
assert_eq!(combobox_active_index(&visible, Some("wc")), None);
assert_eq!(combobox_active_index(&visible, Some("gone")), None);
assert_eq!(combobox_active_index(&visible, None), None);
let filtered = combobox_visible(&options, "sv");
assert_eq!(combobox_active_index(&filtered, Some("Svelte")), Some(0));
assert_eq!(combobox_active_index(&filtered, Some("react")), None);
}
#[test]
fn filtering_long_input_stays_linear() {
let options: Vec<SelectOption> = (0..200)
.map(|index| format!("option {index}").into())
.collect();
let text = "a".repeat(100_000);
assert_eq!(
combobox_visible(&options, &text),
Vec::<&SelectOption>::new()
);
assert_eq!(
combobox_query(&format!("{}x{}", " ".repeat(50_000), " ".repeat(50_000))),
"x"
);
}
}