Skip to content
Shaken UI
Sign in

Password Input

Save

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.

Category
Forms
Version
0.1.0
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Password Input preview

Sign in to Northwind Console

Use the password for mara@northwind.dev.

Choose a new password

You will be signed out on your other devices.

StrengthGood

  • At least 12 characters, met
  • Upper and lowercase letters, not met
  • A number, met
  • A symbol, such as ! or #, met

Installation

npx @shakenui/cli add password-input

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add password-input --dry-run

Usage

password-input-example.tsx
"use client";

import { PasswordInput } from "@/components/shaken/ui/password-input";

export default function PasswordInputExample() {
  return (
    <div className="grid w-full max-w-3xl items-start gap-x-10 gap-y-8 md:grid-cols-2">
      <form className="grid gap-4" onSubmit={(event) => event.preventDefault()}>
        <div className="grid gap-1">
          <h3 className="text-sm font-semibold text-zinc-950 dark:text-white">Sign in to Northwind Console</h3>
          <p className="text-sm text-zinc-500 dark:text-zinc-400">Use the password for mara@northwind.dev.</p>
        </div>
        <input type="email" name="email" autoComplete="username" defaultValue="mara@northwind.dev" hidden readOnly />
        <PasswordInput
          label="Password"
          name="password"
          autoComplete="current-password"
          labelAction={
            <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">
              Forgot password?
            </a>
          }
        />
      </form>
      <form className="grid gap-4" onSubmit={(event) => event.preventDefault()}>
        <div className="grid gap-1">
          <h3 className="text-sm font-semibold text-zinc-950 dark:text-white">Choose a new password</h3>
          <p className="text-sm text-zinc-500 dark:text-zinc-400">You will be signed out on your other devices.</p>
        </div>
        <PasswordInput label="New password" name="new-password" autoComplete="new-password" defaultValue="harbor-lamp7" />
      </form>
    </div>
  );
}

States

Every state, rendered from local fixture data.

Password Input states

Password strength

  • At least 12 characters, not met
  • Upper and lowercase letters, not met
  • A number, not met
  • A symbol, such as ! or #, not met

StrengthToo weak

  • At least 12 characters, met
  • Upper and lowercase letters, met
  • A number, met
  • A symbol, such as ! or #, met

StrengthWeak

  • At least 12 characters, not met
  • Upper and lowercase letters, met
  • A number, met
  • A symbol, such as ! or #, met

StrengthStrong

  • At least 12 characters, met
  • Upper and lowercase letters, met
  • A number, met
  • A symbol, such as ! or #, not met

That password is incorrect. 2 attempts left.

API

PropTypeDefaultDescription
autoComplete"new-password" | "current-password""current-password"new-password turns on the meter and the checklist; current-password is for sign-in.
showStrengthbooleanautoComplete === "new-password"Shows the strength meter.
requirementsPasswordRequirement[] | falsedefaultPasswordRequirements for new-passwordChecklist rules, each { id, label, test }. false hides the checklist.
labelActionReactNode—Content at the end of the label row, such as a reset link.
defaultVisiblebooleanfalseStarts with the password shown.
onVisibilityChange(visible) => void—Called when the toggle flips.
label / description / errorReactNode—Label, helper text, and an error that marks the field invalid.
estimatePasswordStrength(password) => { score, label, bits, level }—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.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/password-input.tsxpassword-input
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/password-input/0.1.0.json.

ui/password-input.tsxShow
ui/password-input.tsx
"use client";

import { type ChangeEvent, type ComponentProps, type KeyboardEvent, type ReactNode, useId, useRef, useState } from "react";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";

export interface PasswordRequirement {
  /** Stable key for the row. */
  id: string;
  /** What the rule asks for, in plain words. */
  label: string;
  /** Returns true when the password meets the rule. */
  test: (password: string) => boolean;
}

export const defaultPasswordRequirements: PasswordRequirement[] = [
  { id: "length", label: "At least 12 characters", test: (value) => Array.from(value).length >= 12 },
  { id: "case", label: "Upper and lowercase letters", test: (value) => /\p{Ll}/u.test(value) && /\p{Lu}/u.test(value) },
  { id: "number", label: "A number", test: (value) => /\d/.test(value) },
  { id: "symbol", label: "A symbol, such as ! or #", test: (value) => /[^\p{L}\p{N}\s]/u.test(value) },
];

export type PasswordStrengthScore = 0 | 1 | 2 | 3 | 4;

export interface PasswordStrength {
  /** 0 too weak, 1 weak, 2 fair, 3 good, 4 strong. */
  score: PasswordStrengthScore;
  /** The score in words. Empty for an empty password. */
  label: string;
  /** Estimated guessing entropy in bits, after penalties. */
  bits: number;
  /** 0 to 4: how far the meter fills. Its whole part is the score. */
  level: number;
}

const strengthLabels = ["Too weak", "Weak", "Fair", "Good", "Strong"] as const;

// A short list of passwords and words that show up first in every cracking dictionary.
const commonWords = new Set([
  "password", "passw0rd", "letmein", "welcome", "qwerty", "qwertyuiop", "asdfgh", "zxcvbn", "iloveyou", "admin",
  "administrator", "login", "master", "monkey", "dragon", "football", "baseball", "sunshine", "princess", "shadow",
  "superman", "trustno1", "starwars", "whatever", "freedom", "secret", "changeme", "default", "abc123", "123456",
]);

const keyboardRows = ["qwertyuiop", "asdfghjkl", "zxcvbnm", "1234567890"];

function isSequential(previous: string, current: string): boolean {
  const a = previous.toLowerCase();
  const b = current.toLowerCase();
  const delta = b.charCodeAt(0) - a.charCodeAt(0);
  if (Math.abs(delta) === 1 && /[a-z0-9]/.test(a) && /[a-z0-9]/.test(b)) return true;
  return keyboardRows.some((row) => {
    const index = row.indexOf(a);
    return index !== -1 && (row[index + 1] === b || row[index - 1] === b);
  });
}

/**
 * Estimates how hard a password is to guess, locally and without dependencies. Starts from the
 * character pool and length, then discounts repeated characters, runs like "abc" or "qwer", and
 * common passwords. A coarse guide for a meter, not a security guarantee.
 */
export function estimatePasswordStrength(password: string): PasswordStrength {
  const chars = Array.from(password);
  if (chars.length === 0) return { score: 0, label: "", bits: 0, level: 0 };

  let pool = 0;
  if (/\p{Ll}/u.test(password)) pool += 26;
  if (/\p{Lu}/u.test(password)) pool += 26;
  if (/\d/.test(password)) pool += 10;
  if (/[^\p{L}\p{N}\s]/u.test(password) || /\s/.test(password)) pool += 33;
  if (/[^\u0000-\u007f]/.test(password)) pool += 64;

  // Each character counts fully unless it repeats or continues a run.
  let effectiveLength = 0;
  chars.forEach((char, index) => {
    const previous = chars[index - 1];
    if (previous === undefined) effectiveLength += 1;
    else if (char === previous) effectiveLength += 0.2;
    else if (isSequential(previous, char)) effectiveLength += 0.35;
    else effectiveLength += 1;
  });

  let bits = effectiveLength * Math.log2(Math.max(pool, 2));

  const core = password.toLowerCase().replace(/[\d\W_]+$/u, "").replace(/^[\d\W_]+/u, "");
  if (commonWords.has(password.toLowerCase()) || commonWords.has(core)) bits = Math.min(bits, 12);
  else if ([...commonWords].some((word) => word.length >= 5 && password.toLowerCase().includes(word))) bits *= 0.6;

  // The first segment fills up to 30 bits, then each further segment takes 20 more.
  const level = bits < 30 ? bits / 30 : Math.min(4, 1 + (bits - 30) / 20);
  const score = Math.min(4, Math.floor(level)) as PasswordStrengthScore;
  return { score, label: strengthLabels[score], bits: Math.round(bits), level };
}

export interface PasswordInputProps extends Omit<ComponentProps<"input">, "type" | "size"> {
  /** Visible label. Pass `aria-label` instead when the label is shown elsewhere. */
  label?: ReactNode;
  /** Content at the end of the label row, such as a "Forgot password?" link. */
  labelAction?: ReactNode;
  /** Helper text below the field. */
  description?: ReactNode;
  /** Error message. Marks the field invalid and replaces the description. */
  error?: ReactNode;
  /** `new-password` for sign-up and reset forms (shows the meter and checklist), `current-password` for sign-in. */
  autoComplete?: "new-password" | "current-password" | (string & {});
  /** Shows the strength meter. Defaults to on for `new-password`. */
  showStrength?: boolean;
  /** The checklist rules. Defaults to `defaultPasswordRequirements` for `new-password`; pass `false` to hide it. */
  requirements?: PasswordRequirement[] | false;
  /** Starts with the password shown. */
  defaultVisible?: boolean;
  /** Called when the show/hide toggle flips. */
  onVisibilityChange?: (visible: boolean) => void;
  /** Classes for the wrapping element. `className` styles the input itself. */
  containerClassName?: string;
}

function EyeIcon({ hidden }: { hidden: boolean }) {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4">
      <path
        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"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinejoin="round"
      />
      <circle cx="8" cy="8" r="1.75" stroke="currentColor" strokeWidth="1.5" />
      {/* The slash draws across the eye while the password is visible ("Hide password"). */}
      <path
        d="M2.75 2.75l10.5 10.5"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        pathLength={1}
        strokeDasharray="1"
        className={cx(`transition-[stroke-dashoffset] duration-200 ${ease} motion-reduce:transition-none`, hidden ? "[stroke-dashoffset:1]" : "[stroke-dashoffset:0]")}
      />
    </svg>
  );
}

function RequirementGlyph({ met }: { met: boolean }) {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-4 shrink-0">
      <circle
        cx="8"
        cy="8"
        r="6.25"
        stroke="currentColor"
        strokeWidth="1.5"
        className={cx("transition-opacity duration-200 ease-out motion-reduce:transition-none", met ? "opacity-100" : "opacity-40")}
      />
      <path
        d="M5.25 8.25l1.9 1.9 3.6-4.15"
        stroke="currentColor"
        strokeWidth="1.5"
        strokeLinecap="round"
        strokeLinejoin="round"
        pathLength={1}
        strokeDasharray="1"
        className={cx(
          "motion-reduce:transition-none",
          // Draws in on the way up; un-draws faster on the way down.
          met
            ? `transition-[stroke-dashoffset] duration-300 ${ease} [stroke-dashoffset:0]`
            : "transition-[stroke-dashoffset] duration-150 ease-out [stroke-dashoffset:1]",
        )}
      />
    </svg>
  );
}

const meterTone: Record<PasswordStrengthScore, { bar: string; text: string }> = {
  0: { bar: "bg-red-500", text: "text-red-600 dark:text-red-400" },
  1: { bar: "bg-red-500", text: "text-red-600 dark:text-red-400" },
  2: { bar: "bg-amber-500", text: "text-amber-600 dark:text-amber-400" },
  3: { bar: "bg-emerald-500", text: "text-emerald-600 dark:text-emerald-400" },
  4: { bar: "bg-emerald-500", text: "text-emerald-600 dark:text-emerald-400" },
};

/**
 * A password field with a show/hide toggle and a Caps Lock warning. For new passwords it adds a
 * strength meter that fills continuously as the estimate grows, and a checklist whose checks draw
 * in as each rule is met. Everything is computed in the browser.
 */
export function PasswordInput({
  label,
  labelAction,
  description,
  error,
  autoComplete = "current-password",
  showStrength,
  requirements,
  defaultVisible = false,
  onVisibilityChange,
  id,
  value: valueProp,
  defaultValue,
  onChange,
  onKeyDown,
  onKeyUp,
  onBlur,
  disabled,
  className,
  containerClassName,
  "aria-describedby": describedBy,
  ...props
}: PasswordInputProps) {
  const generatedId = useId();
  const inputId = id ?? generatedId;
  const messageId = `${inputId}-message`;
  const strengthId = `${inputId}-strength`;
  const rulesId = `${inputId}-rules`;
  const capsId = `${inputId}-caps`;
  const inputRef = useRef<HTMLInputElement>(null);

  const isNew = autoComplete === "new-password";
  const meterOn = showStrength ?? isNew;
  const rules = requirements === false ? [] : (requirements ?? (isNew ? defaultPasswordRequirements : []));

  const [innerValue, setInnerValue] = useState(String(defaultValue ?? ""));
  const value = valueProp !== undefined ? String(valueProp) : innerValue;
  const [visible, setVisible] = useState(defaultVisible);
  const [capsLock, setCapsLock] = useState(false);

  const invalid = error != null && error !== false;
  const message = invalid ? error : description;
  const strength = estimatePasswordStrength(value);
  const tone = meterTone[strength.score];
  const empty = value.length === 0;

  function handleChange(event: ChangeEvent<HTMLInputElement>) {
    if (valueProp === undefined) setInnerValue(event.target.value);
    onChange?.(event);
  }

  function readCapsLock(event: KeyboardEvent<HTMLInputElement>) {
    if (typeof event.getModifierState === "function") setCapsLock(event.getModifierState("CapsLock"));
  }

  function toggleVisible() {
    const input = inputRef.current;
    const start = input?.selectionStart ?? null;
    const end = input?.selectionEnd ?? null;
    const next = !visible;
    setVisible(next);
    onVisibilityChange?.(next);
    // Switching the input type resets the caret in some browsers; put it back.
    requestAnimationFrame(() => {
      if (input && document.activeElement === input && start != null && end != null) input.setSelectionRange(start, end);
    });
  }

  return (
    <div className={cx("@container grid min-w-0 gap-1.5", containerClassName)}>
      {label || labelAction ? (
        <div className="flex items-baseline justify-between gap-3">
          {label ? (
            <label htmlFor={inputId} className="text-sm font-medium text-zinc-900 dark:text-zinc-100">
              {label}
            </label>
          ) : (
            <span />
          )}
          {labelAction ? <span className="text-sm text-zinc-500 dark:text-zinc-400">{labelAction}</span> : null}
        </div>
      ) : null}
      <div
        className={cx(
          "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",
          "transition-[border-color,box-shadow] duration-150 ease-out motion-reduce:transition-none",
          invalid
            ? "border-red-500/60 focus-within:border-red-500 focus-within:ring-3 focus-within:ring-red-500/20"
            : "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",
          disabled && "cursor-not-allowed opacity-60",
        )}
      >
        <input
          ref={inputRef}
          id={inputId}
          type={visible ? "text" : "password"}
          autoComplete={autoComplete}
          autoCapitalize="none"
          autoCorrect="off"
          spellCheck={false}
          value={value}
          onChange={handleChange}
          onKeyDown={(event) => {
            readCapsLock(event);
            onKeyDown?.(event);
          }}
          onKeyUp={(event) => {
            readCapsLock(event);
            onKeyUp?.(event);
          }}
          onBlur={(event) => {
            setCapsLock(false);
            onBlur?.(event);
          }}
          disabled={disabled}
          aria-invalid={invalid || undefined}
          aria-describedby={
            [message ? messageId : null, capsLock ? capsId : null, meterOn ? strengthId : null, rules.length ? rulesId : null, describedBy]
              .filter(Boolean)
              .join(" ") || undefined
          }
          className={cx(
            "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",
            !visible && !empty && "tracking-[0.12em]",
            className,
          )}
          {...props}
        />
        <span
          id={capsId}
          role="status"
          className={cx(
            "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",
            `transition-[opacity,translate] duration-200 ${ease} motion-reduce:transition-none`,
            capsLock ? "opacity-100" : "translate-x-1 opacity-0",
          )}
        >
          <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" className="size-3.5">
            <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" />
          </svg>
          {capsLock ? "Caps Lock on" : null}
        </span>
        <button
          type="button"
          onPointerDown={(event) => {
            // Keep focus (and the caret) in the input for pointer users.
            if (document.activeElement === inputRef.current) event.preventDefault();
          }}
          onClick={toggleVisible}
          disabled={disabled}
          aria-label={visible ? "Hide password" : "Show password"}
          aria-pressed={visible}
          aria-controls={inputId}
          className={cx(
            "flex size-7 shrink-0 cursor-default items-center justify-center rounded-md text-zinc-500 dark:text-zinc-400",
            "transition-colors duration-150 ease-out motion-reduce:transition-none",
            "hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
            "focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500 disabled:pointer-events-none",
          )}
        >
          <EyeIcon hidden={!visible} />
        </button>
      </div>

      {message ? (
        <p id={messageId} className={invalid ? "text-sm text-red-600 dark:text-red-400" : "text-sm text-zinc-500 dark:text-zinc-400"}>
          {message}
        </p>
      ) : null}

      {meterOn ? (
        <div className="mt-1 grid gap-1.5">
          <div aria-hidden="true" className="grid grid-cols-4 gap-1">
            {[0, 1, 2, 3].map((segment) => {
              const fill = Math.max(0, Math.min(1, strength.level - segment));
              return (
                <span key={segment} className="h-1 overflow-hidden rounded-full bg-zinc-950/[0.07] dark:bg-white/10">
                  <span
                    className={cx(
                      "block h-full origin-left rounded-full",
                      `transition-[scale,background-color] duration-300 ${ease} motion-reduce:transition-none`,
                      tone.bar,
                    )}
                    style={{ scale: `${fill} 1` }}
                  />
                </span>
              );
            })}
          </div>
          <p id={strengthId} aria-live="polite" className="flex items-center justify-between gap-3 text-xs">
            <span className="text-zinc-500 dark:text-zinc-400">{empty ? "Password strength" : "Strength"}</span>
            {empty ? null : (
              <span
                key={strength.label}
                className={cx(
                  "font-medium",
                  tone.text,
                  `transition-[opacity,translate] duration-200 ${ease} motion-reduce:transition-none starting:opacity-0 motion-safe:starting:translate-y-0.5`,
                )}
              >
                {strength.label}
              </span>
            )}
          </p>
        </div>
      ) : null}

      {rules.length > 0 ? (
        <ul id={rulesId} aria-label="Password requirements" className="mt-0.5 grid gap-x-4 gap-y-1.5 @sm:grid-cols-2">
          {rules.map((rule) => {
            const met = rule.test(value);
            return (
              <li
                key={rule.id}
                className={cx(
                  "flex items-center gap-2 text-xs transition-colors duration-200 ease-out motion-reduce:transition-none",
                  met ? "text-zinc-950 dark:text-white" : "text-zinc-500 dark:text-zinc-500",
                )}
              >
                <span className={cx("flex transition-colors duration-200 ease-out motion-reduce:transition-none", met ? "text-emerald-600 dark:text-emerald-400" : "")}>
                  <RequirementGlyph met={met} />
                </span>
                <span>
                  {rule.label}
                  <span className="sr-only">{met ? ", met" : ", not met"}</span>
                </span>
              </li>
            );
          })}
        </ul>
      ) : null}
    </div>
  );
}