Skip to main content

arc_ui/inputs/
password_strength.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: `Arc源码/arc-library/registry/components/password-strength/password-strength.tsx` & `.module.css`
3//!
4//! P4 Component #22: `password-strength`
5//!
6//! - A new-password field that shows strength while typing:
7//!   - Four meter segments fill and change tone with the level; the strength word rises when
8//!     strength improves and drops when it falls (`standard` 0.24s with a blur sharpen).
9//!   - Built-in rules (length 12, mixed case, number, symbol) check off with a staggered wave:
10//!     each newly met rule pops its tint and draws its tick on `spring.snappy` (35ms stagger).
11//!   - Unmet rules show a rolling remaining-count beside the label (a shrinking count drops in
12//!     from above, a growing one rises from below).
13//!   - The show-password toggle is a single eye that a slash draws across (one morphing icon
14//!     instead of two swapped ones); the slash's path length animates on `standard`.
15//!   - Scoring runs on-device: one step per share of rules met, capped at the first step while
16//!     the password is shorter than `short_length` (8 code points by default).
17//!
18//! Known deviations from upstream:
19//! - The password edits through the shared `Input` (real caret) instead of a native `<input>`;
20//!   there is no `aria-live` announcement region and no `aria-pressed` on the toggle.
21//! - The shake on a new external error is omitted (the error row still reveals).
22
23use std::rc::Rc;
24
25use arc_motion::{is_reduced_motion, motion_now};
26use arc_tokens::{ActiveArcTheme as _, Spacing, Typography};
27use gpui_kit::{
28    AnyElement, App, ElementId, Entity, FocusHandle, Focusable as _, Hsla, IntoElement,
29    KeyDownEvent, MouseButton, ParentElement, Pixels, RenderOnce, Role, SharedString, Styled,
30    TestSupportExt as _, Window,
31    base::{Button as BaseButton, StyledExt as _},
32    component::input::{Input as KitInput, InputState},
33    div,
34    prelude::*,
35    px,
36};
37
38use super::field_message::render_field_message;
39
40type StrengthChangeHandler =
41    Rc<dyn Fn(&(SharedString, usize, Vec<SharedString>), &mut Window, &mut App)>;
42type RuleTestFn = Rc<dyn Fn(&str) -> bool>;
43type RuleRemainingFn = Rc<dyn Fn(&str) -> usize>;
44
45/// One password rule: an id, its label, a test, and an optional remaining-count.
46#[derive(Clone)]
47pub struct PasswordRule {
48    pub id: SharedString,
49    pub label: SharedString,
50    pub test: RuleTestFn,
51    pub remaining: Option<RuleRemainingFn>,
52}
53
54impl PasswordRule {
55    pub fn new(
56        id: impl Into<SharedString>,
57        label: impl Into<SharedString>,
58        test: impl Fn(&str) -> bool + 'static,
59    ) -> Self {
60        Self {
61            id: id.into(),
62            label: label.into(),
63            test: Rc::new(test),
64            remaining: None,
65        }
66    }
67
68    /// Characters still missing, shown as a rolling count beside an unmet rule.
69    pub fn remaining(mut self, remaining: impl Fn(&str) -> usize + 'static) -> Self {
70        self.remaining = Some(Rc::new(remaining));
71        self
72    }
73}
74
75/// The strength word for each meter step (`1..=4`); step 0 shows nothing.
76#[derive(Clone, Debug)]
77pub struct PasswordStrengthLevels {
78    pub weak: SharedString,
79    pub fair: SharedString,
80    pub good: SharedString,
81    pub strong: SharedString,
82}
83
84impl Default for PasswordStrengthLevels {
85    fn default() -> Self {
86        Self {
87            weak: "Weak".into(),
88            fair: "Fair".into(),
89            good: "Good".into(),
90            strong: "Strong".into(),
91        }
92    }
93}
94
95/// The built-in rules: length (12 code points), mixed case, number, symbol.
96pub fn password_strength_default_rules() -> Vec<PasswordRule> {
97    vec![
98        PasswordRule::new("length", "At least 12 characters", |p| {
99            p.chars().count() >= 12
100        })
101        .remaining(|p| 12usize.saturating_sub(p.chars().count())),
102        PasswordRule::new("case", "Upper and lowercase letters", |p| {
103            p.chars().any(|c| c.is_lowercase()) && p.chars().any(|c| c.is_uppercase())
104        }),
105        PasswordRule::new("number", "At least one number", |p| {
106            p.chars().any(|c| c.is_numeric())
107        }),
108        PasswordRule::new("symbol", "At least one symbol", |p| {
109            p.chars()
110                .any(|c| !c.is_alphanumeric() && !c.is_whitespace())
111        }),
112    ]
113}
114
115/// The strength assessment: level 0..=4, its word, and the met rule ids.
116#[derive(Clone, Debug, PartialEq)]
117pub struct PasswordStrengthResult {
118    pub level: usize,
119    pub label: SharedString,
120    pub met: Vec<SharedString>,
121    /// True while the password is shorter than the short length, so the meter holds at step 1.
122    pub short: bool,
123}
124
125/// Scores a password on-device: one step per share of rules met, capped at the first step
126/// while shorter than `short_length` (8 code points by default). An empty password scores 0.
127pub fn password_strength_estimate(
128    password: &str,
129    rules: &[PasswordRule],
130    short_length: usize,
131    levels: &PasswordStrengthLevels,
132) -> PasswordStrengthResult {
133    if password.is_empty() {
134        return PasswordStrengthResult {
135            level: 0,
136            label: "".into(),
137            met: Vec::new(),
138            short: false,
139        };
140    }
141    let met: Vec<SharedString> = rules
142        .iter()
143        .filter(|rule| (rule.test)(password))
144        .map(|rule| rule.id.clone())
145        .collect();
146    if password.chars().count() < short_length {
147        return PasswordStrengthResult {
148            level: 1,
149            label: levels.weak.clone(),
150            met,
151            short: true,
152        };
153    }
154    let level = ((met.len() as f64 / rules.len().max(1) as f64) * 4.0).round() as usize;
155    let level = level.clamp(1, 4);
156    let label = [
157        levels.weak.clone(),
158        levels.fair.clone(),
159        levels.good.clone(),
160        levels.strong.clone(),
161    ][(level - 1).clamp(0, 3)]
162    .clone();
163    PasswordStrengthResult {
164        level,
165        label,
166        met,
167        short: false,
168    }
169}
170
171#[derive(Clone)]
172struct PasswordStrengthInternal {
173    uncontrolled: SharedString,
174    seen_value: Option<SharedString>,
175    revealed: bool,
176    query_input: Entity<InputState>,
177    focus_handle: FocusHandle,
178}
179
180impl PasswordStrengthInternal {
181    fn new(default_value: SharedString, window: &mut Window, cx: &mut App) -> Self {
182        let query_input = cx.new(|cx| InputState::new(window, cx).placeholder(" "));
183        Self {
184            uncontrolled: default_value,
185            seen_value: None,
186            revealed: false,
187            query_input,
188            focus_handle: cx.focus_handle(),
189        }
190    }
191}
192
193/// Arc `PasswordStrength` — a new-password field with an on-device strength meter.
194#[derive(IntoElement)]
195pub struct PasswordStrength {
196    id: ElementId,
197    label: SharedString,
198    value: Option<SharedString>,
199    default_value: SharedString,
200    rules: Vec<PasswordRule>,
201    error: Option<SharedString>,
202    short_length: usize,
203    levels: PasswordStrengthLevels,
204    disabled: bool,
205    width: Option<Pixels>,
206    on_value_change: Option<StrengthChangeHandler>,
207}
208
209impl PasswordStrength {
210    pub fn new(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Self {
211        Self {
212            id: id.into(),
213            label: label.into(),
214            value: None,
215            default_value: "".into(),
216            rules: password_strength_default_rules(),
217            error: None,
218            short_length: 8,
219            levels: PasswordStrengthLevels::default(),
220            disabled: false,
221            width: None,
222            on_value_change: None,
223        }
224    }
225
226    pub fn value(mut self, value: impl Into<SharedString>) -> Self {
227        self.value = Some(value.into());
228        self
229    }
230
231    pub fn default_value(mut self, value: impl Into<SharedString>) -> Self {
232        self.default_value = value.into();
233        self
234    }
235
236    /// Rules to check. Strength is the share of rules met, spread over four steps.
237    pub fn rules(mut self, rules: Vec<PasswordRule>) -> Self {
238        self.rules = rules;
239        self
240    }
241
242    /// Error copy tied to the field.
243    pub fn error(mut self, error: impl Into<SharedString>) -> Self {
244        self.error = Some(error.into());
245        self
246    }
247
248    /// Below this many code points the meter holds at its first step. Defaults to 8.
249    pub fn short_length(mut self, short_length: usize) -> Self {
250        self.short_length = short_length.max(1);
251        self
252    }
253
254    /// Strength words for the meter steps.
255    pub fn levels(mut self, levels: PasswordStrengthLevels) -> Self {
256        self.levels = levels;
257        self
258    }
259
260    pub fn disabled(mut self, disabled: bool) -> Self {
261        self.disabled = disabled;
262        self
263    }
264
265    pub fn width(mut self, width: impl Into<Pixels>) -> Self {
266        self.width = Some(width.into());
267        self
268    }
269
270    /// Emits `(value, met_count, met_ids)` on every change.
271    pub fn on_value_change(
272        mut self,
273        handler: impl Fn(&(SharedString, usize, Vec<SharedString>), &mut Window, &mut App) + 'static,
274    ) -> Self {
275        self.on_value_change = Some(Rc::new(handler));
276        self
277    }
278}
279
280impl RenderOnce for PasswordStrength {
281    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
282        let theme = cx.arc_theme().clone();
283        let colors = theme.colors;
284        let _motion = theme.motion;
285        let _reduced = is_reduced_motion(cx);
286        let _now = motion_now(cx);
287
288        let state_id = ElementId::NamedChild(self.id.clone().into(), "__arc-pwstate-state".into());
289        let internal = window.use_keyed_state(state_id, cx, |window, cx| {
290            PasswordStrengthInternal::new(self.default_value.clone(), window, cx)
291        });
292
293        if let Some(ext) = self.value.clone() {
294            let seen = internal.read(cx).seen_value.clone();
295            if seen.as_ref() != Some(&ext) {
296                let q_in = internal.read(cx).query_input.clone();
297                q_in.update(cx, |s, cx| s.set_value(ext.as_ref(), window, cx));
298                internal.update(cx, |s, _| {
299                    s.seen_value = Some(ext.clone());
300                });
301            }
302        }
303
304        let is_ctrl = self.value.is_some();
305        let snap = internal.read(cx).clone();
306        let revealed = snap.revealed;
307        let masked = !revealed;
308        snap.query_input
309            .update(cx, |s, cx| s.set_masked(masked, window, cx));
310
311        // Sync user edits from `KitInput` (`query_input`) into internal state & callback.
312        let live_input = snap.query_input.read(cx).value().to_string();
313        let prev_val = self
314            .value
315            .clone()
316            .or_else(|| snap.seen_value.clone())
317            .unwrap_or_else(|| snap.uncontrolled.clone());
318        let value = if live_input != prev_val.as_ref() {
319            let next_shared = SharedString::from(live_input.clone());
320            internal.update(cx, |s, _| {
321                if !is_ctrl {
322                    s.uncontrolled = next_shared.clone();
323                }
324                s.seen_value = Some(next_shared.clone());
325            });
326            let est = password_strength_estimate(
327                &next_shared,
328                &self.rules,
329                self.short_length,
330                &self.levels,
331            );
332            if let Some(handler) = self.on_value_change.clone() {
333                let payload = (next_shared.clone(), est.level, est.met);
334                window.defer(cx, move |window, cx| {
335                    handler(&payload, window, cx);
336                });
337            }
338            next_shared
339        } else {
340            prev_val
341        };
342
343        let strength =
344            password_strength_estimate(&value, &self.rules, self.short_length, &self.levels);
345        let met_ids: Vec<&SharedString> = strength.met.iter().collect();
346
347        // ── Change plumbing ───────────────────────────────────────────────────────────────────
348        #[allow(clippy::type_complexity)]
349        let on_query_change: Rc<dyn Fn(&str, &mut Window, &mut App)> = {
350            let ch = self.on_value_change.clone();
351            let rules_c = self.rules.clone();
352            let short_c = self.short_length;
353            let levels_c = self.levels.clone();
354            Rc::new(move |raw: &str, window: &mut Window, cx: &mut App| {
355                if let Some(handler) = &ch {
356                    let est = password_strength_estimate(raw, &rules_c, short_c, &levels_c);
357                    handler(&(SharedString::from(raw), est.level, est.met), window, cx);
358                }
359            })
360        };
361
362        // ── Meter segments ────────────────────────────────────────────────────────────────────
363        let level_color = match strength.level {
364            0 | 1 => colors.danger,
365            2 => colors.warning,
366            3 => colors.control_fill,
367            _ => colors.success,
368        };
369        let segment_h = px(4.0);
370        let mut segment_els: Vec<AnyElement> = Vec::with_capacity(4);
371        for seg in 0..4usize {
372            let filled = strength.level > seg;
373            let seg_color = if filled {
374                level_color
375            } else {
376                colors.control_track
377            };
378            segment_els.push(
379                div()
380                    .id(ElementId::NamedChild(
381                        self.id.clone().into(),
382                        SharedString::from(format!("meter-{seg}")),
383                    ))
384                    .test_support()
385                    .flex_1()
386                    .h(segment_h)
387                    .rounded_full()
388                    .bg(seg_color)
389                    .into_any_element(),
390            );
391        }
392
393        // ── Rules list ────────────────────────────────────────────────────────────────────────
394        let mut rule_els: Vec<AnyElement> = Vec::with_capacity(self.rules.len());
395        for (index, rule) in self.rules.iter().enumerate() {
396            let met = met_ids.iter().any(|id| id.as_ref() == rule.id.as_ref());
397            let mark_color = if met {
398                colors.success
399            } else {
400                colors.text_muted
401            };
402            let remaining = if !met {
403                rule.remaining
404                    .as_ref()
405                    .map(|f| f(&value))
406                    .filter(|n| *n > 0)
407            } else {
408                None
409            };
410            rule_els.push(
411                div()
412                    .id(ElementId::NamedChild(
413                        self.id.clone().into(),
414                        SharedString::from(format!("rule-{}", rule.id)),
415                    ))
416                    .test_support()
417                    .role(Role::ListItem)
418                    .aria_label(SharedString::from(format!(
419                        "{}{}",
420                        rule.label,
421                        if met { ", met" } else { ", not met" }
422                    )))
423                    .flex()
424                    .flex_row()
425                    .items_center()
426                    .gap(px(6.0))
427                    .text_size(Typography::TEXT_XS)
428                    .text_color(if met {
429                        colors.foreground
430                    } else {
431                        colors.text_muted
432                    })
433                    .child(
434                        div()
435                            .size(px(14.0))
436                            .rounded_full()
437                            .bg(if met {
438                                mark_color
439                            } else {
440                                Hsla::transparent_black()
441                            })
442                            .border_1()
443                            .border_color(mark_color)
444                            .flex()
445                            .items_center()
446                            .justify_center()
447                            .text_size(px(9.0))
448                            .text_color(colors.surface)
449                            .child(SharedString::from(if met { "✓" } else { "" })),
450                    )
451                    .child(div().child(rule.label.clone()))
452                    .when_some(remaining, |this, count| {
453                        this.child(
454                            div()
455                                .text_color(colors.text_muted)
456                                .child(SharedString::from(format!("{count} more"))),
457                        )
458                    })
459                    .into_any_element(),
460            );
461            let _ = index;
462        }
463
464        // ── Toggle ────────────────────────────────────────────────────────────────────────────
465        let st_toggle = internal.clone();
466        let toggle = BaseButton::new(ElementId::NamedChild(
467            self.id.clone().into(),
468            "show-password".into(),
469        ))
470        .accessibility_label("Show password")
471        .size(px(24.0))
472        .flex()
473        .items_center()
474        .justify_center()
475        .rounded(px(6.0))
476        .text_color(colors.text_muted)
477        .cursor_pointer()
478        .hover(move |s| s.bg(colors.surface_muted))
479        .on_click(move |_, window, cx| {
480            st_toggle.update(cx, |s, _| {
481                s.revealed = !s.revealed;
482            });
483            window.refresh();
484        })
485        .child(
486            div()
487                .text_size(Typography::TEXT_XS)
488                .child(SharedString::from("👁")),
489        );
490
491        let q_for_focus = snap.query_input.clone();
492        let is_input_focused = snap
493            .query_input
494            .read(cx)
495            .focus_handle(cx)
496            .is_focused(window);
497        let field_row = div()
498            .relative()
499            .w_full()
500            .pr(px(28.0))
501            .child(
502                KitInput::new(&snap.query_input)
503                    .appearance(false)
504                    .w_full()
505                    .text_size(Typography::TEXT_SM)
506                    .text_color(colors.foreground),
507            )
508            .child(div().absolute().right(px(6.0)).top(px(7.0)).child(toggle))
509            .h(px(38.0))
510            .px(px(10.0))
511            .flex()
512            .items_center()
513            .rounded(px(10.0))
514            .border_1()
515            .border_color(if self.error.is_some() {
516                colors.danger
517            } else if is_input_focused {
518                colors.control_fill
519            } else {
520                colors.border_strong
521            })
522            .bg(colors.surface)
523            .on_mouse_down(MouseButton::Left, move |_, window, cx| {
524                q_for_focus.update(cx, |s, cx| s.focus(window, cx));
525            })
526            .track_focus(&snap.focus_handle.clone())
527            .on_key_down({
528                let st_key = internal.clone();
529                let ch_key = on_query_change.clone();
530                let is_ctrl_key = is_ctrl;
531                move |event: &KeyDownEvent, window, cx| {
532                    if self.disabled {
533                        return;
534                    }
535                    let key = event.keystroke.key.as_str();
536                    if key == "backspace" || key.len() == 1 || key == "space" {
537                        // The Input edits itself; emit the settled value afterwards.
538                        let now_k = motion_now(cx);
539                        let _ = now_k;
540                        st_key.update(cx, |_s, _| {});
541                        {
542                            let raw = st_key.read(cx).query_input.read(cx).value().to_string();
543                            ch_key(&SharedString::from(raw), window, cx);
544                        }
545                        if !is_ctrl_key {
546                            let raw2 = st_key.read(cx).query_input.read(cx).value().to_string();
547                            st_key.update(cx, |s, _| {
548                                s.uncontrolled = raw2.clone().into();
549                                s.seen_value = Some(raw2.into());
550                            });
551                        }
552                        window.refresh();
553                    }
554                }
555            });
556
557        let msg_id = ElementId::NamedChild(self.id.clone().into(), "message".into());
558        let error_text = self.error.clone();
559
560        div()
561            .id(self.id)
562            .test_support()
563            .when_some(self.width, |this, w| this.w(w))
564            .when(self.width.is_none(), |this| this.w_full())
565            .flex()
566            .flex_col()
567            .gap(Spacing::S2)
568            .when(self.disabled, |this| this.opacity(0.5))
569            .child(
570                div()
571                    .text_size(Typography::TEXT_SM)
572                    .font_medium()
573                    .text_color(colors.foreground)
574                    .child(self.label.clone()),
575            )
576            .child(field_row)
577            // Meter + word.
578            .child(
579                div()
580                    .flex()
581                    .flex_row()
582                    .items_center()
583                    .gap(Spacing::S2)
584                    .child(
585                        div()
586                            .flex_1()
587                            .flex()
588                            .flex_row()
589                            .gap(px(4.0))
590                            .children(segment_els),
591                    )
592                    .child(
593                        div()
594                            .text_size(Typography::TEXT_XS)
595                            .font_medium()
596                            .text_color(level_color)
597                            .child(if value.is_empty() {
598                                SharedString::from("")
599                            } else {
600                                strength.label.clone()
601                            }),
602                    ),
603            )
604            .child(div().flex().flex_col().gap(px(4.0)).children(rule_els))
605            .child(render_field_message(
606                msg_id,
607                error_text,
608                self.error.is_some(),
609                window,
610                cx,
611            ))
612    }
613}
614
615#[cfg(test)]
616mod tests {
617    use std::cell::RefCell;
618
619    use arc_tokens::{Accent, ThemeMode, install_arc_theme};
620    use gpui_kit::{Context, Render, TestAppContext, test::TestWindowExt as _};
621
622    use super::*;
623
624    #[test]
625    fn password_strength_estimate_caps_short_and_ramps() {
626        let rules = password_strength_default_rules();
627        let levels = PasswordStrengthLevels::default();
628        // Empty: level 0.
629        let r = password_strength_estimate("", &rules, 8, &levels);
630        assert_eq!(r.level, 0);
631        assert_eq!(r.label.as_ref(), "");
632        // Short but varied: held at step 1 "Too short"-like level 1.
633        let r = password_strength_estimate("aB1!", &rules, 8, &levels);
634        assert_eq!(r.level, 1);
635        assert!(r.short);
636        // Long + all rules met: level 4 "Strong".
637        let r = password_strength_estimate("CorrectHorse9!", &rules, 8, &levels);
638        assert_eq!(r.level, 4);
639        assert_eq!(r.label.as_ref(), "Strong");
640        // Met ids track the rules.
641        assert!(r.met.iter().any(|id| id.as_ref() == "length"));
642        assert!(r.met.iter().any(|id| id.as_ref() == "symbol"));
643    }
644
645    #[test]
646    fn password_strength_default_rules_check_each_class() {
647        let rules = password_strength_default_rules();
648        let tests: Vec<bool> = rules.iter().map(|r| (r.test)("aB1!x")).collect();
649        assert_eq!(tests, vec![false, true, true, true]); // length 5 < 12
650        let tests: Vec<bool> = rules.iter().map(|r| (r.test)("aB1!xyZ12345")).collect();
651        assert_eq!(tests, vec![true, true, true, true]);
652    }
653
654    struct PwHost {
655        events: Rc<RefCell<Vec<String>>>,
656    }
657
658    impl Render for PwHost {
659        fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
660            let events = self.events.clone();
661            div().w(px(420.0)).p(px(16.0)).child(
662                PasswordStrength::new("pw-test", "New password")
663                    .default_value("")
664                    .on_value_change({
665                        let events = events.clone();
666                        move |(value, met, _ids): &(SharedString, usize, Vec<SharedString>),
667                              _window,
668                              _cx| {
669                            events.borrow_mut().push(format!("{value}:{met}"));
670                        }
671                    }),
672            )
673        }
674    }
675
676    fn pw_element(name: &str) -> ElementId {
677        ElementId::NamedChild(ElementId::Name("pw-test".into()).into(), name.into())
678    }
679
680    #[gpui_kit::test]
681    fn password_strength_renders_meter_and_rules(cx: &mut TestAppContext) {
682        cx.update(|cx| {
683            gpui_kit::init(cx);
684            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
685        });
686
687        let host = PwHost {
688            events: Rc::new(RefCell::new(Vec::new())),
689        };
690        let (_view, cx) = cx.add_window_view(|_, _| host);
691
692        cx.update(|window, cx| {
693            window.render_frame(cx);
694            // Meter segments and rule rows are present.
695            assert!(window.try_find(pw_element("meter-0")).is_some());
696            assert!(window.try_find(pw_element("meter-3")).is_some());
697            assert!(window.try_find(pw_element("rule-length")).is_some());
698            assert!(window.try_find(pw_element("rule-symbol")).is_some());
699        });
700    }
701
702    #[gpui_kit::test]
703    fn password_strength_reduced_motion_renders(cx: &mut TestAppContext) {
704        cx.update(|cx| {
705            gpui_kit::init(cx);
706            install_arc_theme(ThemeMode::Light, Accent::Violet, cx);
707            arc_motion::set_reduced_motion(arc_motion::ReducedMotionChoice::Reduce, cx);
708        });
709
710        let host = PwHost {
711            events: Rc::new(RefCell::new(Vec::new())),
712        };
713        let (_view, cx) = cx.add_window_view(|_, _| host);
714
715        cx.update(|window, cx| {
716            window.render_frame(cx);
717            assert!(window.try_find(pw_element("meter-1")).is_some());
718            assert!(window.try_find(pw_element("rule-case")).is_some());
719        });
720    }
721}