Sensitive input
82 lines · 1 file · MIT
A key or secret, masked, with buttons to show it and copy it.
import { useEffect, useRef, useState } from "react";
import { MorphIcon } from "morphicons/react";
import { Eye, EyeOff } from "./icons";
import { check, copy } from "./icon-nodes";
import { IconButton } from "./button";
import { cn } from "./cn";
/**
* A secret on one line: masked by default, with buttons to reveal it and to
* copy it. The value is mono, since a wrong character costs the reader.
* Copying works while it is masked, so a key never has to be shown to be
* used. `onCopy` is yours (the clipboard call and its toast).
*/
export function SensitiveInput({
value,
label,
onCopy,
className,
}: {
value: string;
/** What it is, for the buttons: "API key" gives "Show API key". */
label: string;
onCopy: (value: string) => void | Promise<void>;
className?: string;
}) {
const [shown, setShown] = useState(false);
const [copied, setCopied] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => () => void (timer.current && clearTimeout(timer.current)), []);
const copyValue = async () => {
try {
await onCopy(value);
if (timer.current) clearTimeout(timer.current);
timer.current = setTimeout(() => setCopied(false), 2000);
setCopied(true);
} catch {
// The caller reports clipboard errors in its own toast.
}
};
return (
<span
className={cn(
"flex h-9 w-full min-w-0 items-center gap-1 rounded-lg bg-surface py-1 pr-1 pl-3 smooth-shadow-ring-xs",
className,
)}
>
<input
readOnly
type="text"
aria-label={label}
value={shown ? value : "•".repeat(Math.min(value.length, 32))}
onFocus={(e) => e.currentTarget.select()}
autoComplete="off"
spellCheck={false}
// A text input with bullets, not type="password": a password manager
// would offer to save it as a login.
data-1p-ignore
data-lpignore="true"
data-bwignore
className="h-full min-w-0 flex-1 bg-transparent font-mono text-[13px] text-text outline-none"
/>
<IconButton
label={shown ? `Hide ${label}` : `Show ${label}`}
aria-pressed={shown}
onClick={() => setShown((s) => !s)}
>
{shown ? <EyeOff size={14} /> : <Eye size={14} />}
</IconButton>
<IconButton label={`Copy ${label}`} onClick={copyValue}>
<MorphIcon
icon={copied ? check : copy}
size={12}
spring="snappy"
className={copied ? "text-accent-2" : undefined}
/>
</IconButton>
</span>
);
}
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/sensitive-input- Category
- Forms
- Files
- sensitive-input.tsx
- Brings in
- morphicons