Tag input
210 lines · 1 file · MIT
Several values in one box: each becomes a chip on comma, space or Enter, and a pasted list splits at once.
import { forwardRef, useId, useState, type ClipboardEvent, type KeyboardEvent } from "react";
import { X } from "./icons";
import { cn } from "./cn";
import { NO_AUTOFILL } from "./field";
import { OverflowTip } from "./overflow-tip";
/** Splits typed or pasted text at commas, semicolons and whitespace. */
const splitValues = (text: string) => text.split(/[,;\s]+/).filter(Boolean);
/**
* Several values in one box: each one becomes a chip as soon as a comma, a
* space or Enter ends it, and a pasted list splits into chips at once.
* Backspace in the empty input takes the last chip back out to edit.
*
* Pass `validate` to mark the chips that are wrong while `error` is set.
* Built to sit where a Field would: the label row carries the reason on the
* right, and nothing below the box moves.
*/
export const TagInput = forwardRef<
HTMLInputElement,
{
label: string;
values: string[];
onChange: (values: string[]) => void;
/** True for a good value. Bad chips are outlined once `error` is set. */
validate?: (value: string) => boolean;
/** The text not yet turned into a chip. Pass it (with `onDraftChange`)
* so a submit can count it too; left out, the box keeps it itself. */
draft?: string;
onDraftChange?: (draft: string) => void;
error?: string;
placeholder?: string;
/** Set the chips in the mono face, for identifiers and addresses. */
mono?: boolean;
inputMode?: "text" | "email" | "url" | "numeric";
}
>(
(
{
label,
values,
onChange,
validate,
draft: draftProp,
onDraftChange,
error,
placeholder,
mono,
inputMode = "text",
},
ref,
) => {
const inputId = useId();
const reasonId = useId();
const [focused, setFocused] = useState(false);
const [ownDraft, setOwnDraft] = useState("");
const draft = draftProp ?? ownDraft;
const setDraft = onDraftChange ?? setOwnDraft;
const commit = (text: string) => {
const next = splitValues(text);
if (next.length === 0) return;
onChange(unique([...values, ...next]));
setDraft("");
};
const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
if ((e.key === "," || e.key === ";" || e.key === " " || e.key === "Enter") && draft.trim()) {
e.preventDefault();
commit(draft);
return;
}
if (e.key === "Backspace" && !draft && values.length > 0) {
e.preventDefault();
onChange(values.slice(0, -1));
setDraft(values[values.length - 1]);
}
};
const onPaste = (e: ClipboardEvent<HTMLInputElement>) => {
const text = e.clipboardData.getData("text");
if (splitValues(text).length < 2) return;
e.preventDefault();
commit(`${draft} ${text}`);
};
return (
<div className="min-w-0">
<span className="mb-1.5 flex h-4 items-center gap-1.5 text-xs text-muted">
<label htmlFor={inputId}>{label}</label>
{error && (
<OverflowTip content={error}>
<span
id={reasonId}
className="ml-auto flex min-w-0 items-center gap-1 truncate text-danger"
>
<X aria-hidden size={11} stroke={2.5} className="shrink-0" />
<span className="truncate">{error}</span>
</span>
</OverflowTip>
)}
</span>
{/* Clicking anywhere in the box puts the caret in the input, as a
real field would. */}
{/* oxlint-disable-next-line jsx-a11y/click-events-have-key-events -- the input inside is the keyboard target; this only forwards pointer clicks to it. */}
<div
role="presentation"
onClick={(e) => {
if (e.target === e.currentTarget)
document.getElementById(inputId)?.focus({ preventScroll: true });
}}
className={cn(
"flex min-h-[76px] w-full cursor-text flex-wrap content-start items-center gap-1.5 rounded-lg bg-surface p-2 transition-[box-shadow] duration-150",
focused
? "shadow-[0_0_0_1.5px_var(--accent),0_0_0_4px_color-mix(in_oklab,var(--accent)_25%,transparent)]"
: error
? "shadow-[0_0_0_1.5px_var(--danger)]"
: "smooth-shadow-ring-xs",
)}
>
{values.map((value) => (
<Chip
key={value}
value={value}
mono={mono}
bad={Boolean(error) && validate !== undefined && !validate(value)}
onRemove={() => onChange(values.filter((v) => v !== value))}
/>
))}
<input
ref={ref}
id={inputId}
type="text"
inputMode={inputMode}
autoComplete="off"
{...NO_AUTOFILL}
autoCapitalize="none"
spellCheck={false}
value={draft}
onChange={(e) => {
const value = e.target.value;
// A comma typed on a phone keyboard arrives here, not as a key.
if (/[,;\s]$/.test(value)) commit(value);
else setDraft(value);
}}
onKeyDown={onKeyDown}
onPaste={onPaste}
onFocus={() => setFocused(true)}
onBlur={() => {
setFocused(false);
commit(draft);
}}
aria-invalid={error ? true : undefined}
aria-describedby={error ? reasonId : undefined}
placeholder={values.length === 0 ? placeholder : "Add more, separated by commas"}
className={cn(
"h-7 min-w-[12rem] flex-1 bg-transparent px-1 text-sm text-text outline-none! placeholder:text-placeholder",
mono && "font-mono text-[13px] placeholder:font-sans placeholder:text-sm",
)}
/>
</div>
</div>
);
},
);
TagInput.displayName = "TagInput";
function Chip({
value,
bad,
mono,
onRemove,
}: {
value: string;
bad: boolean;
mono?: boolean;
onRemove: () => void;
}) {
return (
<span
className={cn(
"inline-flex h-7 max-w-full items-center gap-1 rounded-md bg-surface-2 pr-0.5 pl-2",
bad && "text-danger shadow-[inset_0_0_0_1px_var(--danger)]",
)}
>
<OverflowTip content={value}>
<span className={cn("truncate text-xs", mono && "font-mono")}>{value}</span>
</OverflowTip>
<button
type="button"
aria-label={`Remove ${value}`}
onClick={onRemove}
className="relative grid size-6 shrink-0 cursor-pointer place-items-center rounded-[5px] text-muted transition-[background-color,color] duration-150 [@media(hover:hover)]:hover:bg-surface [@media(hover:hover)]:hover:text-text"
>
<X size={12} />
</button>
</span>
);
}
function unique(list: string[]): string[] {
const seen = new Set<string>();
return list.filter((v) => {
const key = v.toLowerCase();
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
Install
One command. The files land in your repo, with everything they import.
$ bunx shadcn@latest add @blocco/tag-input- Category
- Forms
- Files
- tag-input.tsx