65 lines
2.0 KiB
TypeScript
65 lines
2.0 KiB
TypeScript
import { useId, useState, type InputHTMLAttributes } from "react";
|
|
import { Eye, EyeOff } from "lucide-react";
|
|
|
|
export type PasswordFieldProps = Omit<InputHTMLAttributes<HTMLInputElement>, "type" | "value" | "onChange"> & {
|
|
value: string;
|
|
onValueChange: (value: string) => void;
|
|
saved?: boolean;
|
|
savedPlaceholder?: string;
|
|
revealLabel?: string;
|
|
hideLabel?: string;
|
|
inputClassName?: string;
|
|
};
|
|
|
|
export default function PasswordField({
|
|
value,
|
|
onValueChange,
|
|
saved = false,
|
|
savedPlaceholder = "••••••••",
|
|
revealLabel = "Show password",
|
|
hideLabel = "Hide password",
|
|
placeholder,
|
|
disabled = false,
|
|
className = "",
|
|
inputClassName = "",
|
|
id,
|
|
...inputProps
|
|
}: PasswordFieldProps) {
|
|
const generatedId = useId();
|
|
const inputId = id ?? generatedId;
|
|
const [visible, setVisible] = useState(false);
|
|
const hasTypedPassword = value.length > 0;
|
|
const showSavedPlaceholder = saved && !hasTypedPassword;
|
|
const canReveal = hasTypedPassword && !disabled;
|
|
const inputType = visible && canReveal ? "text" : "password";
|
|
|
|
return (
|
|
<div className={`password-field ${canReveal ? "has-toggle" : ""} ${showSavedPlaceholder ? "is-saved-empty" : ""} ${className}`.trim()}>
|
|
<input
|
|
{...inputProps}
|
|
id={inputId}
|
|
className={inputClassName}
|
|
type={inputType}
|
|
value={value}
|
|
disabled={disabled}
|
|
placeholder={showSavedPlaceholder ? savedPlaceholder : placeholder}
|
|
onChange={(event) => {
|
|
onValueChange(event.target.value);
|
|
if (!event.target.value) setVisible(false);
|
|
}}
|
|
/>
|
|
{canReveal && (
|
|
<button
|
|
type="button"
|
|
className="password-field-toggle"
|
|
aria-label={visible ? hideLabel : revealLabel}
|
|
title={visible ? hideLabel : revealLabel}
|
|
onClick={() => setVisible((current) => !current)}
|
|
>
|
|
{visible ? <EyeOff size={17} aria-hidden="true" /> : <Eye size={17} aria-hidden="true" />}
|
|
</button>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|