lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `FormErrors` and `FormFieldError`: form validation results, normalized like
//! `normalizeLumenFormErrors` in lumen-core.

/// One field's validation message.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FormFieldError {
    /// The field name, such as `email`.
    pub name: String,
    /// The message shown to the user.
    pub message: String,
    /// Id of the visible control. [`ErrorSummary`](crate::ErrorSummary) links the message to it.
    pub control_id: Option<String>,
    /// An application error code, such as `required`.
    pub code: Option<String>,
}

impl FormFieldError {
    /// A message for the field `name`.
    pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            message: message.into(),
            control_id: None,
            code: None,
        }
    }

    /// Returns the error linked to the control with this id.
    #[must_use]
    pub fn control_id(mut self, control_id: impl Into<String>) -> Self {
        self.control_id = Some(control_id.into());
        self
    }

    /// Returns the error with an application error code.
    #[must_use]
    pub fn code(mut self, code: impl Into<String>) -> Self {
        self.code = Some(code.into());
        self
    }

    /// The trimmed error, or `None` when the name or the message is blank. Empty control ids and
    /// codes are dropped.
    fn normalized(&self) -> Option<Self> {
        let name = self.name.trim();
        let message = self.message.trim();

        if name.is_empty() || message.is_empty() {
            return None;
        }

        Some(Self {
            name: name.to_string(),
            message: message.to_string(),
            control_id: self.control_id.clone().filter(|id| !id.is_empty()),
            code: self.code.clone().filter(|code| !code.is_empty()),
        })
    }
}

/// Validation errors for a whole form: form-level messages and field messages, like lumen-core's
/// `LumenFormErrors`.
///
/// Build it from field errors, from `(name, message)` pairs (the names `form` and `root` hold
/// form-level messages, and pairs never link to a control, like lumen-core's record input), or
/// field by field:
///
/// ```
/// use lumen_dioxus::{FormErrors, FormFieldError};
///
/// let from_pairs = FormErrors::from(vec![("form", "Try again."), ("email", "Enter an email.")]);
/// let from_fields = FormErrors::from(vec![
///     FormFieldError::new("email", "Enter an email.").control_id("email"),
/// ]);
///
/// assert_eq!(from_pairs.form, vec!["Try again.".to_string()]);
/// assert_eq!(from_fields.fields[0].control_id.as_deref(), Some("email"));
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct FormErrors {
    /// Field messages, in order.
    pub fields: Vec<FormFieldError>,
    /// Form-level messages, in order.
    pub form: Vec<String>,
}

impl FormErrors {
    /// Whether there is no message at all.
    pub fn is_empty(&self) -> bool {
        self.fields.is_empty() && self.form.is_empty()
    }

    /// The errors with trimmed text, without blank messages, and without field errors that have
    /// no name, like `normalizeLumenFormErrors`.
    #[must_use]
    pub fn normalized(&self) -> Self {
        Self {
            fields: self
                .fields
                .iter()
                .filter_map(FormFieldError::normalized)
                .collect(),
            form: compact_messages(&self.form),
        }
    }

    /// The normalized messages of one field.
    pub fn field(&self, name: &str) -> Vec<FormFieldError> {
        self.normalized()
            .fields
            .into_iter()
            .filter(|error| error.name == name)
            .collect()
    }
}

fn compact_messages(messages: &[String]) -> Vec<String> {
    messages
        .iter()
        .map(|message| message.trim())
        .filter(|message| !message.is_empty())
        .map(str::to_string)
        .collect()
}

impl From<Vec<FormFieldError>> for FormErrors {
    fn from(fields: Vec<FormFieldError>) -> Self {
        Self {
            fields,
            form: Vec::new(),
        }
    }
}

impl<N: Into<String>, M: Into<String>> From<Vec<(N, M)>> for FormErrors {
    fn from(pairs: Vec<(N, M)>) -> Self {
        let mut errors = Self::default();

        for (name, message) in pairs {
            let name = name.into();
            let message = message.into();

            if name == "form" || name == "root" {
                errors.form.push(message);
            } else {
                errors.fields.push(FormFieldError::new(name, message));
            }
        }

        errors
    }
}

#[cfg(test)]
mod tests {
    use super::{FormErrors, FormFieldError};

    #[test]
    fn pairs_split_form_and_field_messages() {
        let errors = FormErrors::from(vec![
            ("form", " Try again. "),
            ("email", "Enter an email."),
            ("root", ""),
            ("name", "  "),
        ])
        .normalized();

        assert_eq!(errors.form, vec!["Try again.".to_string()]);
        assert_eq!(
            errors.fields,
            vec![FormFieldError::new("email", "Enter an email.")]
        );
    }

    #[test]
    fn field_errors_are_trimmed_and_blank_ones_dropped() {
        let errors = FormErrors {
            fields: vec![
                FormFieldError::new(" email ", " Enter an email. ")
                    .control_id("email")
                    .code("required"),
                FormFieldError::new("", "No name"),
                FormFieldError::new("name", ""),
                FormFieldError::new("age", "Too young").control_id(""),
            ],
            form: vec![" ".to_string(), "Server error".to_string()],
        }
        .normalized();

        assert_eq!(errors.form, vec!["Server error".to_string()]);
        assert_eq!(
            errors.fields,
            vec![
                FormFieldError::new("email", "Enter an email.")
                    .control_id("email")
                    .code("required"),
                FormFieldError::new("age", "Too young"),
            ]
        );
        assert_eq!(errors.field("age").len(), 1);
        assert_eq!(errors.field("missing"), Vec::<FormFieldError>::new());
        assert!(FormErrors::default().is_empty());
        assert!(!errors.is_empty());
    }
}