{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tag-input",
  "title": "Tag input",
  "description": "Chips input where Enter, comma or paste adds tags that spring in, Backspace arms then removes, duplicates shake, with a filtered suggestions dropdown, validation and a max count.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/inputs/tag-input.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, motion, useAnimate, useReducedMotion } from \"motion/react\"\nimport { X } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, spring } from \"@/lib/goodui-motion\"\n\nconst SHAKE = { x: [0, -6, 6, -4, 4, -2, 0] }\n\nexport type TagInputLabels = {\n  remove: (tag: string) => string\n  duplicate: (tag: string) => string\n  limit: (max: number) => string\n  added: (tag: string) => string\n  addedMany: (count: number) => string\n  removed: (tag: string) => string\n  /** Accessible name of the text input when no aria-label is passed. */\n  input: string\n}\nconst DEFAULT_LABELS: TagInputLabels = {\n  remove: (tag) => `Remove ${tag}`,\n  duplicate: (tag) => `“${tag}” is already added`,\n  limit: (max) => `You can add up to ${max}`,\n  added: (tag) => `Added ${tag}`,\n  addedMany: (count) => `Added ${count} tags`,\n  removed: (tag) => `Removed ${tag}`,\n  input: \"Add tags\",\n}\n\nexport type TagInputProps = Omit<React.ComponentProps<\"div\">, \"onChange\" | \"defaultValue\"> & {\n  /** Controlled list of tags. Pair with `onValueChange`. */\n  value?: string[]\n  /** Initial tags when uncontrolled. */\n  defaultValue?: string[]\n  /** Called with the full new list whenever a tag is added or removed. */\n  onValueChange?: (tags: string[]) => void\n  /** Offered in a dropdown while typing. Already-added tags are hidden. */\n  suggestions?: string[]\n  /** Maximum number of tags; shows an \"n/max\" counter and makes the input read-only when full. */\n  maxTags?: number\n  /** Shown only while there are no tags. */\n  placeholder?: string\n  /** Return `true` to accept, or an error message to reject the tag. */\n  validate?: (tag: string) => true | string\n  /** Treat \"Design\" and \"design\" as different tags. */\n  caseSensitive?: boolean\n  /** Form field name; tags are submitted comma-separated in a hidden input. */\n  name?: string\n  disabled?: boolean\n  /** id of the text input, for an external `<label htmlFor>`. */\n  inputId?: string\n  /** Optional visual for each chip (an icon, an avatar…). */\n  renderTag?: (tag: string) => React.ReactNode\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<TagInputLabels>\n}\n\ntype ChipProps = {\n  tag: string\n  removeLabel: string\n  armed: boolean\n  shakeNonce: number\n  disabled?: boolean\n  reduce: boolean\n  onRemove: () => void\n  children?: React.ReactNode\n  /** Forwarded so AnimatePresence \"popLayout\" can measure the leaving chip. */\n  ref?: React.Ref<HTMLSpanElement>\n}\n\nfunction Chip({ tag, removeLabel, armed, shakeNonce, disabled, reduce, onRemove, children, ref }: ChipProps) {\n  const [scope, animate] = useAnimate<HTMLSpanElement>()\n  React.useEffect(() => {\n    if (!shakeNonce || !scope.current) return\n    if (reduce) return\n    animate(scope.current, SHAKE, { duration: 0.4, ease: \"easeInOut\" })\n  }, [shakeNonce, animate, scope, reduce])\n\n  return (\n    <motion.span\n      ref={ref}\n      layout={!reduce}\n      initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, filter: \"blur(4px)\" }}\n      animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n      exit={reduce ? { opacity: 0, transition: { duration: 0.1 } } : { opacity: 0, scale: 0.6, filter: \"blur(4px)\", transition: { duration: 0.15 } }}\n      transition={reduce ? { duration: 0.12 } : spring.ui}\n      className=\"inline-flex\"\n    >\n      <span\n        ref={scope}\n        data-armed={armed || undefined}\n        data-shake={shakeNonce > 0 || undefined}\n        className={cn(\n          \"inline-flex h-7 max-w-[16rem] items-center gap-1 rounded-md border bg-muted/70 ps-2 pe-1 text-sm font-medium text-foreground transition-colors\",\n          \"data-armed:border-primary data-armed:bg-primary/10 data-armed:ring-2 data-armed:ring-primary/30\",\n        )}\n      >\n        {children}\n        <span className=\"truncate\">{tag}</span>\n        <button\n          type=\"button\"\n          disabled={disabled}\n          aria-label={removeLabel}\n          onClick={onRemove}\n          className=\"pc-press grid size-5 place-items-center rounded-sm text-muted-foreground transition-colors outline-none hover:bg-foreground/10 hover:text-foreground focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none\"\n        >\n          <X className=\"size-3.5\" />\n        </button>\n      </span>\n    </motion.span>\n  )\n}\n\n/** Chips input: Enter or comma adds, Backspace removes, paste splits, duplicates shake, suggestions dropdown. */\nexport function TagInput({\n  value,\n  defaultValue,\n  onValueChange,\n  suggestions = [],\n  maxTags,\n  placeholder = \"Add a tag…\",\n  validate,\n  caseSensitive = false,\n  name,\n  disabled,\n  inputId,\n  renderTag,\n  labels,\n  className,\n  \"aria-label\": ariaLabel,\n  ...props\n}: TagInputProps) {\n  const l = useLabels(\"tag-input\", DEFAULT_LABELS, labels)\n  const reduce = useReducedMotion() ?? false\n  const [inner, setInner] = React.useState<string[]>(defaultValue ?? [])\n  const tags = value ?? inner\n  const [text, setText] = React.useState(\"\")\n  const [open, setOpen] = React.useState(false)\n  const [active, setActive] = React.useState(-1)\n  const [armed, setArmed] = React.useState(false)\n  const [shake, setShake] = React.useState<{ tag: string; n: number } | null>(null)\n  const [error, setError] = React.useState<string | null>(null)\n  const [announce, setAnnounce] = React.useState(\"\")\n  const inputRef = React.useRef<HTMLInputElement>(null)\n  const [fieldScope, animateField] = useAnimate<HTMLDivElement>()\n  const uid = React.useId()\n  const listId = `${uid}-list`\n  const errorId = `${uid}-error`\n\n  const norm = React.useCallback((t: string) => (caseSensitive ? t : t.toLowerCase()), [caseSensitive])\n  const full = maxTags !== undefined && tags.length >= maxTags\n\n  const commit = (next: string[]) => {\n    if (value === undefined) setInner(next)\n    onValueChange?.(next)\n  }\n\n  const shakeField = () => {\n    if (!reduce && fieldScope.current) animateField(fieldScope.current, SHAKE, { duration: 0.4 })\n  }\n\n  /** Adds the given raw strings, returns how many were added. */\n  const add = (raw: string[]) => {\n    const next = [...tags]\n    let lastError: string | null = null\n    for (const r of raw) {\n      const t = r.trim()\n      if (!t) continue\n      const dup = next.find((x) => norm(x) === norm(t))\n      if (dup) {\n        setShake((s) => ({ tag: dup, n: (s?.n ?? 0) + 1 }))\n        lastError = l.duplicate(dup)\n        continue\n      }\n      if (maxTags !== undefined && next.length >= maxTags) {\n        lastError = l.limit(maxTags)\n        shakeField()\n        break\n      }\n      const ok = validate ? validate(t) : true\n      if (ok !== true) {\n        lastError = ok\n        shakeField()\n        continue\n      }\n      next.push(t)\n    }\n    const added = next.length - tags.length\n    if (added > 0) {\n      commit(next)\n      setAnnounce(added === 1 ? l.added(next[next.length - 1]!) : l.addedMany(added))\n    }\n    setError(lastError)\n    if (lastError) setAnnounce(lastError)\n    return added\n  }\n\n  const remove = (tag: string) => {\n    commit(tags.filter((t) => t !== tag))\n    // Forget a pending shake so the tag doesn't shake on mount if it is added again later.\n    setShake((s) => (s && s.tag === tag ? null : s))\n    setAnnounce(l.removed(tag))\n    setArmed(false)\n    setError(null)\n    inputRef.current?.focus()\n  }\n\n  const filtered = React.useMemo(() => {\n    const q = norm(text.trim())\n    const taken = new Set(tags.map(norm))\n    return suggestions.filter((s) => !taken.has(norm(s)) && (!q || norm(s).includes(q))).slice(0, 6)\n  }, [suggestions, tags, text, norm])\n\n  const showList = open && !full && filtered.length > 0 && !disabled\n\n  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    if (e.nativeEvent.isComposing) return\n    if (e.key === \"Enter\" || e.key === \",\") {\n      const pick = (showList && active >= 0 ? filtered[active] : text) ?? text\n      if (!pick.trim()) {\n        if (e.key === \",\") e.preventDefault()\n        return\n      }\n      e.preventDefault()\n      const taken = tags.some((t) => norm(t) === norm(pick.trim()))\n      // Keep rejected text so it can be fixed; clear it when it was added or is a duplicate.\n      if (add([pick]) > 0 || taken) setText(\"\")\n      setActive(-1)\n      return\n    }\n    if (e.key === \"Backspace\" && text === \"\" && tags.length > 0) {\n      e.preventDefault()\n      if (armed) remove(tags[tags.length - 1]!)\n      else setArmed(true)\n      return\n    }\n    if (e.key === \"ArrowDown\" && filtered.length) {\n      e.preventDefault()\n      setOpen(true)\n      setActive((a) => (a + 1) % filtered.length)\n      return\n    }\n    if (e.key === \"ArrowUp\" && filtered.length) {\n      e.preventDefault()\n      setOpen(true)\n      setActive((a) => (a <= 0 ? filtered.length - 1 : a - 1))\n      return\n    }\n    if (e.key === \"Escape\") {\n      if (showList) {\n        e.preventDefault()\n        setOpen(false)\n        setActive(-1)\n      }\n      return\n    }\n    setArmed(false)\n  }\n\n  const onPaste = (e: React.ClipboardEvent<HTMLInputElement>) => {\n    const data = e.clipboardData.getData(\"text\")\n    if (!/[,\\n\\t;]/.test(data)) return\n    e.preventDefault()\n    add(data.split(/[,\\n\\t;]+/))\n    setText(\"\")\n  }\n\n  return (\n    <div className={cn(\"relative w-full\", className)} {...props}>\n      <GooduiTokens />\n      <div\n        ref={fieldScope}\n        onClick={() => inputRef.current?.focus()}\n        data-invalid={error ? true : undefined}\n        data-disabled={disabled || undefined}\n        className={cn(\n          \"flex min-h-10 w-full cursor-text flex-wrap items-center gap-1.5 rounded-lg border border-input bg-background px-1.5 py-1.5 text-sm shadow-xs transition-[border-color,box-shadow] dark:bg-input/30\",\n          \"focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50\",\n          \"data-invalid:border-destructive data-invalid:focus-within:ring-destructive/20\",\n          \"data-disabled:cursor-not-allowed data-disabled:opacity-50\",\n        )}\n      >\n        <AnimatePresence initial={false} mode=\"popLayout\">\n          {tags.map((tag, i) => (\n            <Chip\n              key={tag}\n              tag={tag}\n              removeLabel={l.remove(tag)}\n              armed={armed && i === tags.length - 1}\n              shakeNonce={shake && shake.tag === tag ? shake.n : 0}\n              disabled={disabled}\n              reduce={reduce}\n              onRemove={() => remove(tag)}\n            >\n              {renderTag?.(tag)}\n            </Chip>\n          ))}\n        </AnimatePresence>\n        <motion.input\n          layout={!reduce ? \"position\" : false}\n          ref={inputRef}\n          id={inputId}\n          type=\"text\"\n          role=\"combobox\"\n          aria-label={ariaLabel ?? l.input}\n          aria-expanded={showList}\n          aria-controls={listId}\n          aria-autocomplete=\"list\"\n          aria-activedescendant={showList && active >= 0 ? `${listId}-${active}` : undefined}\n          aria-invalid={error ? true : undefined}\n          aria-describedby={error ? errorId : undefined}\n          disabled={disabled}\n          readOnly={full}\n          value={text}\n          placeholder={full ? \"\" : tags.length ? \"\" : placeholder}\n          onChange={(e) => {\n            const v = e.target.value\n            if (v.includes(\",\")) {\n              const parts = v.split(\",\")\n              add(parts.slice(0, -1))\n              setText(parts[parts.length - 1] ?? \"\")\n            } else setText(v)\n            setArmed(false)\n            setError(null)\n            setOpen(true)\n            setActive(-1)\n          }}\n          onKeyDown={onKeyDown}\n          onPaste={onPaste}\n          onFocus={() => setOpen(true)}\n          onBlur={() => {\n            setOpen(false)\n            setArmed(false)\n            setActive(-1)\n          }}\n          className=\"h-7 min-w-24 flex-1 bg-transparent px-1.5 outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed\"\n        />\n        {maxTags !== undefined && (\n          <span\n            aria-hidden=\"true\"\n            className={cn(\"ms-auto shrink-0 px-1.5 text-xs tabular-nums text-muted-foreground\", full && \"text-foreground\")}\n          >\n            {tags.length}/{maxTags}\n          </span>\n        )}\n      </div>\n\n      <AnimatePresence>\n        {error && (\n          <motion.p\n            id={errorId}\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: -4 }}\n            animate={{ opacity: 1, y: 0 }}\n            exit={{ opacity: 0 }}\n            transition={{ duration: 0.18 }}\n            className=\"mt-1.5 text-xs font-medium text-destructive\"\n          >\n            {error}\n          </motion.p>\n        )}\n      </AnimatePresence>\n\n      <AnimatePresence>\n        {showList && (\n          <motion.ul\n            id={listId}\n            role=\"listbox\"\n            initial={reduce ? { opacity: 0 } : { opacity: 0, y: -6, scale: 0.98 }}\n            animate={{ opacity: 1, y: 0, scale: 1 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, y: -4, scale: 0.98, transition: { duration: 0.12 } }}\n            transition={spring.snap}\n            className=\"absolute inset-x-0 top-full z-20 mt-1.5 origin-top overflow-hidden rounded-lg border bg-popover p-1 text-popover-foreground shadow-[var(--pc-e2)]\"\n          >\n            {filtered.map((s, i) => (\n              <li\n                key={s}\n                id={`${listId}-${i}`}\n                role=\"option\"\n                aria-selected={i === active}\n                onMouseDown={(e) => e.preventDefault()}\n                onMouseEnter={() => setActive(i)}\n                onClick={() => {\n                  add([s])\n                  setText(\"\")\n                  setActive(-1)\n                  inputRef.current?.focus()\n                }}\n                className=\"relative flex cursor-pointer items-center gap-2 rounded-md px-2 py-1.5 text-sm\"\n              >\n                {i === active && (\n                  <motion.span\n                    layoutId={`${uid}-hl`}\n                    transition={reduce ? { duration: 0 } : spring.snap}\n                    className=\"absolute inset-0 rounded-md bg-muted\"\n                  />\n                )}\n                <span className=\"relative\">{renderTag?.(s)}</span>\n                <span className=\"relative truncate\">{s}</span>\n              </li>\n            ))}\n          </motion.ul>\n        )}\n      </AnimatePresence>\n\n      {name && <input type=\"hidden\" name={name} value={tags.join(\",\")} />}\n      <span className=\"sr-only\" aria-live=\"polite\" role=\"status\">\n        {announce}\n      </span>\n    </div>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/tag-input.tsx"
    }
  ],
  "categories": [
    "components",
    "inputs"
  ],
  "type": "registry:component"
}