lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `SelectOption`: one choice shared by the option-list components.

/// One choice in a [`Select`](crate::Select), [`NativeSelect`](crate::NativeSelect),
/// [`ListBox`](crate::ListBox), [`Segmented`](crate::Segmented), or [`Mentions`](crate::Mentions)
/// list, like lumen-react's `SelectOption`.
///
/// Build options from plain strings (the label is also the value) or with [`SelectOption::new`]:
///
/// ```
/// use lumen_dioxus::SelectOption;
///
/// let options: Vec<SelectOption> = vec![
///     "Draft".into(),
///     SelectOption::new("published", "Published"),
///     SelectOption::new("archived", "Archived").disabled(true),
/// ];
///
/// assert_eq!(options[0].value, "Draft");
/// assert!(options[2].disabled);
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub struct SelectOption {
    /// The value the option submits and reports.
    pub value: String,
    /// The visible label.
    pub label: String,
    /// Whether the option is unavailable.
    pub disabled: bool,
}

impl SelectOption {
    /// An enabled option with a separate value and label.
    pub fn new(value: impl Into<String>, label: impl Into<String>) -> Self {
        Self {
            value: value.into(),
            label: label.into(),
            disabled: false,
        }
    }

    /// Returns the option with its disabled state set.
    #[must_use]
    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }
}

impl From<&str> for SelectOption {
    fn from(value: &str) -> Self {
        Self::new(value, value)
    }
}

impl From<String> for SelectOption {
    fn from(value: String) -> Self {
        Self {
            label: value.clone(),
            value,
            disabled: false,
        }
    }
}

impl From<(&str, &str)> for SelectOption {
    fn from((value, label): (&str, &str)) -> Self {
        Self::new(value, label)
    }
}

#[cfg(test)]
mod tests {
    use super::SelectOption;

    #[test]
    fn strings_become_options_with_matching_label_and_value() {
        let option = SelectOption::from("Draft");

        assert_eq!(option, SelectOption::new("Draft", "Draft"));
        assert_eq!(
            SelectOption::from(String::from("Live")),
            SelectOption::new("Live", "Live")
        );
        assert_eq!(
            SelectOption::from(("a", "Alpha")).disabled(true),
            SelectOption {
                value: "a".into(),
                label: "Alpha".into(),
                disabled: true
            }
        );
    }
}