Skip to main content

lumen_dioxus/inputs/
select_option.rs

1//! `SelectOption`: one choice shared by the option-list components.
2
3/// One choice in a [`Select`](crate::Select), [`NativeSelect`](crate::NativeSelect),
4/// [`ListBox`](crate::ListBox), [`Segmented`](crate::Segmented), or [`Mentions`](crate::Mentions)
5/// list, like lumen-react's `SelectOption`.
6///
7/// Build options from plain strings (the label is also the value) or with [`SelectOption::new`]:
8///
9/// ```
10/// use lumen_dioxus::SelectOption;
11///
12/// let options: Vec<SelectOption> = vec![
13///     "Draft".into(),
14///     SelectOption::new("published", "Published"),
15///     SelectOption::new("archived", "Archived").disabled(true),
16/// ];
17///
18/// assert_eq!(options[0].value, "Draft");
19/// assert!(options[2].disabled);
20/// ```
21#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
22pub struct SelectOption {
23    /// The value the option submits and reports.
24    pub value: String,
25    /// The visible label.
26    pub label: String,
27    /// Whether the option is unavailable.
28    pub disabled: bool,
29}
30
31impl SelectOption {
32    /// An enabled option with a separate value and label.
33    pub fn new(value: impl Into<String>, label: impl Into<String>) -> Self {
34        Self {
35            value: value.into(),
36            label: label.into(),
37            disabled: false,
38        }
39    }
40
41    /// Returns the option with its disabled state set.
42    #[must_use]
43    pub fn disabled(mut self, disabled: bool) -> Self {
44        self.disabled = disabled;
45        self
46    }
47}
48
49impl From<&str> for SelectOption {
50    fn from(value: &str) -> Self {
51        Self::new(value, value)
52    }
53}
54
55impl From<String> for SelectOption {
56    fn from(value: String) -> Self {
57        Self {
58            label: value.clone(),
59            value,
60            disabled: false,
61        }
62    }
63}
64
65impl From<(&str, &str)> for SelectOption {
66    fn from((value, label): (&str, &str)) -> Self {
67        Self::new(value, label)
68    }
69}
70
71#[cfg(test)]
72mod tests {
73    use super::SelectOption;
74
75    #[test]
76    fn strings_become_options_with_matching_label_and_value() {
77        let option = SelectOption::from("Draft");
78
79        assert_eq!(option, SelectOption::new("Draft", "Draft"));
80        assert_eq!(
81            SelectOption::from(String::from("Live")),
82            SelectOption::new("Live", "Live")
83        );
84        assert_eq!(
85            SelectOption::from(("a", "Alpha")).disabled(true),
86            SelectOption {
87                value: "a".into(),
88                label: "Alpha".into(),
89                disabled: true
90            }
91        );
92    }
93}