Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 113 additions & 0 deletions apps/docs/content/1.component/password-strength.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
---
title: Password Strength
description: A password field with a four-bar meter that fills as the password gets stronger and a checklist that ticks off each rule.
icon: key-round
---

A password field with a **four-bar strength meter** under it. As you type,
the bars **fill one after another** from the left and shift from red to teal.
The **strength word rolls in** beside the label: Weak, Fair, Good or Strong.
Below it, each requirement **draws a check** the moment it is met and erases
it when it is not. The eye button **draws a slash across itself** when the
password is shown, and **blinks** as it toggles. Driven by GSAP.

::component-preview{name="password-strength"}
::

## Installation

::tabs
:::tabs-item{label="CLI" icon="i-lucide-terminal"}

::install-tabs{item="password-strength"}
::

:::
:::tabs-item{label="Manual" icon="i-lucide-clipboard"}

::component-source{name="password-strength"}
::

:::
::

## Usage

::tabs
:::tabs-item{label="React" icon="i-lucide-atom"}

```tsx [app/page.tsx]
import PasswordStrength from '@/components/tweenui/password-strength';

export default function Page() {
return (
<form>
<PasswordStrength />
</form>
);
}
```

:::
::

Pass your own rules to change the checklist. The meter always has four bars,
so the share of rules met is scaled to them.

```tsx
import PasswordStrength, { defaultRules } from '@/components/tweenui/password-strength';

<PasswordStrength
rules={[...defaultRules, { label: 'No spaces', test: (value) => !/\s/.test(value) }]}
/>;
```

## How it moves

- **Bars.** Each bar scales in from the left on a 450ms `power3.out` ease.
Bars that change are staggered 60ms apart, left to right when the score
rises and right to left when it falls. Bars already filled change colour
in place.
- **Word.** When the level changes the word slides in from below as it rises
and from above as it falls, over 350ms.
- **Checks.** The circle fills with the accent and the check draws through
`strokeDashoffset`, 100ms behind the fill. Losing a rule erases it faster.
- **Eye.** The eye blinks shut and open in 300ms while its slash draws in
250ms.

## Props

| Prop | Type | Default | Description |
| --------------- | ---------------------- | --------------------- | --------------------------------------------------- |
| `label` | `string` | `"Password"` | Visible label and accessible name. |
| `placeholder` | `string` | `"Choose a password"` | Placeholder text. |
| `name` | `string` | `"password"` | Form field name. |
| `autoComplete` | `string` | `"new-password"` | Lets password managers suggest a password. |
| `rules` | `PasswordRule[]` | `defaultRules` | Each rule is `{ label, test(value) }`. |
| `value` | `string` | — | Controlled value. Pair it with `onValueChange`. |
| `defaultValue` | `string` | `""` | Starting value when uncontrolled. |
| `onValueChange` | `(value, met) => void` | — | Called on every change with the count of met rules. |
| `className` | `string` | — | Extra classes for the root. |

The checks use `--password-accent` with the tick drawn in
`--password-on-accent`. Override them with a class, e.g.
`[--password-accent:#e11d48]`. Text, borders and the empty bars take
`currentColor`.

## Accessibility

::note
Under `prefers-reduced-motion: reduce` the bars, checks, word and eye change
instantly.
::

The input is a real `<input>` with a `<label>`, described by the strength line
and the rule list. The strength line is an `aria-live="polite"` region, so
screen readers announce "Strength: Good" as it changes. Each rule ends with a
hidden "(met)" or "(not met)", and strength is always given in words, never
by colour alone. A hidden password shows asterisks instead of dots. The browser still draws
the mask itself: a 356-byte inline font, limited by `unicode-range` to the
two mask characters (`•` and `●`), turns each dot into an asterisk. So
selection, the caret, scrolling, password managers and screen readers all
behave exactly like a native password field. The eye is a real button labelled "Show password" or "Hide
password" with `aria-pressed`.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file not shown.
22 changes: 22 additions & 0 deletions apps/docs/public/r/password-strength-demo.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "password-strength-demo",
"type": "registry:example",
"title": "Password Strength Demo",
"description": "Usage examples for Password Strength.",
"registryDependencies": [
"https://tween-ui.staticmania.com/r/password-strength.json"
],
"files": [
{
"path": "examples/password-strength-demo.tsx",
"type": "registry:example",
"content": "import PasswordStrength from '@/components/tweenui/password-strength';\n\nexport default function Page() {\n return (\n <form>\n <PasswordStrength />\n </form>\n );\n}"
},
{
"path": "examples/password-strength-demo-2.tsx",
"type": "registry:example",
"content": "import PasswordStrength, { defaultRules } from '@/components/tweenui/password-strength';\n\n<PasswordStrength\n rules={[...defaultRules, { label: 'No spaces', test: (value) => !/\\s/.test(value) }]}\n/>;"
}
]
}
24 changes: 24 additions & 0 deletions apps/docs/public/r/password-strength.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
"name": "password-strength",
"type": "registry:ui",
"title": "Password Strength",
"description": "A password field with a four-bar strength meter. The bars fill one after another and shift from red to teal as the password gets stronger, the strength word rolls in, and each requirement draws a check when it is met. The eye blinks and draws a slash across itself to show or hide the password.",
"dependencies": [
"gsap",
"@gsap/react"
],
"registryDependencies": [],
"cssVars": {
"theme": {}
},
"files": [
{
"path": "components/tweenui/password-strength.tsx",
"type": "registry:component",
"target": "components/tweenui/password-strength.tsx",
"content": "'use client';\n\nimport { useId, useRef, useState, type ComponentPropsWithoutRef, type RefObject } from 'react';\nimport { useGSAP } from '@gsap/react';\nimport gsap from 'gsap';\nimport { cn } from '@/lib/utils';\n\ngsap.registerPlugin(useGSAP);\n\nexport interface PasswordRule {\n label: string;\n test: (value: string) => boolean;\n}\n\nexport const defaultRules: readonly PasswordRule[] = [\n { label: 'At least 10 characters', test: (value) => value.length >= 10 },\n {\n label: 'Upper and lower case letters',\n test: (value) => /[a-z]/.test(value) && /[A-Z]/.test(value),\n },\n { label: 'At least one number', test: (value) => /\\d/.test(value) },\n { label: 'At least one symbol', test: (value) => /[^A-Za-z0-9]/.test(value) },\n];\n\nconst LEVELS = [\n { word: 'Weak', color: '#e5484d' },\n { word: 'Fair', color: '#f5a524' },\n { word: 'Good', color: '#8bc34a' },\n { word: 'Strong', color: '#14b8a6' },\n] as const;\n\nconst BARS = LEVELS.length;\nconst MASK_FONT = 'tween-password-mask';\n\nconst MASK_FONT_FACE = `@font-face{font-family:${MASK_FONT};src:url(data:font/woff2;base64,d09GMgABAAAAAAFkAAoAAAAAArgAAAEdAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAABmAAPAo4UAE2AiQDBgsGAAQgBYEEByYbFQIAngfZuXAl09NfFYuG5CSC5+9HP+e+u50UyUkJUmmRgm27aEsLsh79C6TC3NYwWgzVmEU1ytDDoCg4nqUv4Wv/nIGBrDp3sx3v/iaDxMNo7FHXLpA4AAgwCiwOJA0ww3SH6mliRErkr1cU6TpWIoMcc11oekhXT/9t+r8UKr8AdIUJBZotzM+GUFpDmtL+/0e6z893w4JInA9UowWQAUXOedcWVRu5JYo75ds9+o9eLmxefbR56fsIAsHWa1LdxNfyKL7A56HhZV179TSdQiGBYEt9jV9xI8CiehOBpFoBEgAAsnEBQhMCJGWaFCJXCAM680lSa2ZFgX3wnWZR5oOpX6BIAWzeAiaEOq7Om8XEFMDwWNhlhNiTawA=) format('woff2');unicode-range:U+2022,U+25CF;font-display:block}`;\n\nconst prefersReducedMotion = () =>\n typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;\n\nconst scoreOf = (value: string, met: number, total: number) =>\n value ? Math.max(1, Math.round((met / (total || 1)) * BARS)) : 0;\n\nconst EyeIcon = ({ slashRef }: { slashRef: RefObject<SVGPathElement | null> }) => (\n <svg\n viewBox=\"0 0 24 24\"\n className=\"size-4\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n aria-hidden=\"true\"\n >\n <path d=\"M2 12s3.6-7 10-7 10 7 10 7-3.6 7-10 7S2 12 2 12Z\" />\n <circle cx=\"12\" cy=\"12\" r=\"3\" />\n <path ref={slashRef} d=\"M4 4l16 16\" pathLength={1} strokeDasharray=\"1\" strokeDashoffset=\"1\" />\n </svg>\n);\n\nexport interface PasswordStrengthProps extends Omit<\n ComponentPropsWithoutRef<'div'>,\n 'defaultValue' | 'onChange'\n> {\n label?: string;\n placeholder?: string;\n name?: string;\n autoComplete?: string;\n rules?: readonly PasswordRule[];\n value?: string;\n defaultValue?: string;\n onValueChange?: (value: string, met: number) => void;\n}\n\nconst PasswordStrength = ({\n label = 'Password',\n placeholder = 'Choose a password',\n name = 'password',\n autoComplete = 'new-password',\n rules = defaultRules,\n value: controlledValue,\n defaultValue = '',\n onValueChange,\n className,\n ...props\n}: PasswordStrengthProps) => {\n const id = useId();\n const inputId = `${id}-input`;\n const strengthId = `${id}-strength`;\n const rulesId = `${id}-rules`;\n\n const rootRef = useRef<HTMLDivElement>(null);\n const slashRef = useRef<SVGPathElement>(null);\n const wordRef = useRef<HTMLSpanElement>(null);\n const fillRefs = useRef<(HTMLSpanElement | null)[]>([]);\n const discRefs = useRef<(HTMLSpanElement | null)[]>([]);\n const checkRefs = useRef<(SVGPathElement | null)[]>([]);\n const eyeRef = useRef<HTMLSpanElement>(null);\n const previousScore = useRef(0);\n const settled = useRef(false);\n\n const [innerValue, setInnerValue] = useState(defaultValue);\n const [visible, setVisible] = useState(false);\n const [inheritedFont, setInheritedFont] = useState<string>();\n\n const value = controlledValue ?? innerValue;\n const results = rules.map((rule) => rule.test(value));\n const met = results.filter(Boolean).length;\n const score = scoreOf(value, met, rules.length);\n const level = score > 0 ? LEVELS[score - 1] : undefined;\n const metKey = results.map(Number).join('');\n\n useGSAP(\n () => {\n const instant = !settled.current || prefersReducedMotion();\n const from = previousScore.current;\n const rising = score >= from;\n const low = Math.min(from, score);\n const high = Math.max(from, score);\n\n fillRefs.current.forEach((fill, index) => {\n if (!fill) return;\n const changed = index >= low && index < high;\n const order = rising ? index - low : high - 1 - index;\n gsap.to(fill, {\n scaleX: index < score ? 1 : 0,\n duration: instant ? 0 : 0.45,\n delay: instant || !changed ? 0 : order * 0.06,\n ease: 'power3.out',\n overwrite: 'auto',\n });\n });\n\n if (!instant && level && score !== from) {\n gsap.fromTo(\n wordRef.current,\n { yPercent: rising ? 60 : -60, opacity: 0 },\n { yPercent: 0, opacity: 1, duration: 0.35, ease: 'power3.out', overwrite: true }\n );\n }\n\n previousScore.current = score;\n },\n { scope: rootRef, dependencies: [score] }\n );\n\n useGSAP(\n () => {\n const instant = !settled.current || prefersReducedMotion();\n results.forEach((ok, index) => {\n const disc = discRefs.current[index];\n const check = checkRefs.current[index];\n if (!disc || !check) return;\n gsap.to(disc, {\n scale: ok ? 1 : 0,\n duration: instant ? 0 : 0.3,\n ease: 'power3.out',\n overwrite: 'auto',\n });\n gsap.to(check, {\n attr: { 'stroke-dashoffset': ok ? 0 : 1 },\n duration: instant ? 0 : ok ? 0.3 : 0.15,\n delay: instant || !ok ? 0 : 0.1,\n ease: 'power2.out',\n overwrite: 'auto',\n });\n });\n settled.current = true;\n },\n { scope: rootRef, dependencies: [metKey] }\n );\n\n useGSAP(\n () => {\n gsap.to(slashRef.current, {\n attr: { 'stroke-dashoffset': visible ? 0 : 1 },\n duration: prefersReducedMotion() ? 0 : 0.25,\n ease: 'power2.out',\n overwrite: 'auto',\n });\n },\n { scope: rootRef, dependencies: [visible] }\n );\n\n useGSAP(\n () => {\n if (rootRef.current) setInheritedFont(getComputedStyle(rootRef.current).fontFamily);\n },\n { scope: rootRef }\n );\n\n const toggleVisible = () => {\n const next = !visible;\n setVisible(next);\n if (prefersReducedMotion()) return;\n gsap\n .timeline()\n .to(eyeRef.current, { scaleY: 0.1, duration: 0.1, ease: 'power2.in' })\n .to(eyeRef.current, { scaleY: 1, duration: 0.2, ease: 'power2.out' });\n };\n\n const handleChange = (next: string) => {\n if (controlledValue === undefined) setInnerValue(next);\n onValueChange?.(next, rules.filter((rule) => rule.test(next)).length);\n };\n\n return (\n <div\n ref={rootRef}\n data-password-strength\n className={cn(\n 'w-full max-w-sm [--password-accent:#045f64] [--password-on-accent:#ffffff] dark:[--password-accent:#c6f56f] dark:[--password-on-accent:#12161f]',\n className\n )}\n {...props}\n >\n <style href={MASK_FONT} precedence=\"default\">\n {MASK_FONT_FACE}\n </style>\n <label htmlFor={inputId} className=\"block text-sm font-medium\">\n {label}\n </label>\n\n <div className=\"relative mt-2\">\n <input\n id={inputId}\n name={name}\n type={visible ? 'text' : 'password'}\n value={value}\n placeholder={placeholder}\n autoComplete={autoComplete}\n spellCheck={false}\n aria-describedby={`${strengthId} ${rulesId}`}\n onChange={(event) => handleChange(event.target.value)}\n style={{ fontFamily: inheritedFont ? `${MASK_FONT}, ${inheritedFont}` : MASK_FONT }}\n className=\"w-full rounded-xl border border-current/15 bg-transparent py-3 pr-12 pl-4 text-sm transition-[border-color] duration-200 placeholder:text-current/40 focus:border-(--password-accent) focus:outline-none motion-reduce:transition-none\"\n />\n <button\n type=\"button\"\n aria-label={visible ? 'Hide password' : 'Show password'}\n aria-pressed={visible}\n aria-controls={inputId}\n onClick={toggleVisible}\n className=\"absolute top-1/2 right-2 grid size-8 -translate-y-1/2 cursor-pointer place-items-center rounded-lg opacity-60 transition-opacity duration-200 hover:opacity-100 focus-visible:opacity-100 focus-visible:outline-2 focus-visible:outline-current\"\n >\n <span ref={eyeRef} className=\"flex\">\n <EyeIcon slashRef={slashRef} />\n </span>\n </button>\n </div>\n\n <div aria-hidden=\"true\" className=\"mt-3 grid grid-cols-4 gap-1.5\">\n {LEVELS.map(({ word }, index) => (\n <span key={word} className=\"h-1.5 overflow-hidden rounded-full bg-current/10\">\n <span\n ref={(node) => {\n fillRefs.current[index] = node;\n }}\n className=\"block size-full origin-left [transform:scaleX(0)] rounded-full transition-colors duration-300 will-change-transform\"\n style={{ backgroundColor: level?.color ?? LEVELS[0].color }}\n />\n </span>\n ))}\n </div>\n\n <p id={strengthId} aria-live=\"polite\" className=\"mt-2 h-4 overflow-hidden text-xs\">\n {level && (\n <>\n <span className=\"opacity-60\">Strength: </span>\n <span ref={wordRef} className=\"inline-block font-medium\">\n {level.word}\n </span>\n </>\n )}\n </p>\n\n <ul id={rulesId} className=\"mt-4 space-y-2 text-sm\">\n {rules.map((rule, index) => (\n <li\n key={rule.label}\n data-met={results[index] || undefined}\n className=\"flex items-center gap-2.5 opacity-60 transition-opacity duration-200 data-met:opacity-100 motion-reduce:transition-none\"\n >\n <span\n aria-hidden=\"true\"\n className=\"relative grid size-4 shrink-0 place-items-center rounded-full border border-current/25\"\n >\n <span\n ref={(node) => {\n discRefs.current[index] = node;\n }}\n className=\"absolute -inset-px [transform:scale(0)] rounded-full bg-(--password-accent)\"\n />\n <svg viewBox=\"0 0 16 16\" className=\"relative size-3\" fill=\"none\">\n <path\n ref={(node) => {\n checkRefs.current[index] = node;\n }}\n d=\"M3.5 8.5l3 3 6-7\"\n pathLength={1}\n strokeDasharray=\"1\"\n stroke=\"var(--password-on-accent)\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n strokeDashoffset=\"1\"\n />\n </svg>\n </span>\n {rule.label}\n <span className=\"sr-only\">{results[index] ? '(met)' : '(not met)'}</span>\n </li>\n ))}\n </ul>\n </div>\n );\n};\n\nexport default PasswordStrength;\n"
}
],
"docs": "Docs, props and examples: https://tween-ui.staticmania.com/component/password-strength"
}
28 changes: 28 additions & 0 deletions apps/docs/public/r/registry.json
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,34 @@
}
]
},
{
"name": "password-strength",
"type": "registry:ui",
"title": "Password Strength",
"description": "A password field with a four-bar strength meter. The bars fill one after another and shift from red to teal as the password gets stronger, the strength word rolls in, and each requirement draws a check when it is met. The eye blinks and draws a slash across itself to show or hide the password.",
"files": [
{
"path": "components/tweenui/password-strength.tsx",
"type": "registry:component"
}
]
},
{
"name": "password-strength-demo",
"type": "registry:example",
"title": "Password Strength Demo",
"description": "Usage examples for Password Strength.",
"files": [
{
"path": "examples/password-strength-demo.tsx",
"type": "registry:example"
},
{
"path": "examples/password-strength-demo-2.tsx",
"type": "registry:example"
}
]
},
{
"name": "pricing-plan-switch",
"type": "registry:block",
Expand Down
1 change: 1 addition & 0 deletions apps/docs/registry/__index__.generated.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ export const demos: Record<string, ComponentType> = {
'elastic-slider:default': dynamic(() => import('./demos/elastic-slider')),
'package-command:default': dynamic(() => import('./demos/package-command')),
'ink-stroke-button:default': dynamic(() => import('./demos/ink-stroke-button')),
'password-strength:default': dynamic(() => import('./demos/password-strength')),
'pricing-plan-switch:default': dynamic(() => import('./demos/pricing-plan-switch')),
'process-card-reveal:default': dynamic(() => import('./demos/process-card-reveal')),
'process-sticky-steps:default': dynamic(() => import('./demos/process-sticky-steps')),
Expand Down
Loading
Loading