lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `SettingsRow`: a label and description on the start side with a control on the end side.

// cspell:words feff

use dioxus::prelude::*;

use crate::class::compose;
use crate::hooks::use_unique_id;

/// The longest id lumen-core accepts.
const MAX_ID_LENGTH: usize = 256;
/// The id prefix when neither `control_id` nor `id` is usable.
const FALLBACK_PREFIX: &str = "ui-settings-row";

/// Attributes a [`SettingsRow`] hands to its `control` render function, so the row names and
/// describes the control. Spread them on the control, like lumen-react's
/// `SettingsRowControlProps`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SettingsRowControlProps {
    /// Id for the control. The row's `<label>` points at it.
    pub id: String,
    /// Id of the row's label, for controls that `<label for>` cannot name (such as the ARIA-button
    /// `Switch` and `Checkbox`).
    pub aria_labelledby: String,
    /// Id of the row's description, when it has one.
    pub aria_describedby: Option<String>,
}

/// JavaScript's whitespace: Unicode white space plus the byte order mark, without the next-line
/// control that Rust's `char::is_whitespace` also includes.
fn is_js_whitespace(character: char) -> bool {
    (character.is_whitespace() && character != '\u{85}') || character == '\u{feff}'
}

/// A usable element id: trimmed, not empty, at most 256 UTF-16 units, and without whitespace,
/// like lumen-core's `normalizeLumenElementId`. Linear and bounded scans only.
fn normalize_element_id(value: Option<&str>) -> Option<String> {
    let value = value?;

    if value.encode_utf16().take(MAX_ID_LENGTH + 1).count() > MAX_ID_LENGTH {
        return None;
    }

    let trimmed = value.trim_matches(is_js_whitespace);

    if trimmed.is_empty() || trimmed.chars().any(is_js_whitespace) {
        return None;
    }

    Some(trimmed.to_string())
}

/// The ids a row derives, like lumen-core's `resolveLumenSettingsRowIds`.
#[derive(Debug, PartialEq, Eq)]
struct SettingsRowIds {
    control: Option<String>,
    label: String,
    description: String,
}

impl SettingsRowIds {
    /// Derives the label and description ids from `control_id` when it is valid, otherwise from
    /// `fallback_prefix`.
    fn resolve(control_id: Option<&str>, fallback_prefix: &str) -> Self {
        let control = normalize_element_id(control_id);
        let prefix = control
            .clone()
            .or_else(|| normalize_element_id(Some(fallback_prefix)))
            .unwrap_or_else(|| FALLBACK_PREFIX.to_string());

        Self {
            control,
            label: format!("{prefix}-label"),
            description: format!("{prefix}-description"),
        }
    }
}

/// Props for [`SettingsRow`].
#[derive(Props, Clone, PartialEq)]
pub struct SettingsRowProps {
    /// Visible label. It becomes the accessible name of the control.
    #[props(into)]
    pub label: String,
    /// Supporting sentence under the label, with the id `{control_id}-description`.
    #[props(into)]
    pub description: Option<String>,
    /// Id of the control. The label points at it with `for`, and the label and description ids
    /// derive from it (`{control_id}-label`, `{control_id}-description`).
    #[props(into)]
    pub control_id: Option<String>,
    /// Id of the row. Without a `control_id`, the derived ids use it as their prefix.
    #[props(into)]
    pub id: Option<String>,
    /// Icon or graphic before the text. Mark decorative icons as hidden.
    pub leading: Option<Element>,
    /// Renders the control with the ids it needs, like lumen-react's function child. It wins over
    /// `children`. Without a `control_id`, the control id is `{id}-control`.
    pub control: Option<Callback<SettingsRowControlProps, Element>>,
    /// Extra classes appended after the Lumen class.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<div>` or global attribute.
    #[props(extends = GlobalAttributes, extends = div)]
    pub attributes: Vec<Attribute>,
    /// The control at the end of the row, when it does not use `control`.
    pub children: Element,
}

/// A label and description on the start side with a control on the end side. It stacks in
/// narrow containers.
#[component]
pub fn SettingsRow(props: SettingsRowProps) -> Element {
    let generated = use_unique_id();
    let prefix = props.id.clone().unwrap_or(generated);
    let ids = SettingsRowIds::resolve(props.control_id.as_deref(), &prefix);
    let description = props
        .description
        .clone()
        .filter(|description| !description.trim().is_empty());
    let (control, control_id) = if let Some(render) = props.control {
        let control_id = ids
            .control
            .clone()
            .unwrap_or_else(|| format!("{prefix}-control"));
        let control = render.call(SettingsRowControlProps {
            id: control_id.clone(),
            aria_labelledby: ids.label.clone(),
            aria_describedby: description.as_ref().map(|_| ids.description.clone()),
        });

        (Some(control), Some(control_id))
    } else {
        let has_children = props.children != VNode::empty();

        (has_children.then_some(props.children), ids.control.clone())
    };
    let class = compose([Some("ui-settings-row"), props.class.as_deref()]);

    rsx! {
        div {
            class,
            "data-slot": "settings-row",
            id: props.id,
            ..props.attributes,
            if let Some(leading) = props.leading {
                div { class: "ui-settings-row__leading", "data-slot": "settings-row-leading", {leading} }
            }
            div { class: "ui-settings-row__content", "data-slot": "settings-row-content",
                if let Some(control_id) = control_id {
                    label {
                        class: "ui-settings-row__label",
                        "data-slot": "settings-row-label",
                        id: ids.label,
                        r#for: control_id,
                        "{props.label}"
                    }
                } else {
                    span {
                        class: "ui-settings-row__label",
                        "data-slot": "settings-row-label",
                        id: ids.label,
                        "{props.label}"
                    }
                }
                if let Some(description) = description {
                    p {
                        class: "ui-settings-row__description",
                        "data-slot": "settings-row-description",
                        id: ids.description,
                        "{description}"
                    }
                }
            }
            if let Some(control) = control {
                div { class: "ui-settings-row__control", "data-slot": "settings-row-control", {control} }
            }
        }
    }
}

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

    #[test]
    fn ids_derive_from_a_valid_control_id() {
        assert_eq!(
            SettingsRowIds::resolve(Some(" theme "), "row"),
            SettingsRowIds {
                control: Some("theme".to_string()),
                label: "theme-label".to_string(),
                description: "theme-description".to_string(),
            }
        );
    }

    #[test]
    fn invalid_control_ids_fall_back_to_the_prefix() {
        for invalid in ["", "   ", "two words", "tab\tid", "bom\u{feff}id"] {
            let ids = SettingsRowIds::resolve(Some(invalid), "row");

            assert_eq!(ids.control, None, "{invalid:?}");
            assert_eq!(ids.label, "row-label");
        }

        assert_eq!(
            SettingsRowIds::resolve(None, "bad prefix").label,
            "ui-settings-row-label"
        );
        assert_eq!(
            normalize_element_id(Some("next\u{85}line")).as_deref(),
            Some("next\u{85}line"),
            "JavaScript does not treat U+0085 as whitespace"
        );
    }

    #[test]
    fn long_ids_are_rejected_in_linear_time() {
        let long = "a".repeat(257);
        let spaced = format!("{} b", "a".repeat(100_000));

        assert_eq!(
            normalize_element_id(Some(&"a".repeat(256))).map(|id| id.len()),
            Some(256)
        );
        assert_eq!(normalize_element_id(Some(&long)), None);
        assert_eq!(normalize_element_id(Some(&spaced)), None);
    }
}