lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
//! `PasswordField`: a labelled password input with a show and hide toggle.

use std::rc::Rc;

use dioxus::prelude::*;

use super::input_form::{FormSignals, use_form_signals};
use crate::class::compose;
use crate::hooks::use_unique_id;
use crate::icons::{icon_svg, lucide};
use crate::overlay::focus_element;
use crate::{Button, ButtonSize, ButtonVariant, Field, FieldError, Label};

/// Props for [`PasswordField`].
#[derive(Props, Clone, PartialEq)]
pub struct PasswordFieldProps {
    /// Visible label. Defaults to `Password`.
    #[props(default = "Password".to_string(), into)]
    pub label: String,
    /// Help text under the input, linked with `aria-describedby`.
    #[props(into)]
    pub hint: Option<String>,
    /// Validation message. A non-empty message marks the field and input invalid.
    #[props(into)]
    pub error: Option<String>,
    /// Accessible name of the toggle while the password is hidden. Defaults to `Show password`.
    #[props(default = "Show password".to_string(), into)]
    pub show_label: String,
    /// Accessible name of the toggle while the password is visible. Defaults to `Hide password`.
    #[props(default = "Hide password".to_string(), into)]
    pub hide_label: String,
    /// Id of the input. Defaults to `ui-password-` plus a generated id; the hint and error ids
    /// derive from it (`{id}-hint`, `{id}-error`).
    #[props(into)]
    pub id: Option<String>,
    /// Form field name of the input.
    #[props(into)]
    pub name: Option<String>,
    /// Ids of extra descriptions, listed before the hint and error in `aria-describedby`.
    #[props(into)]
    pub aria_describedby: Option<String>,
    /// Fires on every edit.
    pub oninput: Option<EventHandler<FormEvent>>,
    /// Fires when the value is committed.
    pub onchange: Option<EventHandler<FormEvent>>,
    /// Extra classes appended to the `ui-field ui-password-field` wrapper.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<input>` or global attribute, such as `value`, `autocomplete`, or `required`.
    /// They go on the input, like lumen-react.
    #[props(extends = GlobalAttributes, extends = input)]
    pub attributes: Vec<Attribute>,
}

/// `aria-describedby` for the input: the app's ids, then the hint, then the error, like
/// lumen-react's `getPasswordFieldDescribedBy`.
fn password_field_described_by(
    aria_describedby: Option<&str>,
    hint_id: Option<&str>,
    error_id: Option<&str>,
) -> Option<String> {
    Some(compose([aria_describedby, hint_id, error_id])).filter(|ids| !ids.is_empty())
}

/// A labelled password input with an icon toggle that shows or hides the text.
///
/// The toggle switches the input between `type="password"` and `type="text"` in Rust, so it works
/// on every renderer. Inside a [`Form`](crate::Form), the password hides again when the form is
/// reset or its status becomes `Success`.
#[component]
pub fn PasswordField(props: PasswordFieldProps) -> Element {
    let generated = use_unique_id();
    let control_id = props
        .id
        .clone()
        .unwrap_or_else(|| format!("ui-password-{generated}"));
    let hint = props.hint.clone().filter(|hint| !hint.is_empty());
    let error = props.error.clone().filter(|error| !error.is_empty());
    let hint_id = hint.as_ref().map(|_| format!("{control_id}-hint"));
    let error_id = format!("{control_id}-error");
    let described_by = password_field_described_by(
        props.aria_describedby.as_deref(),
        hint_id.as_deref(),
        error.as_ref().map(|_| error_id.as_str()),
    );

    // The text stays visible only while the enclosing form has not been reset or succeeded since
    // the toggle was pressed.
    let form = use_form_signals().unwrap_or_default();
    let mut shown_at = use_signal(|| None::<FormSignals>);
    let visible = *shown_at.read() == Some(form);
    let mut input = use_signal(|| None::<Rc<MountedData>>);
    let class = compose([Some("ui-password-field"), props.class.as_deref()]);
    let invalid = error.is_some();
    let aria_invalid = invalid.then_some("true");
    let toggle_label = if visible {
        props.hide_label
    } else {
        props.show_label
    };
    let (oninput, onchange) = (props.oninput, props.onchange);

    rsx! {
        Field {
            class,
            control_id: control_id.clone(),
            described_by: described_by.clone(),
            invalid,
            Label { r#for: control_id.clone(), "{props.label}" }
            div { class: "ui-password-field__control", "data-ui-password-field": "true",
                input {
                    aria_describedby: described_by,
                    aria_invalid,
                    class: "ui-input",
                    id: control_id.clone(),
                    name: props.name,
                    r#type: if visible { "text" } else { "password" },
                    onmounted: move |event| input.set(Some(event.data())),
                    oninput: move |event| {
                        if let Some(handler) = oninput {
                            handler.call(event);
                        }
                    },
                    onchange: move |event| {
                        if let Some(handler) = onchange {
                            handler.call(event);
                        }
                    },
                    ..props.attributes,
                }
                Button {
                    aria_controls: control_id.clone(),
                    aria_label: toggle_label,
                    aria_pressed: if visible { "true" } else { "false" },
                    "data-ui-password-toggle": "true",
                    size: ButtonSize::Icon,
                    variant: ButtonVariant::Ghost,
                    onclick: move |event: MouseEvent| {
                        // Keeps focus in the input on Dioxus Native, where a button click would
                        // otherwise clear it.
                        event.prevent_default();
                        shown_at.set(if visible { None } else { Some(form) });
                        focus_element(input());
                    },
                    span {
                        aria_hidden: "true",
                        class: "ui-password-field__icon",
                        "data-ui-password-icon": "show",
                        {icon_svg(&lucide::EYE, "ui-icon__svg lucide-eye")}
                    }
                    span {
                        aria_hidden: "true",
                        class: "ui-password-field__icon",
                        "data-ui-password-icon": "hide",
                        {icon_svg(&lucide::EYE_OFF, "ui-icon__svg lucide-eye-off")}
                    }
                }
            }
            if let Some(hint) = hint {
                p { class: "ui-field__hint", "data-ui-field-hint": "true", id: hint_id, "{hint}" }
            }
            FieldError { message: error }
        }
    }
}

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

    #[test]
    fn described_by_lists_app_ids_then_hint_then_error() {
        assert_eq!(password_field_described_by(None, None, None), None);
        assert_eq!(
            password_field_described_by(Some("extra"), Some("pw-hint"), Some("pw-error"))
                .as_deref(),
            Some("extra pw-hint pw-error")
        );
        assert_eq!(
            password_field_described_by(None, None, Some("pw-error")).as_deref(),
            Some("pw-error")
        );
    }
}