{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"password-field","type":"registry:component","title":"Password field","description":"Reveals the password with a wave of dots turning into letters; the meter fills as it gets stronger.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/password-field.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useLayoutEffect, useRef, useState } from \"react\";\nimport { motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n// Long enough to outlast a burst of typing, short enough that the verdict\n// still arrives while the user is thinking about it.\nconst ANNOUNCE_DELAY = 900;\n// Per changed segment, so even an empty-to-full jump starts its last segment\n// only 120ms after the first.\nconst STAGGER = 40;\n\n// The reveal: each dot slides out to where its letter sits and resolves\n// into it, left to right like reading; hiding runs it back from the right\n// and the dots close ranks. Per character it is a quick 200ms swap. The wave\n// across the word is capped at 160ms however long the password is, so the\n// whole gesture stays near 360ms: long enough to read as one sweep.\nconst CHAR_MS = 200;\nconst WAVE_MS = 160;\nconst MORPH_CSS = `\n@keyframes pw-slide { from { translate: var(--pw-from) 0; } to { translate: var(--pw-to) 0; } }\n@keyframes pw-show { from { opacity: 0; filter: blur(4px); scale: 0.6; } }\n@keyframes pw-hide { to { opacity: 0; filter: blur(4px); scale: 0.6; } }\n`;\n\ntype Morph = {\n  id: number;\n  reveal: boolean;\n  chars: string[];\n  // Left edge of each character as text, and as a password dot.\n  letterX: number[];\n  dotX: number[];\n};\n\nlet measureCanvas: HTMLCanvasElement | null = null;\n\n// Where each character starts in both renderings, measured with the input's\n// own font, so the overlay lands exactly on what the input will draw.\nfunction measure(input: HTMLInputElement, chars: string[]) {\n  measureCanvas ??= document.createElement(\"canvas\");\n  const ctx = measureCanvas.getContext(\"2d\");\n  if (!ctx) return null;\n  const style = getComputedStyle(input);\n  ctx.font = `${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;\n  const dot = ctx.measureText(\"•\").width;\n  const letterX: number[] = [];\n  let prefix = \"\";\n  for (const c of chars) {\n    letterX.push(ctx.measureText(prefix).width);\n    prefix += c;\n  }\n  return { letterX, dotX: chars.map((_, i) => i * dot) };\n}\n\nconst WORDS = [\"\", \"Weak\", \"Good\", \"Good\", \"Strong\"] as const;\nconst VERDICTS = [\"Weak\", \"Good\", \"Strong\"] as const;\n// Weak is the one level worth alarm; past that, the meter just gets bolder.\nconst LEVEL_COLORS = [\n  \"\",\n  \"bg-destructive\",\n  \"bg-foreground/35\",\n  \"bg-foreground/65\",\n  \"bg-foreground\",\n];\n\nconst RULES = [\n  { label: \"8 or more characters\", test: (p: string) => p.length >= 8 },\n  { label: \"A number\", test: (p: string) => /\\d/.test(p) },\n  { label: \"A symbol\", test: (p: string) => /[^A-Za-z0-9\\s]/.test(p) },\n];\n\n// 0 when empty, otherwise 1 to 4. Length matters most, so anything under 8\n// characters stays Weak however varied it is.\nexport function passwordStrength(password: string) {\n  if (password === \"\") return 0;\n  const variety = [/[a-z]/, /[A-Z]/, /\\d/, /[^A-Za-z0-9]/].filter((r) =>\n    r.test(password),\n  ).length;\n  if (password.length < 8) return 1;\n  let score = 1;\n  if (password.length >= 12) score++;\n  if (variety >= 2) score++;\n  if (variety >= 3) score++;\n  return Math.min(score, 4);\n}\n\nexport function PasswordField({\n  label = \"Password\",\n  name,\n  autoComplete = \"new-password\",\n  onValueChange,\n  className,\n}: {\n  label?: string;\n  name?: string;\n  autoComplete?: string;\n  onValueChange?: (value: string) => void;\n  className?: string;\n}) {\n  const id = useId();\n  const rulesId = `${id}-rules`;\n  const reduceMotion = useReducedMotion();\n  const inputRef = useRef<HTMLInputElement>(null);\n  const selection = useRef<[number, number] | null>(null);\n  const [value, setValue] = useState(\"\");\n  const [revealed, setRevealed] = useState(false);\n\n  const score = passwordStrength(value);\n  const word = WORDS[score];\n\n  // The score before the latest change, so only the segments that actually\n  // change get staggered: left to right as the meter fills, right to left as\n  // it drains. Segments already filled just recolor at once.\n  const [current, setCurrent] = useState(score);\n  const [from, setFrom] = useState(score);\n  if (score !== current) {\n    setFrom(current);\n    setCurrent(score);\n  }\n\n  const [announced, setAnnounced] = useState(\"\");\n  useEffect(() => {\n    const timer = setTimeout(\n      () => setAnnounced(word ? `Password strength: ${word}` : \"\"),\n      ANNOUNCE_DELAY,\n    );\n    return () => clearTimeout(timer);\n  }, [word]);\n\n  // Switching the input type can reset the caret in some browsers, so put\n  // it back exactly where it was.\n  useLayoutEffect(() => {\n    const input = inputRef.current;\n    const range = selection.current;\n    if (!input || !range || document.activeElement !== input) return;\n    input.setSelectionRange(range[0], range[1]);\n    selection.current = null;\n  }, [revealed]);\n\n  const [morph, setMorph] = useState<Morph | null>(null);\n  const morphTimer = useRef<ReturnType<typeof setTimeout>>(undefined);\n  useEffect(() => () => clearTimeout(morphTimer.current), []);\n\n  const toggle = () => {\n    const input = inputRef.current;\n    if (input && input.selectionStart !== null && input.selectionEnd !== null)\n      selection.current = [input.selectionStart, input.selectionEnd];\n    const next = !revealed;\n    setRevealed(next);\n    clearTimeout(morphTimer.current);\n    setMorph(null);\n    const chars = [...value];\n    // Skipped when the text is scrolled inside the field: the overlay only\n    // knows where characters sit when the field starts at its first one.\n    if (\n      !input ||\n      reduceMotion ||\n      chars.length === 0 ||\n      input.scrollWidth > input.clientWidth ||\n      input.scrollLeft > 0\n    )\n      return;\n    const spots = measure(input, chars);\n    if (!spots) return;\n    const id = (morph?.id ?? 0) + 1;\n    setMorph({ id, reveal: next, chars, ...spots });\n    morphTimer.current = setTimeout(() => setMorph(null), CHAR_MS + WAVE_MS);\n  };\n\n  const step = morph ? Math.min(24, WAVE_MS / Math.max(morph.chars.length - 1, 1)) : 0;\n\n  return (\n    <div className={cn(\"flex flex-col\", className)}>\n      <label\n        htmlFor={id}\n        className=\"mb-2 text-[15px] font-medium text-foreground select-none\"\n      >\n        {label}\n      </label>\n      <div className=\"relative\">\n        <input\n          ref={inputRef}\n          id={id}\n          name={name}\n          type={revealed ? \"text\" : \"password\"}\n          autoComplete={autoComplete}\n          autoCapitalize=\"off\"\n          spellCheck={false}\n          value={value}\n          aria-describedby={rulesId}\n          onChange={(e) => {\n            // Typing wins over the flourish: the real text shows at once.\n            clearTimeout(morphTimer.current);\n            setMorph(null);\n            setValue(e.target.value);\n            onValueChange?.(e.target.value);\n          }}\n          className={cn(\n            \"h-11 w-full rounded-xl border border-border bg-background pr-12 pl-3.5 text-[15px] caret-foreground outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-1 focus-visible:outline-foreground\",\n            // The overlay draws the characters while it runs; the caret stays.\n            morph ? \"text-transparent\" : \"text-foreground\",\n          )}\n        />\n        {morph && (\n          <span\n            key={morph.id}\n            aria-hidden\n            // Same box and type as the input's text: 1px border + 14px padding.\n            className=\"pointer-events-none absolute inset-y-0 right-12 left-[15px] overflow-hidden text-[15px] whitespace-pre text-foreground\"\n          >\n            <style href=\"password-field\" precedence=\"default\">\n              {MORPH_CSS}\n            </style>\n            {morph.chars.map((char, i) => {\n              // Reveal sweeps left to right; hiding starts from the end.\n              const order = morph.reveal ? i : morph.chars.length - 1 - i;\n              const timing = `${CHAR_MS}ms cubic-bezier(0.23, 1, 0.32, 1) ${order * step}ms both`;\n              const from = morph.reveal ? morph.dotX[i] : morph.letterX[i];\n              const to = morph.reveal ? morph.letterX[i] : morph.dotX[i];\n              return (\n                <span\n                  key={i}\n                  // Left-aligned, so the dot and the letter share the left\n                  // edge the measurements describe.\n                  className=\"absolute inset-y-0 left-0 grid items-center justify-items-start\"\n                  style={\n                    {\n                      \"--pw-from\": `${from}px`,\n                      \"--pw-to\": `${to}px`,\n                      animation: `pw-slide ${timing}`,\n                    } as React.CSSProperties\n                  }\n                >\n                  <span\n                    className=\"col-start-1 row-start-1\"\n                    style={{ animation: `${morph.reveal ? \"pw-show\" : \"pw-hide\"} ${timing}` }}\n                  >\n                    {char}\n                  </span>\n                  <span\n                    className=\"col-start-1 row-start-1\"\n                    style={{ animation: `${morph.reveal ? \"pw-hide\" : \"pw-show\"} ${timing}` }}\n                  >\n                    {\"•\"}\n                  </span>\n                </span>\n              );\n            })}\n          </span>\n        )}\n        {/* 8px radius inside the 12px field with 4px of inset: concentric. */}\n        <button\n          type=\"button\"\n          aria-label=\"Show password\"\n          aria-pressed={revealed}\n          aria-controls={id}\n          // Stops a mouse click from stealing focus, so the caret stays put\n          // and typing can carry on. Keyboard users keep focus on the button.\n          onPointerDown={(e) => {\n            if (e.pointerType === \"mouse\") e.preventDefault();\n          }}\n          onClick={toggle}\n          className={cn(\n            \"absolute top-1 right-1 flex size-9 touch-manipulation items-center justify-center rounded-lg text-muted-foreground outline-hidden transition-[scale,color,background-color] duration-150 ease-out select-none hover:bg-muted hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color]\",\n            revealed && \"text-foreground\",\n          )}\n        >\n          <span className=\"grid\" aria-hidden>\n            <Icon visible={!revealed} reduceMotion={reduceMotion}>\n              <path d=\"M1.75 8S4 3.75 8 3.75 14.25 8 14.25 8 12 12.25 8 12.25 1.75 8 1.75 8Z\" />\n              <circle cx=\"8\" cy=\"8\" r=\"2\" />\n            </Icon>\n            <Icon visible={revealed} reduceMotion={reduceMotion}>\n              <path d=\"M6.5 3.9A6 6 0 0 1 8 3.75c4 0 6.25 4.25 6.25 4.25a11 11 0 0 1-1.6 2.2M9.4 9.45a2 2 0 0 1-2.85-2.85M11.6 11.3A6.3 6.3 0 0 1 8 12.25C4 12.25 1.75 8 1.75 8a11 11 0 0 1 2.7-3.2M2.25 2.25l11.5 11.5\" />\n            </Icon>\n          </span>\n        </button>\n      </div>\n\n      <div className=\"mt-3 flex items-center gap-3\" aria-hidden>\n        <div className=\"flex flex-1 gap-1.5\">\n          {[1, 2, 3, 4].map((segment) => {\n            const filled = segment <= score;\n            const step =\n              score > from\n                ? segment - from - 1\n                : segment > score\n                  ? from - segment\n                  : 0;\n            const delay = Math.max(0, step) * STAGGER;\n            return (\n              <span\n                key={segment}\n                className=\"h-1.5 flex-1 overflow-hidden rounded-full bg-border\"\n              >\n                <span\n                  style={{\n                    transitionDelay: reduceMotion ? \"0ms\" : `${delay}ms`,\n                  }}\n                  className={cn(\n                    \"block h-full origin-left rounded-full transition-[scale,opacity,background-color] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity,background-color]\",\n                    filled\n                      ? cn(\"scale-x-100 opacity-100\", LEVEL_COLORS[score])\n                      : \"scale-x-0 opacity-0 motion-reduce:scale-x-100\",\n                  )}\n                />\n              </span>\n            );\n          })}\n        </div>\n        {/* All words share one grid cell, so the row keeps the width of the\n            longest and never jumps; they crossfade through a 4px blur. */}\n        <span className=\"grid w-14 text-right text-sm font-medium\">\n          {VERDICTS.map((w) => (\n            <span\n              key={w}\n              className={cn(\n                \"col-start-1 row-start-1 transition-[opacity,filter] ease-out\",\n                w === word\n                  ? \"opacity-100 blur-[0px] duration-200\"\n                  : \"opacity-0 blur-[4px] duration-150\",\n                w === \"Weak\" ? \"text-destructive\" : \"text-foreground\",\n              )}\n            >\n              {w}\n            </span>\n          ))}\n        </span>\n      </div>\n\n      <ul id={rulesId} className=\"mt-3.5 flex flex-col gap-2\">\n        {RULES.map((rule) => {\n          const met = rule.test(value);\n          return (\n            <li\n              key={rule.label}\n              className={cn(\n                \"flex items-center gap-2 text-sm transition-[color] duration-150 ease-out\",\n                met ? \"text-foreground\" : \"text-muted-foreground\",\n              )}\n            >\n              <span className=\"grid\" aria-hidden>\n                <Icon visible={!met} reduceMotion={reduceMotion} small>\n                  <circle cx=\"8\" cy=\"8\" r=\"2\" />\n                </Icon>\n                <Icon visible={met} reduceMotion={reduceMotion} small>\n                  <path d=\"m3.5 8.5 3 3 6-7\" />\n                </Icon>\n              </span>\n              {rule.label}\n              <span className=\"sr-only\">{met ? \", met\" : \", not met\"}</span>\n            </li>\n          );\n        })}\n      </ul>\n\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {announced}\n      </span>\n    </div>\n  );\n}\n\nfunction Icon({\n  visible,\n  reduceMotion,\n  small,\n  children,\n}: {\n  visible: boolean;\n  reduceMotion: boolean | null;\n  small?: boolean;\n  children: React.ReactNode;\n}) {\n  // Reduced motion keeps the cross-fade but drops the scale and blur.\n  const hidden = reduceMotion\n    ? { opacity: 0 }\n    : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" };\n  return (\n    <motion.svg\n      viewBox=\"0 0 16 16\"\n      className={cn(\"col-start-1 row-start-1\", small ? \"size-4\" : \"size-5\")}\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={1.5}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      initial={false}\n      animate={visible ? { scale: 1, opacity: 1, filter: \"blur(0px)\" } : hidden}\n      transition={ICON_SWAP}\n    >\n      {children}\n    </motion.svg>\n  );\n}\n\nexport default function PasswordFieldDemo() {\n  return <PasswordField name=\"password\" className=\"w-[380px] max-w-full\" />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/password-field"}