Skip to main content

next_rust_ui/
select.rs

1//! A custom select with a listbox popover.
2
3use next_rust_view::{Attr, Element, Node, View};
4
5use crate::icons::{self, icon};
6use crate::input::{Field, Frame, field_methods};
7use crate::{Extra, apply, attr, flag, next_id};
8
9/// One option of a [`Select`]. The text children are its label.
10///
11/// `SelectItem![value = "in", description = "+91", "India"]`
12#[derive(Default)]
13pub struct SelectItem {
14    value: Option<String>,
15    label: Option<String>,
16    description: Option<String>,
17    start_content: Option<Node>,
18    disabled: bool,
19    extra: Extra,
20}
21
22impl SelectItem {
23    pub fn new() -> Self {
24        Self::default()
25    }
26    /// Submitted value (defaults to the label).
27    pub fn value(mut self, v: impl Into<String>) -> Self {
28        self.value = Some(v.into());
29        self
30    }
31    /// The text shown; children text works too.
32    pub fn label(mut self, v: impl Into<String>) -> Self {
33        self.label = Some(v.into());
34        self
35    }
36    /// Secondary text under the label.
37    pub fn description(mut self, v: impl Into<String>) -> Self {
38        self.description = Some(v.into());
39        self
40    }
41    /// An icon or avatar before the label.
42    pub fn start_content(mut self, v: impl View) -> Self {
43        self.start_content = Some(v.into_node());
44        self
45    }
46    pub fn disabled(mut self, v: bool) -> Self {
47        self.disabled = v;
48        self
49    }
50    /// Add an attribute to the option, or children (their text is the label).
51    pub fn with(mut self, part: impl next_rust_view::Part) -> Self {
52        self.extra.push(part);
53        self
54    }
55}
56
57/// Values accepted inside `Select![..]`: items and attributes for the control.
58pub trait SelectPart {
59    fn add_to(self, select: &mut Select);
60}
61
62impl SelectPart for SelectItem {
63    fn add_to(self, select: &mut Select) {
64        select.items.push(self);
65    }
66}
67impl SelectPart for Vec<SelectItem> {
68    fn add_to(self, select: &mut Select) {
69        select.items.extend(self);
70    }
71}
72impl SelectPart for Attr {
73    fn add_to(self, select: &mut Select) {
74        select.field.extra.push(self);
75    }
76}
77/// `("value", "Label")`.
78impl SelectPart for (&str, &str) {
79    fn add_to(self, select: &mut Select) {
80        select.items.push(SelectItem::new().value(self.0).label(self.1));
81    }
82}
83impl<const N: usize> SelectPart for [(&str, &str); N] {
84    fn add_to(self, select: &mut Select) {
85        for item in self {
86            item.add_to(select);
87        }
88    }
89}
90
91/// A select with a styled listbox: keyboard navigation, type-ahead, single or
92/// multiple choice. Submits like a native `<select>` (it is one underneath).
93///
94/// ```
95/// # use next_rust_ui::*; use next_rust_view::*;
96/// let s = Select![label = "Country", name = "country", value = "in",
97///     SelectItem![value = "in", "India"], SelectItem![value = "us", "United States"]];
98/// let html = render_static(s);
99/// assert!(html.contains(r#"<option value="in" selected>India</option>"#));
100/// assert!(html.contains(r#"role="option""#));
101/// ```
102#[derive(Default)]
103pub struct Select {
104    field: Field,
105    items: Vec<SelectItem>,
106    multiple: bool,
107    values: Vec<String>,
108}
109
110impl Select {
111    pub fn new() -> Self {
112        Self::default()
113    }
114    field_methods!();
115
116    /// Add options ([`SelectItem`], `("value", "Label")`) or attributes for
117    /// the control; `class(..)` goes to the outer element.
118    pub fn with(mut self, part: impl SelectPart) -> Self {
119        part.add_to(&mut self);
120        self
121    }
122    /// Options, as a list.
123    pub fn items(mut self, v: impl IntoIterator<Item = SelectItem>) -> Self {
124        self.items.extend(v);
125        self
126    }
127    /// Allow choosing several options.
128    pub fn multiple(mut self, v: bool) -> Self {
129        self.multiple = v;
130        self
131    }
132    /// Selected values when `multiple`.
133    pub fn values<S: Into<String>>(mut self, v: impl IntoIterator<Item = S>) -> Self {
134        self.values = v.into_iter().map(Into::into).collect();
135        self
136    }
137}
138
139/// Text of the text nodes among `nodes`.
140fn text_of(nodes: &[Node]) -> String {
141    let mut out = String::new();
142    for n in nodes {
143        match n {
144            Node::Text(t) => out.push_str(t),
145            Node::Fragment(children) => out.push_str(&text_of(children)),
146            _ => {}
147        }
148    }
149    out.trim().to_owned()
150}
151
152impl View for Select {
153    fn into_node(mut self) -> Node {
154        let (class, attrs, _) = std::mem::take(&mut self.field.extra).split();
155        if let Some(class) = class {
156            self.field.extra.push(class);
157        }
158        let selected: Vec<String> = match (&self.field.value, self.multiple) {
159            (_, true) => self.values.clone(),
160            (Some(v), false) => vec![v.clone()],
161            (None, false) => Vec::new(),
162        };
163        let id = self.field.control_id();
164        let list_id = next_id("nr-listbox");
165        let placeholder = self.field.placeholder.clone();
166
167        let mut native = Element::new("select").with(attr(
168            "class",
169            match &self.field.input_class {
170                Some(c) => format!("nr-field-input nr-select-native {c}"),
171                None => "nr-field-input nr-select-native".to_owned(),
172            },
173        ));
174        apply(&mut native, self.field.control_attrs());
175        native.set_attr(flag("multiple", self.multiple));
176        apply(&mut native, attrs);
177        if !self.multiple {
178            // The empty choice: the placeholder, or nothing.
179            native.children.push(
180                Element::new("option")
181                    .with(attr("value", ""))
182                    .with(flag("selected", selected.is_empty()))
183                    .with(flag("disabled", self.field.required))
184                    .with(placeholder.clone().unwrap_or_default())
185                    .into_node(),
186            );
187        }
188
189        let mut list = Element::new("ul")
190            .with(attr("class", "nr-select-list"))
191            .with(attr("id", list_id.clone()))
192            .with(attr("role", "listbox"))
193            .with(attr("tabindex", "-1"))
194            .with(flag("hidden", true));
195        if self.multiple {
196            list.set_attr(attr("aria-multiselectable", "true"));
197        }
198
199        let mut chosen = Vec::new();
200        for (i, item) in self.items.into_iter().enumerate() {
201            let (_, item_attrs, children) = item.extra.split();
202            let label = item.label.clone().unwrap_or_else(|| text_of(&children));
203            let value = item.value.clone().unwrap_or_else(|| label.clone());
204            let is_selected = selected.contains(&value);
205            if is_selected {
206                chosen.push(label.clone());
207            }
208            native.children.push(
209                Element::new("option")
210                    .with(attr("value", value.clone()))
211                    .with(flag("selected", is_selected))
212                    .with(flag("disabled", item.disabled))
213                    .with(label.clone())
214                    .into_node(),
215            );
216            let mut option = Element::new("li")
217                .with(attr("class", "nr-select-option"))
218                .with(attr("id", format!("{list_id}-{i}")))
219                .with(attr("role", "option"))
220                .with(attr("data-value", value))
221                .with(attr("aria-selected", if is_selected { "true" } else { "false" }));
222            if item.disabled {
223                option.set_attr(attr("aria-disabled", "true"));
224            }
225            apply(&mut option, item_attrs);
226            if let Some(start) = item.start_content {
227                option
228                    .children
229                    .push(Element::new("span").with(attr("class", "nr-select-option-start")).with(start).into_node());
230            }
231            let mut text = Element::new("span")
232                .with(attr("class", "nr-select-option-text"))
233                .with(Element::new("span").with(attr("class", "nr-select-option-label")).with(label));
234            if let Some(d) = item.description {
235                text = text.with(Element::new("span").with(attr("class", "nr-select-option-description")).with(d));
236            }
237            option.children.push(text.into_node());
238            option.children.push(
239                Element::new("span")
240                    .with(attr("class", "nr-select-check"))
241                    .with(icon(icons::check().stroke_width(3.0)))
242                    .into_node(),
243            );
244            list.children.push(option.into_node());
245        }
246
247        let shown = if chosen.is_empty() { placeholder.clone().unwrap_or_default() } else { chosen.join(", ") };
248        let mut trigger = Element::new("button")
249            .with(attr("type", "button"))
250            .with(attr("class", "nr-select-trigger"))
251            .with(attr("aria-haspopup", "listbox"))
252            .with(attr("aria-expanded", "false"))
253            .with(attr("aria-controls", list_id))
254            .with(flag("disabled", self.field.disabled))
255            .with(
256                Element::new("span")
257                    .with(attr("class", "nr-select-value"))
258                    .with(flag("data-placeholder", chosen.is_empty()))
259                    .with(shown),
260            );
261        if self.field.label.is_some() {
262            trigger.set_attr(attr("aria-labelledby", format!("{id}-label {id}-trigger")));
263        }
264        trigger.set_attr(attr("id", format!("{id}-trigger")));
265
266        let floats = placeholder.is_none();
267        let root_attrs: Vec<Attr> = vec![
268            attr("data-nr-ui", "select"),
269            flag("data-filled", !chosen.is_empty()),
270            flag("data-multiple", self.multiple),
271        ];
272        let end = vec![
273            Element::new("span").with(attr("class", "nr-select-chevron")).with(icon(icons::chevron_down())).into_node(),
274        ];
275        let control = Node::Fragment(vec![native.into_node(), trigger.into_node()]);
276        self.field
277            .render(control, Frame { kind: "nr-select", floats, after_box: vec![list.into_node()], root_attrs, end })
278    }
279}