| 1 | "use client"; |
| 2 | |
| 3 | import { |
| 4 | evaluatePasswordStrength, |
| 5 | type PasswordStrengthLevel, |
| 6 | } from "@better-auth-ui/core"; |
| 7 | import { useAuth } |
| 8 | |
| 9 | import { cn } |
| 10 | |
| 11 | /** Fixed segment identities, so the bars keep their own React keys. */ |
| 12 | const STRENGTH_SEGMENTS = [ |
| 13 | |
| 14 | type FilledLevel |
| 15 | |
| 16 | const segmentColors: Record |
| 17 | weak: "bg-destructive", |
| 18 | fair: "bg-amber-500", |
| 19 | good: "bg-sky-500", |
| 20 | strong: "bg-emerald-500", |
| 21 | }; |
| 22 | |
| 23 | export type PasswordStrengthMeterProps |
| 24 | /** The password as typed. Renders nothing while it is empty. */ |
| 25 | password: string |
| 26 | className?: string |
| 27 | }; |
| 28 | |
| 29 | /** |
| 30 | * Four-segment strength hint shown while someone picks a new password. |
| 31 | * |
| 32 | * Renders nothing when `emailAndPassword.strengthMeter` is off or the field is empty. The score never gates submission: your server rules stay the authority on what is acceptable. |
| 33 | */ |
| 34 | export function PasswordStrengthMeter({ |
| 35 | password, |
| 36 | className, |
| 37 | }: PasswordStrengthMeterProps) |
| 38 | const { emailAndPassword, |
| 39 | |
| 40 | if (!emailAndPassword?.strengthMeter |
| 41 | |
| 42 | const { score, |
| 43 | minLength: emailAndPassword.minPasswordLength |
| 44 | }); |
| 45 | |
| 46 | if (level === |
| 47 | |
| 48 | const levelLabels: |
| 49 | weak: localization.auth |
| 50 | fair: localization.auth |
| 51 | good: localization.auth |
| 52 | strong: localization.auth |
| 53 | }; |
| 54 | |
| 55 | return ( |
| 56 | <div className={cn |
| 57 | {/* Decorative: the live region below is what gets announced. */ |
| 58 | <div aria-hidden="true |
| 59 | {STRENGTH_SEGMENTS.map(( |
| 60 | <span |
| 61 | key={segment} |
| 62 | className={cn( |
| 63 | "h-1 flex-1 rounded-full bg-muted transition-colors", |
| 64 | segment <= score |
| 65 | )} |
| 66 | /> |
| 67 | ))} |
| 68 | </div> |
| 69 | |
| 70 | <p aria-live="polite |
| 71 | {localization.auth.passwordStrength |
| 72 | <span className="font-medium text-foreground |
| 73 | {levelLabels[level]} |
| 74 | </span> |
| 75 | </p> |
| 76 | </div> |
| 77 | ); |
| 78 | } |