Free Text Tag Input
Field where Enter, comma or Tab turns typed text into a removable chip inside the same bordered box. Duplicates are rejected with a brief highlight and pasted lists split into chips.
How it differs. Unconstrained chip entry in one wrapping box with delimiter keys, duplicate rejection and a two step Backspace, with no per-tag validation and no suggestion popup.
Install
pnpm dlx shadcn@latest add @hazine/tag-input-free-textAdds 1 file, 1 Hazine item (@hazine/use-controllable-state), and 1 package (lucide-react).
First time? Add the registry to components.json
{
"registries": {
"@hazine": "https://api.hazine.dev/r/{name}.json"
}
}Needed once per project. Items resolve each other through the @hazine namespace.
components/hazine/tag-input-free-text.tsx, 438 lines
"use client"
import * as React from "react"
import { CircleAlert, X } from "lucide-react"
import { cn } from "@/lib/utils"
import { useControllableState } from "@/hooks/use-controllable-state"
const INPUT_SELECTOR = '[data-slot="tag-input-free-text-input"]'
const REMOVE_SELECTOR = '[data-slot="tag-input-free-text-remove"]'
const SPLIT_PATTERN = /[,\n\t]+/
const FLASH_MS = 1500
const FIELD_CLASS =
"flex min-h-9 w-full cursor-text flex-wrap items-center gap-1 rounded-md border border-foreground/50 bg-transparent p-1 transition-colors duration-100 data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-[invalid=true]:border-destructive data-[readonly=true]:bg-muted/50"
const TAG_CLASS =
"inline-flex h-6 max-w-full min-w-0 items-center rounded-sm bg-muted ps-2 pe-2 text-sm text-foreground transition-colors duration-100 has-[button]:pe-0 data-[state=duplicate]:bg-primary data-[state=duplicate]:text-primary-foreground data-[state=selected]:bg-primary data-[state=selected]:text-primary-foreground"
const REMOVE_CLASS =
"flex size-6 shrink-0 items-center justify-center rounded-sm transition-colors duration-100 hover:bg-foreground/10 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-foreground active:bg-foreground/30 disabled:pointer-events-none"
const INPUT_CLASS =
"h-6 min-w-24 flex-1 rounded-sm bg-transparent px-1.5 text-base text-foreground placeholder:text-muted-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-foreground md:text-sm"
/** What the live region is about to say. Passed to `formatAnnouncement`. */
export type TagAnnouncement =
| { type: "added"; tags: string[]; skipped: number }
| { type: "removed"; tag: string }
| { type: "selected"; tag: string }
| { type: "duplicate"; tag: string }
| { type: "limit"; max: number }
function describeAnnouncement(announcement: TagAnnouncement) {
switch (announcement.type) {
case "added": {
const { tags, skipped } = announcement
const lead =
tags.length === 1 ? `${tags[0]} added.` : `${tags.length} tags added.`
if (skipped === 0) return lead
return `${lead} ${skipped} skipped as duplicate or over the limit.`
}
case "removed":
return `${announcement.tag} removed.`
case "selected":
return `${announcement.tag} selected. Press Backspace again to remove it.`
case "duplicate":
return `${announcement.tag} is already added.`
case "limit":
return `Limit of ${announcement.max} reached. Remove a tag to add another.`
}
}
function normalizeTag(raw: string) {
return raw.trim().replace(/\s+/g, " ")
}
/** Props are spread on the text input, not on the root. */
export interface TagInputFreeTextProps
extends Omit<React.ComponentProps<"input">, "type" | "value" | "defaultValue"> {
value?: string[]
defaultValue?: string[]
onValueChange?: (value: string[]) => void
/** Most tags the field accepts. Further entries are rejected and announced. */
max?: number
/** Line under the field that names the keys. Hidden when disabled or read-only. */
hint?: string
/** Accessible name of the list of tags. */
listLabel?: string
/** Start of each remove button name. The tag is appended: "Remove soil health". */
removeLabel?: string
/** Text at the end of the line under the field, for example "4 of 8 tags". */
formatCount?: (count: number, max: number | undefined) => string
formatAnnouncement?: (announcement: TagAnnouncement) => string
/** Used to compare tags without regard to case and to format the count. */
locale?: string
}
export function TagInputFreeText({
value,
defaultValue = [],
onValueChange,
max,
hint = "Enter, comma or Tab adds a tag",
listLabel = "Tags",
removeLabel = "Remove",
formatCount,
formatAnnouncement = describeAnnouncement,
locale = "en-US",
id,
name,
disabled = false,
readOnly = false,
required,
className,
onChange,
onKeyDown,
onPaste,
onBlur,
"aria-describedby": describedBy,
"aria-invalid": ariaInvalid,
...props
}: TagInputFreeTextProps) {
const generatedId = React.useId()
const inputId = id ?? generatedId
const hintId = `${inputId}-hint`
const countId = `${inputId}-count`
const [tags, setTags] = useControllableState({
value,
defaultValue,
onChange: onValueChange,
})
const [text, setText] = React.useState("")
const [armed, setArmed] = React.useState(false)
const [flash, setFlash] = React.useState<string | null>(null)
const [notice, setNotice] = React.useState<{
id: number
text: string
visible: boolean
} | null>(null)
const rootRef = React.useRef<HTMLDivElement>(null)
const flashTimer = React.useRef<ReturnType<typeof setTimeout> | null>(null)
const pendingFocus = React.useRef<number | null>(null)
const editable = !disabled && !readOnly
const limit = max ?? Number.POSITIVE_INFINITY
const invalid = ariaInvalid === true || ariaInvalid === "true"
const keyOf = (tag: string) => tag.toLocaleLowerCase(locale)
const number = new Intl.NumberFormat(locale)
const noun = tags.length === 1 ? "tag" : "tags"
const countText = formatCount
? formatCount(tags.length, max)
: max === undefined
? `${number.format(tags.length)} ${noun}`
: `${number.format(tags.length)} of ${number.format(max)} tags`
const visibleNotice = notice?.visible ? notice.text : null
React.useEffect(
() => () => {
if (flashTimer.current) clearTimeout(flashTimer.current)
},
[]
)
function focusInput() {
rootRef.current?.querySelector<HTMLInputElement>(INPUT_SELECTOR)?.focus()
}
function focusTag(index: number) {
const buttons =
rootRef.current?.querySelectorAll<HTMLButtonElement>(REMOVE_SELECTOR)
const target = buttons?.[Math.min(index, (buttons?.length ?? 0) - 1)]
if (target) target.focus()
else focusInput()
}
// After a keyboard removal, focus lands on the tag that took the place, or on the input.
React.useEffect(() => {
if (pendingFocus.current === null) return
const index = pendingFocus.current
pendingFocus.current = null
focusTag(index)
})
function announce(announcement: TagAnnouncement, visible: boolean) {
const message = formatAnnouncement(announcement)
setNotice((previous) => ({
id: (previous?.id ?? 0) + 1,
text: message,
visible,
}))
}
function settle() {
setArmed(false)
setNotice((previous) => (previous?.visible ? null : previous))
}
function flashTag(key: string) {
if (flashTimer.current) clearTimeout(flashTimer.current)
setFlash(key)
flashTimer.current = setTimeout(() => setFlash(null), FLASH_MS)
}
/** Returns true when at least one tag was added. */
function commit(candidates: string[]) {
const seen = new Map(tags.map((tag) => [keyOf(tag), tag]))
const accepted: string[] = []
let skipped = 0
let duplicate: string | null = null
for (const candidate of candidates) {
const tag = normalizeTag(candidate)
if (!tag) continue
const key = keyOf(tag)
if (seen.has(key)) {
skipped += 1
duplicate ??= key
} else if (tags.length + accepted.length >= limit) {
skipped += 1
} else {
seen.set(key, tag)
accepted.push(tag)
}
}
setArmed(false)
if (accepted.length > 0) {
setTags([...tags, ...accepted])
announce({ type: "added", tags: accepted, skipped }, skipped > 0)
return true
}
if (duplicate !== null) {
flashTag(duplicate)
announce({ type: "duplicate", tag: seen.get(duplicate) ?? duplicate }, true)
} else if (skipped > 0 && max !== undefined) {
announce({ type: "limit", max }, true)
}
return false
}
function removeAt(index: number, focusAfter: "tag" | "input") {
const tag = tags[index]
if (tag === undefined) return
setTags(tags.filter((_, position) => position !== index))
setArmed(false)
announce({ type: "removed", tag }, false)
if (focusAfter === "tag") pendingFocus.current = index
else focusInput()
}
function handleChange(event: React.ChangeEvent<HTMLInputElement>) {
onChange?.(event)
const next = event.target.value
settle()
// Commas are split here and not on keydown, so on-screen keyboards work too.
if (!next.includes(",")) {
setText(next)
return
}
const parts = next.split(",")
const rest = parts.pop() ?? ""
setText(commit(parts) ? rest.trimStart() : normalizeTag(next.replace(/,/g, " ")))
}
function handlePaste(event: React.ClipboardEvent<HTMLInputElement>) {
onPaste?.(event)
if (event.defaultPrevented || !editable) return
const pasted = event.clipboardData.getData("text")
if (!SPLIT_PATTERN.test(pasted)) return
event.preventDefault()
const start = event.currentTarget.selectionStart ?? text.length
const end = event.currentTarget.selectionEnd ?? start
const merged = `${text.slice(0, start)}${pasted}${text.slice(end)}`
// A paste that adds nothing leaves the typed text as it was.
if (commit(merged.split(SPLIT_PATTERN))) setText("")
}
function handleKeyDown(event: React.KeyboardEvent<HTMLInputElement>) {
onKeyDown?.(event)
if (event.defaultPrevented || !editable || event.nativeEvent.isComposing) return
const input = event.currentTarget
const rtl = getComputedStyle(input).direction === "rtl"
const atStart = input.selectionStart === 0 && input.selectionEnd === 0
const hasText = text.trim() !== ""
if (event.key === "Backspace" && text === "" && tags.length > 0) {
event.preventDefault()
// A held Backspace that just emptied the text must not run on into the tags.
if (event.repeat) return
if (armed) {
removeAt(tags.length - 1, "input")
} else {
setArmed(true)
announce({ type: "selected", tag: tags[tags.length - 1] ?? "" }, true)
}
return
}
if (armed) settle()
if (event.key === "Enter" && hasText) {
// Enter only submits the surrounding form once the text is empty.
event.preventDefault()
if (commit([text])) setText("")
} else if (event.key === "Tab" && !event.shiftKey && hasText) {
// A rejected entry lets Tab move on, so the field never traps focus.
if (commit([text])) {
event.preventDefault()
setText("")
}
} else if (event.key === (rtl ? "ArrowRight" : "ArrowLeft") && atStart && tags.length > 0) {
event.preventDefault()
// The focus outline of a remove button is drawn for the resting fill.
setFlash(null)
focusTag(tags.length - 1)
}
}
function handleTagKeyDown(event: React.KeyboardEvent<HTMLButtonElement>, index: number) {
const rtl = getComputedStyle(event.currentTarget).direction === "rtl"
const back = rtl ? "ArrowRight" : "ArrowLeft"
const forward = rtl ? "ArrowLeft" : "ArrowRight"
if (event.key === back || event.key === forward || event.key === "Home" || event.key === "End") {
event.preventDefault()
if (event.key === back) focusTag(Math.max(index - 1, 0))
else if (event.key === "Home") focusTag(0)
else if (event.key === "End" || index === tags.length - 1) focusInput()
else focusTag(index + 1)
} else if (event.key === "Backspace" || event.key === "Delete") {
event.preventDefault()
removeAt(index, "tag")
} else if (event.key === "Escape") {
focusInput()
} else if (event.key.length === 1 && event.key !== " " && !event.ctrlKey && !event.metaKey && !event.altKey) {
// Typing while a tag is focused continues in the text input.
focusInput()
}
}
return (
<div
ref={rootRef}
data-slot="tag-input-free-text"
className={cn("flex w-full flex-col gap-1.5", className)}
>
<div
data-slot="tag-input-free-text-field"
data-disabled={disabled || undefined}
data-readonly={readOnly || undefined}
data-invalid={invalid || undefined}
className={FIELD_CLASS}
// Pointer convenience only: the gaps between tags lead to the text input.
onPointerDown={(event) => {
if (event.target !== event.currentTarget) return
event.preventDefault()
focusInput()
}}
>
{tags.length > 0 && (
<ul aria-label={listLabel} className="contents">
{tags.map((tag, index) => {
const key = keyOf(tag)
const last = index === tags.length - 1
return (
<li
key={key}
data-slot="tag-input-free-text-tag"
data-state={
flash === key ? "duplicate" : armed && last ? "selected" : undefined
}
className={TAG_CLASS}
>
<span className="truncate" title={tag}>
{tag}
</span>
{!readOnly && (
<button
type="button"
// One tab stop for the field. Arrow keys reach the tags from the input.
tabIndex={-1}
data-slot="tag-input-free-text-remove"
aria-label={`${removeLabel} ${tag}`}
disabled={disabled}
className={REMOVE_CLASS}
onClick={(event) =>
removeAt(index, event.detail === 0 ? "tag" : "input")
}
onKeyDown={(event) => handleTagKeyDown(event, index)}
>
<X aria-hidden="true" className="size-3.5" />
</button>
)}
</li>
)
})}
</ul>
)}
<input
id={inputId}
type="text"
data-slot="tag-input-free-text-input"
value={text}
disabled={disabled}
readOnly={readOnly}
// The text is empty once tags exist, so native validation only asks while there are none.
required={required && tags.length === 0}
aria-required={required}
autoComplete="off"
autoCapitalize="none"
enterKeyHint="done"
aria-invalid={ariaInvalid}
aria-describedby={
[describedBy, editable && hint ? hintId : null, countId]
.filter(Boolean)
.join(" ") || undefined
}
className={INPUT_CLASS}
onChange={handleChange}
onKeyDown={handleKeyDown}
onPaste={handlePaste}
onBlur={(event) => {
onBlur?.(event)
settle()
}}
{...props}
/>
{name !== undefined &&
tags.map((tag) => (
<input key={keyOf(tag)} type="hidden" name={name} value={tag} disabled={disabled} />
))}
</div>
<div className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1 text-xs text-muted-foreground">
{visibleNotice !== null && (
<p
aria-hidden="true"
data-slot="tag-input-free-text-notice"
className="flex min-w-0 items-center gap-1.5 font-medium text-foreground"
>
<CircleAlert aria-hidden="true" className="size-3.5 shrink-0" />
{visibleNotice}
</p>
)}
{editable && hint && (
<p id={hintId} className={cn(visibleNotice !== null && "sr-only")}>
{hint}
</p>
)}
<p
id={countId}
data-slot="tag-input-free-text-count"
className={cn(
"ms-auto shrink-0 tabular-nums",
tags.length >= limit && "font-medium text-foreground"
)}
>
{countText}
</p>
</div>
<p role="status" className="sr-only">
{notice !== null && <span key={notice.id}>{notice.text}</span>}
</p>
</div>
)
}
The demo in the preview, 209 lines
"use client"
import * as React from "react"
import { CircleAlert } from "lucide-react"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { TagInputFreeText } from "@/components/hazine/tag-input-free-text"
const SAVED_TOPICS = ["soil health", "cover crops", "no-till", "market gardening"]
const TOPIC_LIMIT = 8
const ARCHIVE_TOPICS = [
"soil health",
"cover crops",
"no-till",
"market gardening",
"composting",
"crop rotation",
"drip irrigation",
"seed saving",
"high tunnels",
"farm accounting",
"community supported agriculture subscriptions",
"wash and pack",
"regenerative-agriculture-certification-standards-for-smallholders",
"pollinator strips",
]
function formatTopicCount(count: number, max: number | undefined) {
const noun = count === 1 ? "topic" : "topics"
return max === undefined ? `${count} ${noun}` : `${count} of ${max} topics`
}
export default function TagInputFreeTextDemo() {
const id = React.useId()
const [saved, setSaved] = React.useState(SAVED_TOPICS)
const [topics, setTopics] = React.useState(SAVED_TOPICS)
const added = topics.filter((topic) => !saved.includes(topic)).length
const removed = saved.filter((topic) => !topics.includes(topic)).length
const changes = [
added > 0 ? `${added} added` : null,
removed > 0 ? `${removed} removed` : null,
].filter(Boolean)
const reordered = changes.length === 0 && topics.join() !== saved.join()
const dirty = changes.length > 0 || reordered
return (
<div className="grid w-full max-w-md gap-2">
<Label htmlFor={id}>Topics</Label>
<p className="text-sm text-muted-foreground">
<span className="font-medium text-foreground">
Episode 48 is filed under {formatTopicCount(saved.length, undefined)}.
</span>{" "}
Listeners filter the archive by these.
</p>
<TagInputFreeText
id={id}
value={topics}
onValueChange={setTopics}
max={TOPIC_LIMIT}
placeholder="Add a topic"
hint="Enter, comma or Tab adds a topic"
listLabel="Topics"
formatCount={formatTopicCount}
/>
<div className="mt-2 flex flex-wrap items-center gap-3">
<Button type="button" onClick={() => setSaved(topics)}>
Save {formatTopicCount(topics.length, undefined)}
</Button>
<p className="text-sm tabular-nums text-muted-foreground">
{dirty
? `${reordered ? "Order changed" : changes.join(", ")} since the last save`
: "No unsaved changes"}
</p>
</div>
</div>
)
}
function TagInputFreeTextEmpty() {
const id = React.useId()
return (
<div className="grid w-full max-w-md gap-2">
<Label htmlFor={id}>Topics</Label>
<TagInputFreeText
id={id}
max={TOPIC_LIMIT}
placeholder="Add a topic, for example soil health"
hint="Enter, comma or Tab adds a topic"
listLabel="Topics"
formatCount={formatTopicCount}
/>
</div>
)
}
function TagInputFreeTextInvalid() {
const id = React.useId()
const errorId = React.useId()
const [topics, setTopics] = React.useState<string[]>([])
const missing = topics.length === 0
return (
<div className="grid w-full max-w-md gap-2">
<Label htmlFor={id}>Topics</Label>
<TagInputFreeText
id={id}
value={topics}
onValueChange={setTopics}
max={TOPIC_LIMIT}
placeholder="Add a topic"
hint="Enter, comma or Tab adds a topic"
listLabel="Topics"
formatCount={formatTopicCount}
aria-invalid={missing}
aria-describedby={missing ? errorId : undefined}
/>
{missing && (
<p id={errorId} className="flex items-center gap-1.5 text-sm text-destructive">
<CircleAlert aria-hidden="true" className="size-3.5 shrink-0" />
Add at least one topic so listeners can find this episode.
</p>
)}
</div>
)
}
function TagInputFreeTextDisabled() {
const id = React.useId()
return (
<div className="grid w-full max-w-md gap-2">
<Label htmlFor={id}>Topics</Label>
<TagInputFreeText
id={id}
defaultValue={SAVED_TOPICS}
max={TOPIC_LIMIT}
listLabel="Topics"
formatCount={formatTopicCount}
disabled
/>
<p className="text-xs text-muted-foreground">
Episode 48 is being published. Topics can be edited again in a few
minutes.
</p>
</div>
)
}
function TagInputFreeTextReadOnly() {
const id = React.useId()
return (
<div className="grid w-full max-w-md gap-2">
<Label htmlFor={id}>Topics</Label>
<TagInputFreeText
id={id}
defaultValue={SAVED_TOPICS}
listLabel="Topics"
formatCount={formatTopicCount}
readOnly
/>
<p className="text-xs text-muted-foreground">
Imported from the show feed. Edit topics in your podcast host.
</p>
</div>
)
}
function TagInputFreeTextOverflow() {
const id = React.useId()
return (
<div className="grid w-full max-w-md gap-2">
<Label htmlFor={id}>Archive topics</Label>
<TagInputFreeText
id={id}
defaultValue={ARCHIVE_TOPICS}
placeholder="Add a topic"
hint="Enter, comma or Tab adds a topic"
listLabel="Archive topics"
formatCount={formatTopicCount}
/>
</div>
)
}
function TagInputFreeTextLimit() {
const id = React.useId()
return (
<div className="grid w-full max-w-md gap-2">
<Label htmlFor={id}>Topics</Label>
<TagInputFreeText
id={id}
defaultValue={ARCHIVE_TOPICS.slice(0, TOPIC_LIMIT)}
max={TOPIC_LIMIT}
hint="Remove a topic to add another"
listLabel="Topics"
formatCount={formatTopicCount}
/>
</div>
)
}
export const scenarios = {
empty: TagInputFreeTextEmpty,
invalid: TagInputFreeTextInvalid,
disabled: TagInputFreeTextDisabled,
"read-only": TagInputFreeTextReadOnly,
overflow: TagInputFreeTextOverflow,
limit: TagInputFreeTextLimit,
}
Props10
- value
- string[]
- defaultValue
- string[] = []
- onValueChange
- (value: string[]) => void
- max
- number
- Most tags the field accepts. Further entries are rejected and announced.
- hint
- string = "Enter, comma or Tab adds a tag"
- Line under the field that names the keys. Hidden when disabled or read-only.
- listLabel
- string = "Tags"
- Accessible name of the list of tags.
- removeLabel
- string = "Remove"
- Start of each remove button name. The tag is appended: "Remove soil health".
- formatCount
- (count: number, max: number | undefined) => string
- Text at the end of the line under the field, for example "4 of 8 tags".
- formatAnnouncement
- (announcement: TagAnnouncement) => string = describeAnnouncement
- locale
- string = "en-US"
- Used to compare tags without regard to case and to format the count.
Also accepts every prop of Omit<React.ComponentProps<"input">, "type" | "value" | "defaultValue">.
Accessibility
- Pattern
- Form with labelled fields, Button (APG, opens in a new tab)
- Keyboard
Keyboard support for Free Text Tag Input Key Effect Tab Focuses the text input. With text typed it adds the tag and stays in the field. With no text, or when the entry is rejected, it moves on Enter Adds the typed text as a tag. With no text it is left to the surrounding form Comma Adds the text before it as a tag Backspace in the empty input Selects the last tag, and a second press removes it. A held key stops at the empty input. Any other key or leaving the field clears the selection Arrow Left at the start of the input Moves focus to the remove button of the last tag (Arrow Right in right to left layouts) Arrow Left, Arrow Right on a tag Moves between tags. Moving past the last tag returns to the input. The two keys swap in right to left layouts Home, End on a tag Moves to the first tag or back to the input Enter, Space, Backspace or Delete on a tag Removes the tag and moves focus to the tag that takes its place, or to the input when none is left Escape on a tag Returns focus to the input A letter or digit on a tag Returns focus to the input and types the character there Paste Text with commas, tabs or line breaks is split into tags at the caret. Duplicates and entries over the limit are skipped and counted. When nothing is added the typed text stays - Screen reader
A native text input the consumer labels, after a labelled list of tags that each hold a remove button named after the tag. The field is one tab stop, arrow keys reach the tags, and every addition, removal, duplicate and limit is announced in a polite status region.
- Announces: {tag} added.
- Announces: {count} tags added.
- Announces: {count} tags added. {skipped} skipped as duplicate or over the limit.
- Announces: {tag} removed.
- Announces: {tag} selected. Press Backspace again to remove it.
- Announces: {tag} is already added.
- Announces: Limit of {max} reached. Remove a tag to add another.
- Reduced motion
- No motion. Colour transitions only. The duplicate highlight is a steady inverted fill for 1.5 seconds.
- Checked
- Not checked yet. Automated results appear here once CI has run.
Dependencies2
- @hazine/use-controllable-state
- lucide-react
Filled chips are registry items the CLI adds for you. Outlined chips are npm packages.
Tokens shipped0
None. The item is styled by the tokens your theme already has.