Skip to content
Thrum

Password input

A password field with a button that shows and hides what was typed. It can add a strength meter for a new password and it says when Caps Lock is on. For a one-time code use an OTP input; for any other secret that needs no reveal, an input of type password is enough.

Install

npx shadcn@latest add https://thrumui.dev/r/password-input.json

Adds components/ui/password-input.tsx. Nothing else in your project changes.

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

Automatically installs icons eye and eye-off from the icon set.

Props

PropTypeDefaultDescription
strengthbooleanDefault falseShow a four-step meter and a word under the field: Weak, Fair, Good or Strong. The score comes from passwordStrength().
visibleboolean–Whether the password is readable, when the parent holds that state. Use it with onVisibleChange.
defaultVisiblebooleanDefault falseWhether the password starts readable, when the field holds that state itself.
onVisibleChange(visible: boolean) => void–Called with the new state when the button is pressed, and with false when the form is submitted.
capsLockNoticebooleanDefault truePrint Caps Lock is on under the field while it is, and the field has the focus.
size"sm" | "md" | "lg"Default "md"sm is 28 pixels tall, md 32, lg 40.
autoCompletestringDefault "current-password"Set new-password on a sign-up or change form, so a password manager offers to make one.
disabledbooleanDefault falseDisables the field and the button, and dims both.
soundbooleanDefault truePlay a soft toggle sound when showing or hiding the password, if the visitor has sound on.
classNamestring–Extra classes for the wrapper around the field, the meter and the notice. It fills its container; set a width here.
...propsComponentProps<"input">–Every other input attribute and event handler goes to the input: value, defaultValue, onChange, name, id, required, aria-invalid.
passwordStrength()(value: string) => number–A second export, a pure function: 0 for empty, 1 under 8 characters or under 5 different ones, then one more each for 12 characters, for 16, and for three kinds of character. At most 4.

Motion and sound

Motion

  • The steps of the meter change colour over 150 ms.
  • The button's background fades in over 150 ms on hover and a press scales it to 97%.
  • The eye loses or gains its stroke at once.
  • Reduced motion: every change happens at once.

Sound

  • Two rising clicks when the password is revealed and two falling clicks when it is hidden again.

Sound is off until the visitor turns it on. Pass sound={false} to keep this component silent. How sound works

Accessibility

  • It is a native input of type password that becomes type text while the password is readable, so password managers and autofill treat it as any password field.
  • The button is a toggle: it carries aria-pressed, and its name is Show password or Hide password after what a press does. The eye is struck through while the password is hidden.
  • Name the field with a label element. The meter is a separate element with the meter role, named Password strength, from 0 to 4, with the word as its value text.
  • The word next to the meter and the Caps Lock notice are polite live regions: a screen reader hears Password strength: Fair, and Caps Lock is on, when they change.
  • The meter fills in the text colour, not in red and green: the word says what the steps mean.
  • The component keeps the score and never the password. A readable password is hidden again when its form is submitted, so the browser does not save it as plain text, and spell checking is off.
KeysAction
TabFocus the field, then the show button.
Enter / SpaceOn the button: show or hide the password. The focus stays on the button.
Caps LockIn the field: the notice appears or leaves.

Source

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

import { useState, type ComponentProps } from "react";

import { cn } from "@/lib/utils";
import { play } from "@/lib/thrum-sound";
import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, type InputGroupSize } from "@/components/ui/input-group";
import { EyeIcon } from "@/components/icons/eye";
import { EyeOffIcon } from "@/components/icons/eye-off";

export type PasswordInputProps = Omit<ComponentProps<"input">, "type" | "size"> & {
  /** `sm` is 28 pixels tall, `md` 32, `lg` 40. */
  size?: InputGroupSize;
  /** Whether the password is readable, when the parent holds that state. Use it with `onVisibleChange`. */
  visible?: boolean;
  /** Whether the password starts readable, when the field holds that state itself. */
  defaultVisible?: boolean;
  /** Called with the new state when the show button is pressed, and with `false` when the form is submitted. */
  onVisibleChange?: (visible: boolean) => void;
  /** Show a four-step strength meter under the field, scored by `passwordStrength()`. */
  strength?: boolean;
  /** Say so under the field while Caps Lock is on and the field has the focus. */
  capsLockNotice?: boolean;
  /** Play a soft toggle sound when showing or hiding the password, if the visitor has sound on. */
  sound?: boolean;
};

const KINDS = [/[a-z]/, /[A-Z]/, /\d/, /[^A-Za-z0-9]/];
const WORDS = ["", "Weak", "Fair", "Good", "Strong"];
const STEPS = [1, 2, 3, 4];

/**
 * A rough score from 0 to 4, from length and variety alone. 0 is empty. Under 8 characters, or fewer than 5 different ones, is 1.
 * From there one point each for 12 characters, for 16, and for three kinds out of lower case, upper case, digits and symbols.
 * It knows no dictionary and no breach list: use it as a nudge, and check the password properly on the server.
 */
export function passwordStrength(value: string): number {
  if (!value) return 0;
  if (value.length < 8 || new Set(value).size < 5) return 1;
  const kinds = KINDS.filter((kind) => kind.test(value)).length;
  return Math.min(4, 1 + Number(value.length >= 12) + Number(value.length >= 16) + Number(kinds >= 3));
}

/**
 * A password field with a button that shows and hides what was typed. It is a native `<input>`, so password managers fill it.
 * The component keeps the score and never the password: nothing is logged, stored or sent.
 */
export function PasswordInput({
  size,
  visible,
  defaultVisible = false,
  onVisibleChange,
  strength = false,
  capsLockNotice = true,
  sound = true,
  className,
  value,
  defaultValue,
  disabled,
  autoComplete = "current-password",
  onChange,
  onKeyDown,
  onKeyUp,
  onBlur,
  ...props
}: PasswordInputProps) {
  const [shown, setShown] = useState(defaultVisible);
  const readable = visible ?? shown;
  const [typedScore, setTypedScore] = useState(() => passwordStrength(String(defaultValue ?? "")));
  const score = value !== undefined ? passwordStrength(String(value)) : typedScore;
  const [caps, setCaps] = useState(false);

  const show = (next: boolean) => {
    setShown(next);
    onVisibleChange?.(next);
  };

  return (
    <div data-slot="password-input" className={cn("grid w-full min-w-0 gap-1.5", className)}>
      <InputGroup size={size}>
        <InputGroupInput
          type={readable ? "text" : "password"}
          value={value}
          defaultValue={defaultValue}
          disabled={disabled}
          autoComplete={autoComplete}
          // A readable password is still not a word: keep it away from spell checkers and autocorrect.
          spellCheck={false}
          autoCapitalize="none"
          autoCorrect="off"
          onChange={(event) => {
            setTypedScore(passwordStrength(event.target.value));
            onChange?.(event);
          }}
          onKeyDown={(event) => {
            setCaps(event.getModifierState("CapsLock"));
            onKeyDown?.(event);
          }}
          onKeyUp={(event) => {
            setCaps(event.getModifierState("CapsLock"));
            onKeyUp?.(event);
          }}
          onBlur={(event) => {
            setCaps(false);
            onBlur?.(event);
          }}
          {...props}
        />
        <InputGroupAddon>
          <InputGroupButton
            aria-label={readable ? "Hide password" : "Show password"}
            aria-pressed={readable}
            disabled={disabled}
            sound={false}
            onClick={(event) => {
              const next = !readable;
              if (sound) play(next ? "toggleOn" : "toggleOff");
              // A form sent while the password is readable would let the browser remember it as plain text.
              if (!readable) event.currentTarget.form?.addEventListener("submit", () => show(false), { once: true });
              show(next);
            }}
          >
            {/* Struck through while the password is hidden, so the two states differ in shape. */}
            {readable ? <EyeIcon size={16} /> : <EyeOffIcon size={16} />}
          </InputGroupButton>
        </InputGroupAddon>
      </InputGroup>
      {strength && (
        <div data-slot="password-input-strength" className={cn("flex items-center gap-2", disabled && "opacity-50")}>
          <div role="meter" aria-label="Password strength" aria-valuemin={0} aria-valuemax={4} aria-valuenow={score} aria-valuetext={WORDS[score] || "No password"} className="grid h-1 flex-1 grid-cols-4 gap-1">
            {STEPS.map((step) => (
              <span
                key={step}
                className={cn("rounded-[calc(var(--radius)*9999)] transition-[background-color] duration-150 ease-out motion-reduce:transition-none", step <= score ? "bg-foreground" : "bg-border")}
              />
            ))}
          </div>
          {/* The word carries the state, so it never rests on how many steps are filled. It is announced when it changes. */}
          <span aria-live="polite" className="w-12 flex-none text-end text-xs leading-4 text-muted-foreground">
            {score > 0 && <span className="sr-only">Password strength: </span>}
            {WORDS[score]}
          </span>
        </div>
      )}
      {capsLockNotice && (
        // Always in the page, so a screen reader notices when it gets its text.
        <p data-slot="password-input-notice" aria-live="polite" className={caps ? "text-xs leading-4 font-medium text-foreground" : "sr-only"}>
          {caps ? "Caps Lock is on" : ""}
        </p>
      )}
    </div>
  );
}

Files and dependencies

Adds
components/ui/password-input.tsx
Packages
None
Brings along
Input groupSound engine
Icons
eyeeye-off

Changelog

  1. 1.0.0 · 2026-12-03First release.

Loading index…

Keyboard shortcuts

/Ctrl KSearch components, docs and actions
?Show this list
AAppearance studio
SSound on or off
MFull or reduced motion
TTheme: auto, light, dark
GSurface: solid or frosted
BBackdrop photograph (under glass)
CCorner radius: square to round
RReplay the demo, on a component page
DDraw new data, on a component page
←→HomeEndMove the cursor in a focused chart
EscClose a dialog, or leave a chart cursor