{
  "schemaVersion": 1,
  "target": "react",
  "name": "password-input",
  "version": "0.1.0",
  "category": "forms",
  "title": "Password Input",
  "description": "A password field with a show/hide toggle, a Caps Lock warning, and for new passwords a local strength meter and a requirements checklist that tick over as you type.",
  "tags": [
    "form",
    "password",
    "strength",
    "auth",
    "sign-in",
    "sign-up"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {},
  "registryDependencies": [],
  "docsPath": "/components/password-input",
  "props": [
    {
      "name": "autoComplete",
      "type": "\"new-password\" | \"current-password\"",
      "default": "\"current-password\"",
      "description": "new-password turns on the meter and the checklist; current-password is for sign-in."
    },
    {
      "name": "showStrength",
      "type": "boolean",
      "default": "autoComplete === \"new-password\"",
      "description": "Shows the strength meter."
    },
    {
      "name": "requirements",
      "type": "PasswordRequirement[] | false",
      "default": "defaultPasswordRequirements for new-password",
      "description": "Checklist rules, each { id, label, test }. false hides the checklist."
    },
    {
      "name": "labelAction",
      "type": "ReactNode",
      "description": "Content at the end of the label row, such as a reset link."
    },
    {
      "name": "defaultVisible",
      "type": "boolean",
      "default": "false",
      "description": "Starts with the password shown."
    },
    {
      "name": "onVisibilityChange",
      "type": "(visible) => void",
      "description": "Called when the toggle flips."
    },
    {
      "name": "label / description / error",
      "type": "ReactNode",
      "description": "Label, helper text, and an error that marks the field invalid."
    },
    {
      "name": "estimatePasswordStrength",
      "type": "(password) => { score, label, bits, level }",
      "description": "The estimator on its own: pool size and length, discounted for repeats, runs like abc or qwer, and common passwords."
    }
  ],
  "accessibility": [
    "The toggle is a button labeled Show password or Hide password with aria-pressed; it keeps focus and the caret in the input for pointer users.",
    "Works with password managers: autocomplete is passed through and the input stays a real password input while hidden.",
    "Caps Lock is announced through a status region and linked to the input while it is on.",
    "The strength word is a polite live region that only changes when the score changes; the meter bars are decorative.",
    "Each checklist row says met or not met in text for screen readers, and the list is linked to the input with aria-describedby.",
    "With reduced motion preferred the meter, checks, and eye slash change instantly."
  ],
  "states": [
    "empty",
    "weak",
    "fair",
    "strong",
    "visible",
    "caps lock",
    "invalid",
    "disabled"
  ],
  "files": [
    {
      "path": "ui/password-input.tsx",
      "content": "\"use client\";\n\nimport { type ChangeEvent, type ComponentProps, type KeyboardEvent, type ReactNode, useId, useRef, useState } from \"react\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\n\nexport interface PasswordRequirement {\n  /** Stable key for the row. */\n  id: string;\n  /** What the rule asks for, in plain words. */\n  label: string;\n  /** Returns true when the password meets the rule. */\n  test: (password: string) => boolean;\n}\n\nexport const defaultPasswordRequirements: PasswordRequirement[] = [\n  { id: \"length\", label: \"At least 12 characters\", test: (value) => Array.from(value).length >= 12 },\n  { id: \"case\", label: \"Upper and lowercase letters\", test: (value) => /\\p{Ll}/u.test(value) && /\\p{Lu}/u.test(value) },\n  { id: \"number\", label: \"A number\", test: (value) => /\\d/.test(value) },\n  { id: \"symbol\", label: \"A symbol, such as ! or #\", test: (value) => /[^\\p{L}\\p{N}\\s]/u.test(value) },\n];\n\nexport type PasswordStrengthScore = 0 | 1 | 2 | 3 | 4;\n\nexport interface PasswordStrength {\n  /** 0 too weak, 1 weak, 2 fair, 3 good, 4 strong. */\n  score: PasswordStrengthScore;\n  /** The score in words. Empty for an empty password. */\n  label: string;\n  /** Estimated guessing entropy in bits, after penalties. */\n  bits: number;\n  /** 0 to 4: how far the meter fills. Its whole part is the score. */\n  level: number;\n}\n\nconst strengthLabels = [\"Too weak\", \"Weak\", \"Fair\", \"Good\", \"Strong\"] as const;\n\n// A short list of passwords and words that show up first in every cracking dictionary.\nconst commonWords = new Set([\n  \"password\", \"passw0rd\", \"letmein\", \"welcome\", \"qwerty\", \"qwertyuiop\", \"asdfgh\", \"zxcvbn\", \"iloveyou\", \"admin\",\n  \"administrator\", \"login\", \"master\", \"monkey\", \"dragon\", \"football\", \"baseball\", \"sunshine\", \"princess\", \"shadow\",\n  \"superman\", \"trustno1\", \"starwars\", \"whatever\", \"freedom\", \"secret\", \"changeme\", \"default\", \"abc123\", \"123456\",\n]);\n\nconst keyboardRows = [\"qwertyuiop\", \"asdfghjkl\", \"zxcvbnm\", \"1234567890\"];\n\nfunction isSequential(previous: string, current: string): boolean {\n  const a = previous.toLowerCase();\n  const b = current.toLowerCase();\n  const delta = b.charCodeAt(0) - a.charCodeAt(0);\n  if (Math.abs(delta) === 1 && /[a-z0-9]/.test(a) && /[a-z0-9]/.test(b)) return true;\n  return keyboardRows.some((row) => {\n    const index = row.indexOf(a);\n    return index !== -1 && (row[index + 1] === b || row[index - 1] === b);\n  });\n}\n\n/**\n * Estimates how hard a password is to guess, locally and without dependencies. Starts from the\n * character pool and length, then discounts repeated characters, runs like \"abc\" or \"qwer\", and\n * common passwords. A coarse guide for a meter, not a security guarantee.\n */\nexport function estimatePasswordStrength(password: string): PasswordStrength {\n  const chars = Array.from(password);\n  if (chars.length === 0) return { score: 0, label: \"\", bits: 0, level: 0 };\n\n  let pool = 0;\n  if (/\\p{Ll}/u.test(password)) pool += 26;\n  if (/\\p{Lu}/u.test(password)) pool += 26;\n  if (/\\d/.test(password)) pool += 10;\n  if (/[^\\p{L}\\p{N}\\s]/u.test(password) || /\\s/.test(password)) pool += 33;\n  if (/[^\\u0000-\\u007f]/.test(password)) pool += 64;\n\n  // Each character counts fully unless it repeats or continues a run.\n  let effectiveLength = 0;\n  chars.forEach((char, index) => {\n    const previous = chars[index - 1];\n    if (previous === undefined) effectiveLength += 1;\n    else if (char === previous) effectiveLength += 0.2;\n    else if (isSequential(previous, char)) effectiveLength += 0.35;\n    else effectiveLength += 1;\n  });\n\n  let bits = effectiveLength * Math.log2(Math.max(pool, 2));\n\n  const core = password.toLowerCase().replace(/[\\d\\W_]+$/u, \"\").replace(/^[\\d\\W_]+/u, \"\");\n  if (commonWords.has(password.toLowerCase()) || commonWords.has(core)) bits = Math.min(bits, 12);\n  else if ([...commonWords].some((word) => word.length >= 5 && password.toLowerCase().includes(word))) bits *= 0.6;\n\n  // The first segment fills up to 30 bits, then each further segment takes 20 more.\n  const level = bits < 30 ? bits / 30 : Math.min(4, 1 + (bits - 30) / 20);\n  const score = Math.min(4, Math.floor(level)) as PasswordStrengthScore;\n  return { score, label: strengthLabels[score], bits: Math.round(bits), level };\n}\n\nexport interface PasswordInputProps extends Omit<ComponentProps<\"input\">, \"type\" | \"size\"> {\n  /** Visible label. Pass `aria-label` instead when the label is shown elsewhere. */\n  label?: ReactNode;\n  /** Content at the end of the label row, such as a \"Forgot password?\" link. */\n  labelAction?: ReactNode;\n  /** Helper text below the field. */\n  description?: ReactNode;\n  /** Error message. Marks the field invalid and replaces the description. */\n  error?: ReactNode;\n  /** `new-password` for sign-up and reset forms (shows the meter and checklist), `current-password` for sign-in. */\n  autoComplete?: \"new-password\" | \"current-password\" | (string & {});\n  /** Shows the strength meter. Defaults to on for `new-password`. */\n  showStrength?: boolean;\n  /** The checklist rules. Defaults to `defaultPasswordRequirements` for `new-password`; pass `false` to hide it. */\n  requirements?: PasswordRequirement[] | false;\n  /** Starts with the password shown. */\n  defaultVisible?: boolean;\n  /** Called when the show/hide toggle flips. */\n  onVisibilityChange?: (visible: boolean) => void;\n  /** Classes for the wrapping element. `className` styles the input itself. */\n  containerClassName?: string;\n}\n\nfunction EyeIcon({ hidden }: { hidden: boolean }) {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-4\">\n      <path\n        d=\"M1.75 8s2.25-4.25 6.25-4.25S14.25 8 14.25 8 12 12.25 8 12.25 1.75 8 1.75 8z\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinejoin=\"round\"\n      />\n      <circle cx=\"8\" cy=\"8\" r=\"1.75\" stroke=\"currentColor\" strokeWidth=\"1.5\" />\n      {/* The slash draws across the eye while the password is visible (\"Hide password\"). */}\n      <path\n        d=\"M2.75 2.75l10.5 10.5\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinecap=\"round\"\n        pathLength={1}\n        strokeDasharray=\"1\"\n        className={cx(`transition-[stroke-dashoffset] duration-200 ${ease} motion-reduce:transition-none`, hidden ? \"[stroke-dashoffset:1]\" : \"[stroke-dashoffset:0]\")}\n      />\n    </svg>\n  );\n}\n\nfunction RequirementGlyph({ met }: { met: boolean }) {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-4 shrink-0\">\n      <circle\n        cx=\"8\"\n        cy=\"8\"\n        r=\"6.25\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        className={cx(\"transition-opacity duration-200 ease-out motion-reduce:transition-none\", met ? \"opacity-100\" : \"opacity-40\")}\n      />\n      <path\n        d=\"M5.25 8.25l1.9 1.9 3.6-4.15\"\n        stroke=\"currentColor\"\n        strokeWidth=\"1.5\"\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        pathLength={1}\n        strokeDasharray=\"1\"\n        className={cx(\n          \"motion-reduce:transition-none\",\n          // Draws in on the way up; un-draws faster on the way down.\n          met\n            ? `transition-[stroke-dashoffset] duration-300 ${ease} [stroke-dashoffset:0]`\n            : \"transition-[stroke-dashoffset] duration-150 ease-out [stroke-dashoffset:1]\",\n        )}\n      />\n    </svg>\n  );\n}\n\nconst meterTone: Record<PasswordStrengthScore, { bar: string; text: string }> = {\n  0: { bar: \"bg-red-500\", text: \"text-red-600 dark:text-red-400\" },\n  1: { bar: \"bg-red-500\", text: \"text-red-600 dark:text-red-400\" },\n  2: { bar: \"bg-amber-500\", text: \"text-amber-600 dark:text-amber-400\" },\n  3: { bar: \"bg-emerald-500\", text: \"text-emerald-600 dark:text-emerald-400\" },\n  4: { bar: \"bg-emerald-500\", text: \"text-emerald-600 dark:text-emerald-400\" },\n};\n\n/**\n * A password field with a show/hide toggle and a Caps Lock warning. For new passwords it adds a\n * strength meter that fills continuously as the estimate grows, and a checklist whose checks draw\n * in as each rule is met. Everything is computed in the browser.\n */\nexport function PasswordInput({\n  label,\n  labelAction,\n  description,\n  error,\n  autoComplete = \"current-password\",\n  showStrength,\n  requirements,\n  defaultVisible = false,\n  onVisibilityChange,\n  id,\n  value: valueProp,\n  defaultValue,\n  onChange,\n  onKeyDown,\n  onKeyUp,\n  onBlur,\n  disabled,\n  className,\n  containerClassName,\n  \"aria-describedby\": describedBy,\n  ...props\n}: PasswordInputProps) {\n  const generatedId = useId();\n  const inputId = id ?? generatedId;\n  const messageId = `${inputId}-message`;\n  const strengthId = `${inputId}-strength`;\n  const rulesId = `${inputId}-rules`;\n  const capsId = `${inputId}-caps`;\n  const inputRef = useRef<HTMLInputElement>(null);\n\n  const isNew = autoComplete === \"new-password\";\n  const meterOn = showStrength ?? isNew;\n  const rules = requirements === false ? [] : (requirements ?? (isNew ? defaultPasswordRequirements : []));\n\n  const [innerValue, setInnerValue] = useState(String(defaultValue ?? \"\"));\n  const value = valueProp !== undefined ? String(valueProp) : innerValue;\n  const [visible, setVisible] = useState(defaultVisible);\n  const [capsLock, setCapsLock] = useState(false);\n\n  const invalid = error != null && error !== false;\n  const message = invalid ? error : description;\n  const strength = estimatePasswordStrength(value);\n  const tone = meterTone[strength.score];\n  const empty = value.length === 0;\n\n  function handleChange(event: ChangeEvent<HTMLInputElement>) {\n    if (valueProp === undefined) setInnerValue(event.target.value);\n    onChange?.(event);\n  }\n\n  function readCapsLock(event: KeyboardEvent<HTMLInputElement>) {\n    if (typeof event.getModifierState === \"function\") setCapsLock(event.getModifierState(\"CapsLock\"));\n  }\n\n  function toggleVisible() {\n    const input = inputRef.current;\n    const start = input?.selectionStart ?? null;\n    const end = input?.selectionEnd ?? null;\n    const next = !visible;\n    setVisible(next);\n    onVisibilityChange?.(next);\n    // Switching the input type resets the caret in some browsers; put it back.\n    requestAnimationFrame(() => {\n      if (input && document.activeElement === input && start != null && end != null) input.setSelectionRange(start, end);\n    });\n  }\n\n  return (\n    <div className={cx(\"@container grid min-w-0 gap-1.5\", containerClassName)}>\n      {label || labelAction ? (\n        <div className=\"flex items-baseline justify-between gap-3\">\n          {label ? (\n            <label htmlFor={inputId} className=\"text-sm font-medium text-zinc-900 dark:text-zinc-100\">\n              {label}\n            </label>\n          ) : (\n            <span />\n          )}\n          {labelAction ? <span className=\"text-sm text-zinc-500 dark:text-zinc-400\">{labelAction}</span> : null}\n        </div>\n      ) : null}\n      <div\n        className={cx(\n          \"flex h-9 w-full items-center rounded-lg border bg-white pr-1 shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:bg-black dark:shadow-none\",\n          \"transition-[border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none\",\n          invalid\n            ? \"border-red-500/60 focus-within:border-red-500 focus-within:ring-3 focus-within:ring-red-500/20\"\n            : \"border-zinc-950/15 hover:border-zinc-950/25 focus-within:border-sky-500 focus-within:ring-3 focus-within:ring-sky-500/20 dark:border-white/15 dark:hover:border-white/25 dark:focus-within:border-sky-500\",\n          disabled && \"cursor-not-allowed opacity-60\",\n        )}\n      >\n        <input\n          ref={inputRef}\n          id={inputId}\n          type={visible ? \"text\" : \"password\"}\n          autoComplete={autoComplete}\n          autoCapitalize=\"none\"\n          autoCorrect=\"off\"\n          spellCheck={false}\n          value={value}\n          onChange={handleChange}\n          onKeyDown={(event) => {\n            readCapsLock(event);\n            onKeyDown?.(event);\n          }}\n          onKeyUp={(event) => {\n            readCapsLock(event);\n            onKeyUp?.(event);\n          }}\n          onBlur={(event) => {\n            setCapsLock(false);\n            onBlur?.(event);\n          }}\n          disabled={disabled}\n          aria-invalid={invalid || undefined}\n          aria-describedby={\n            [message ? messageId : null, capsLock ? capsId : null, meterOn ? strengthId : null, rules.length ? rulesId : null, describedBy]\n              .filter(Boolean)\n              .join(\" \") || undefined\n          }\n          className={cx(\n            \"h-full w-0 min-w-0 flex-1 bg-transparent pl-3 text-sm text-zinc-950 outline-hidden placeholder:text-zinc-400 disabled:cursor-not-allowed dark:text-white dark:placeholder:text-zinc-500\",\n            !visible && !empty && \"tracking-[0.12em]\",\n            className,\n          )}\n          {...props}\n        />\n        <span\n          id={capsId}\n          role=\"status\"\n          className={cx(\n            \"pointer-events-none mr-1 flex shrink-0 items-center gap-1 text-xs font-medium whitespace-nowrap text-amber-600 dark:text-amber-400\",\n            `transition-[opacity,translate] duration-200 ${ease} motion-reduce:transition-none`,\n            capsLock ? \"opacity-100\" : \"translate-x-1 opacity-0\",\n          )}\n        >\n          <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-3.5\">\n            <path d=\"M8 2.75L3.25 7.75H5.75v2.5h4.5v-2.5h2.5L8 2.75zM5.75 13.25h4.5\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinejoin=\"round\" strokeLinecap=\"round\" />\n          </svg>\n          {capsLock ? \"Caps Lock on\" : null}\n        </span>\n        <button\n          type=\"button\"\n          onPointerDown={(event) => {\n            // Keep focus (and the caret) in the input for pointer users.\n            if (document.activeElement === inputRef.current) event.preventDefault();\n          }}\n          onClick={toggleVisible}\n          disabled={disabled}\n          aria-label={visible ? \"Hide password\" : \"Show password\"}\n          aria-pressed={visible}\n          aria-controls={inputId}\n          className={cx(\n            \"flex size-7 shrink-0 cursor-default items-center justify-center rounded-md text-zinc-500 dark:text-zinc-400\",\n            \"transition-colors duration-150 ease-out motion-reduce:transition-none\",\n            \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n            \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500 disabled:pointer-events-none\",\n          )}\n        >\n          <EyeIcon hidden={!visible} />\n        </button>\n      </div>\n\n      {message ? (\n        <p id={messageId} className={invalid ? \"text-sm text-red-600 dark:text-red-400\" : \"text-sm text-zinc-500 dark:text-zinc-400\"}>\n          {message}\n        </p>\n      ) : null}\n\n      {meterOn ? (\n        <div className=\"mt-1 grid gap-1.5\">\n          <div aria-hidden=\"true\" className=\"grid grid-cols-4 gap-1\">\n            {[0, 1, 2, 3].map((segment) => {\n              const fill = Math.max(0, Math.min(1, strength.level - segment));\n              return (\n                <span key={segment} className=\"h-1 overflow-hidden rounded-full bg-zinc-950/[0.07] dark:bg-white/10\">\n                  <span\n                    className={cx(\n                      \"block h-full origin-left rounded-full\",\n                      `transition-[scale,background-color] duration-300 ${ease} motion-reduce:transition-none`,\n                      tone.bar,\n                    )}\n                    style={{ scale: `${fill} 1` }}\n                  />\n                </span>\n              );\n            })}\n          </div>\n          <p id={strengthId} aria-live=\"polite\" className=\"flex items-center justify-between gap-3 text-xs\">\n            <span className=\"text-zinc-500 dark:text-zinc-400\">{empty ? \"Password strength\" : \"Strength\"}</span>\n            {empty ? null : (\n              <span\n                key={strength.label}\n                className={cx(\n                  \"font-medium\",\n                  tone.text,\n                  `transition-[opacity,translate] duration-200 ${ease} motion-reduce:transition-none starting:opacity-0 motion-safe:starting:translate-y-0.5`,\n                )}\n              >\n                {strength.label}\n              </span>\n            )}\n          </p>\n        </div>\n      ) : null}\n\n      {rules.length > 0 ? (\n        <ul id={rulesId} aria-label=\"Password requirements\" className=\"mt-0.5 grid gap-x-4 gap-y-1.5 @sm:grid-cols-2\">\n          {rules.map((rule) => {\n            const met = rule.test(value);\n            return (\n              <li\n                key={rule.id}\n                className={cx(\n                  \"flex items-center gap-2 text-xs transition-colors duration-200 ease-out motion-reduce:transition-none\",\n                  met ? \"text-zinc-950 dark:text-white\" : \"text-zinc-500 dark:text-zinc-500\",\n                )}\n              >\n                <span className={cx(\"flex transition-colors duration-200 ease-out motion-reduce:transition-none\", met ? \"text-emerald-600 dark:text-emerald-400\" : \"\")}>\n                  <RequirementGlyph met={met} />\n                </span>\n                <span>\n                  {rule.label}\n                  <span className=\"sr-only\">{met ? \", met\" : \", not met\"}</span>\n                </span>\n              </li>\n            );\n          })}\n        </ul>\n      ) : null}\n    </div>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { PasswordInput } from \"@/components/shaken/ui/password-input\";\n\nexport default function PasswordInputExample() {\n  return (\n    <div className=\"grid w-full max-w-3xl items-start gap-x-10 gap-y-8 md:grid-cols-2\">\n      <form className=\"grid gap-4\" onSubmit={(event) => event.preventDefault()}>\n        <div className=\"grid gap-1\">\n          <h3 className=\"text-sm font-semibold text-zinc-950 dark:text-white\">Sign in to Northwind Console</h3>\n          <p className=\"text-sm text-zinc-500 dark:text-zinc-400\">Use the password for mara@northwind.dev.</p>\n        </div>\n        <input type=\"email\" name=\"email\" autoComplete=\"username\" defaultValue=\"mara@northwind.dev\" hidden readOnly />\n        <PasswordInput\n          label=\"Password\"\n          name=\"password\"\n          autoComplete=\"current-password\"\n          labelAction={\n            <a href=\"#reset\" className=\"rounded-sm hover:text-zinc-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 dark:hover:text-white\">\n              Forgot password?\n            </a>\n          }\n        />\n      </form>\n      <form className=\"grid gap-4\" onSubmit={(event) => event.preventDefault()}>\n        <div className=\"grid gap-1\">\n          <h3 className=\"text-sm font-semibold text-zinc-950 dark:text-white\">Choose a new password</h3>\n          <p className=\"text-sm text-zinc-500 dark:text-zinc-400\">You will be signed out on your other devices.</p>\n        </div>\n        <PasswordInput label=\"New password\" name=\"new-password\" autoComplete=\"new-password\" defaultValue=\"harbor-lamp7\" />\n      </form>\n    </div>\n  );\n}\n"
  }
}
