Skip to main content

lumen_dioxus/inputs/
password_field.rs

1//! `PasswordField`: a labelled password input with a show and hide toggle.
2
3use std::rc::Rc;
4
5use dioxus::prelude::*;
6
7use super::input_form::{FormSignals, use_form_signals};
8use crate::class::compose;
9use crate::hooks::use_unique_id;
10use crate::icons::{icon_svg, lucide};
11use crate::overlay::focus_element;
12use crate::{Button, ButtonSize, ButtonVariant, Field, FieldError, Label};
13
14/// Props for [`PasswordField`].
15#[derive(Props, Clone, PartialEq)]
16pub struct PasswordFieldProps {
17    /// Visible label. Defaults to `Password`.
18    #[props(default = "Password".to_string(), into)]
19    pub label: String,
20    /// Help text under the input, linked with `aria-describedby`.
21    #[props(into)]
22    pub hint: Option<String>,
23    /// Validation message. A non-empty message marks the field and input invalid.
24    #[props(into)]
25    pub error: Option<String>,
26    /// Accessible name of the toggle while the password is hidden. Defaults to `Show password`.
27    #[props(default = "Show password".to_string(), into)]
28    pub show_label: String,
29    /// Accessible name of the toggle while the password is visible. Defaults to `Hide password`.
30    #[props(default = "Hide password".to_string(), into)]
31    pub hide_label: String,
32    /// Id of the input. Defaults to `ui-password-` plus a generated id; the hint and error ids
33    /// derive from it (`{id}-hint`, `{id}-error`).
34    #[props(into)]
35    pub id: Option<String>,
36    /// Form field name of the input.
37    #[props(into)]
38    pub name: Option<String>,
39    /// Ids of extra descriptions, listed before the hint and error in `aria-describedby`.
40    #[props(into)]
41    pub aria_describedby: Option<String>,
42    /// Fires on every edit.
43    pub oninput: Option<EventHandler<FormEvent>>,
44    /// Fires when the value is committed.
45    pub onchange: Option<EventHandler<FormEvent>>,
46    /// Extra classes appended to the `ui-field ui-password-field` wrapper.
47    #[props(into)]
48    pub class: Option<String>,
49    /// Any other `<input>` or global attribute, such as `value`, `autocomplete`, or `required`.
50    /// They go on the input, like lumen-react.
51    #[props(extends = GlobalAttributes, extends = input)]
52    pub attributes: Vec<Attribute>,
53}
54
55/// `aria-describedby` for the input: the app's ids, then the hint, then the error, like
56/// lumen-react's `getPasswordFieldDescribedBy`.
57fn password_field_described_by(
58    aria_describedby: Option<&str>,
59    hint_id: Option<&str>,
60    error_id: Option<&str>,
61) -> Option<String> {
62    Some(compose([aria_describedby, hint_id, error_id])).filter(|ids| !ids.is_empty())
63}
64
65/// A labelled password input with an icon toggle that shows or hides the text.
66///
67/// The toggle switches the input between `type="password"` and `type="text"` in Rust, so it works
68/// on every renderer. Inside a [`Form`](crate::Form), the password hides again when the form is
69/// reset or its status becomes `Success`.
70#[component]
71pub fn PasswordField(props: PasswordFieldProps) -> Element {
72    let generated = use_unique_id();
73    let control_id = props
74        .id
75        .clone()
76        .unwrap_or_else(|| format!("ui-password-{generated}"));
77    let hint = props.hint.clone().filter(|hint| !hint.is_empty());
78    let error = props.error.clone().filter(|error| !error.is_empty());
79    let hint_id = hint.as_ref().map(|_| format!("{control_id}-hint"));
80    let error_id = format!("{control_id}-error");
81    let described_by = password_field_described_by(
82        props.aria_describedby.as_deref(),
83        hint_id.as_deref(),
84        error.as_ref().map(|_| error_id.as_str()),
85    );
86
87    // The text stays visible only while the enclosing form has not been reset or succeeded since
88    // the toggle was pressed.
89    let form = use_form_signals().unwrap_or_default();
90    let mut shown_at = use_signal(|| None::<FormSignals>);
91    let visible = *shown_at.read() == Some(form);
92    let mut input = use_signal(|| None::<Rc<MountedData>>);
93    let class = compose([Some("ui-password-field"), props.class.as_deref()]);
94    let invalid = error.is_some();
95    let aria_invalid = invalid.then_some("true");
96    let toggle_label = if visible {
97        props.hide_label
98    } else {
99        props.show_label
100    };
101    let (oninput, onchange) = (props.oninput, props.onchange);
102
103    rsx! {
104        Field {
105            class,
106            control_id: control_id.clone(),
107            described_by: described_by.clone(),
108            invalid,
109            Label { r#for: control_id.clone(), "{props.label}" }
110            div { class: "ui-password-field__control", "data-ui-password-field": "true",
111                input {
112                    aria_describedby: described_by,
113                    aria_invalid,
114                    class: "ui-input",
115                    id: control_id.clone(),
116                    name: props.name,
117                    r#type: if visible { "text" } else { "password" },
118                    onmounted: move |event| input.set(Some(event.data())),
119                    oninput: move |event| {
120                        if let Some(handler) = oninput {
121                            handler.call(event);
122                        }
123                    },
124                    onchange: move |event| {
125                        if let Some(handler) = onchange {
126                            handler.call(event);
127                        }
128                    },
129                    ..props.attributes,
130                }
131                Button {
132                    aria_controls: control_id.clone(),
133                    aria_label: toggle_label,
134                    aria_pressed: if visible { "true" } else { "false" },
135                    "data-ui-password-toggle": "true",
136                    size: ButtonSize::Icon,
137                    variant: ButtonVariant::Ghost,
138                    onclick: move |event: MouseEvent| {
139                        // Keeps focus in the input on Dioxus Native, where a button click would
140                        // otherwise clear it.
141                        event.prevent_default();
142                        shown_at.set(if visible { None } else { Some(form) });
143                        focus_element(input());
144                    },
145                    span {
146                        aria_hidden: "true",
147                        class: "ui-password-field__icon",
148                        "data-ui-password-icon": "show",
149                        {icon_svg(&lucide::EYE, "ui-icon__svg lucide-eye")}
150                    }
151                    span {
152                        aria_hidden: "true",
153                        class: "ui-password-field__icon",
154                        "data-ui-password-icon": "hide",
155                        {icon_svg(&lucide::EYE_OFF, "ui-icon__svg lucide-eye-off")}
156                    }
157                }
158            }
159            if let Some(hint) = hint {
160                p { class: "ui-field__hint", "data-ui-field-hint": "true", id: hint_id, "{hint}" }
161            }
162            FieldError { message: error }
163        }
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::password_field_described_by;
170
171    #[test]
172    fn described_by_lists_app_ids_then_hint_then_error() {
173        assert_eq!(password_field_described_by(None, None, None), None);
174        assert_eq!(
175            password_field_described_by(Some("extra"), Some("pw-hint"), Some("pw-error"))
176                .as_deref(),
177            Some("extra pw-hint pw-error")
178        );
179        assert_eq!(
180            password_field_described_by(None, None, Some("pw-error")).as_deref(),
181            Some("pw-error")
182        );
183    }
184}