Skip to main content

lumen_dioxus/inputs/
autocomplete.rs

1//! `Autocomplete`: a search input tied to a `<datalist>` of suggestions.
2
3use dioxus::prelude::*;
4
5use super::SelectOption;
6use crate::class::compose;
7
8/// Props for [`Autocomplete`].
9#[derive(Props, Clone, PartialEq)]
10pub struct AutocompleteProps {
11    /// Id of the `<datalist>` that holds the suggestions.
12    #[props(into)]
13    pub list: String,
14    /// The native input type. Defaults to `search`.
15    #[props(default = "search".to_string(), into)]
16    pub r#type: String,
17    /// Suggestions to render as a `<datalist>` with the `list` id, right after the input. Leave
18    /// empty (the default) to point `list` at a datalist you render yourself, like lumen-react.
19    #[props(default)]
20    pub options: Vec<SelectOption>,
21    /// Extra classes appended after the Lumen classes.
22    #[props(into)]
23    pub class: Option<String>,
24    /// Fires on every edit.
25    pub oninput: Option<EventHandler<FormEvent>>,
26    /// Fires when the value is committed.
27    pub onchange: Option<EventHandler<FormEvent>>,
28    /// Any other `<input>` or global attribute, such as `value`, `name`, or `placeholder`.
29    #[props(extends = GlobalAttributes, extends = input)]
30    pub attributes: Vec<Attribute>,
31}
32
33/// A search input with `role="combobox"` that suggests values from a `<datalist>`.
34///
35/// Browsers and desktop webviews draw the datalist's suggestion popup. Dioxus Native has no
36/// datalist popup, so the input works there as a plain search field; use
37/// [`Combobox`](crate::Combobox) when the suggestions must show on every renderer.
38#[component]
39pub fn Autocomplete(props: AutocompleteProps) -> Element {
40    let class = compose([Some("ui-input ui-autocomplete"), props.class.as_deref()]);
41    let (oninput, onchange) = (props.oninput, props.onchange);
42    let list = props.list.clone();
43
44    rsx! {
45        input {
46            aria_autocomplete: "list",
47            class,
48            list: list.clone(),
49            r#type: props.r#type,
50            oninput: move |event| {
51                if let Some(handler) = oninput {
52                    handler.call(event);
53                }
54            },
55            onchange: move |event| {
56                if let Some(handler) = onchange {
57                    handler.call(event);
58                }
59            },
60            ..props.attributes,
61        }
62        if !props.options.is_empty() {
63            datalist { id: props.list,
64                for (index, option) in props.options.into_iter().enumerate() {
65                    option {
66                        key: "{index}",
67                        disabled: option.disabled,
68                        value: option.value.clone(),
69                        "{option.label}"
70                    }
71                }
72            }
73        }
74    }
75}