{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"react-tag-input-with-autocomplete-suggestions-paste-support-and-coloured-category-chips","type":"registry:component","title":"React Tag Input with Autocomplete Suggestions, Paste Support and Coloured Category Chips","description":"Free React tag input in Tailwind: Enter or comma adds, Backspace removes, paste a list, keyboard suggestions, max count and no duplicates. Copy and paste.","dependencies":["framer-motion"],"files":[{"path":"components/we-inc/react-tag-input-with-autocomplete-suggestions-paste-support-and-coloured-category-chips.tsx","type":"registry:component","content":"import { useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"framer-motion\";\n\n/* ---------- Content: edit these ---------- */\n\ntype Category = { label: string; chip: string; dot: string };\n\nconst CATEGORIES: Record<string, Category> = {\n  area: { label: \"Area\", chip: \"bg-sky-50 text-sky-800 ring-sky-200\", dot: \"bg-sky-500\" },\n  priority: { label: \"Priority\", chip: \"bg-rose-50 text-rose-800 ring-rose-200\", dot: \"bg-rose-500\" },\n  team: { label: \"Team\", chip: \"bg-emerald-50 text-emerald-800 ring-emerald-200\", dot: \"bg-emerald-500\" },\n  custom: { label: \"Custom\", chip: \"bg-stone-100 text-stone-700 ring-stone-300\", dot: \"bg-stone-400\" },\n};\n\ntype Option = { value: string; category?: keyof typeof CATEGORIES };\n\nconst SKILLS: Option[] = [\"React\", \"TypeScript\", \"Tailwind\", \"Node.js\", \"GraphQL\", \"Postgres\", \"Figma\", \"Testing\", \"Accessibility\", \"Animation\", \"Rust\", \"Go\", \"Python\", \"Docker\"].map((value) => ({ value }));\n\nconst LABELS: Option[] = [\n  { value: \"checkout\", category: \"area\" },\n  { value: \"search\", category: \"area\" },\n  { value: \"onboarding\", category: \"area\" },\n  { value: \"billing\", category: \"area\" },\n  { value: \"urgent\", category: \"priority\" },\n  { value: \"low\", category: \"priority\" },\n  { value: \"design\", category: \"team\" },\n  { value: \"platform\", category: \"team\" },\n  { value: \"growth\", category: \"team\" },\n];\n\nconst SPLIT = /[,;\\n]+/;\n\n/* ---------- The reusable tag input ---------- */\n\ntype TagInputProps = {\n  label: string;\n  hint: string;\n  placeholder: string;\n  initial: Option[];\n  suggestions?: Option[];\n  max?: number;\n  coloured?: boolean;\n  startQuery?: string;\n  startOpen?: boolean;\n};\n\nfunction TagInput({ label, hint, placeholder, initial, suggestions = [], max = 10, coloured = false, startQuery = \"\", startOpen = false }: TagInputProps) {\n  const id = useId();\n  const reduce = useReducedMotion();\n  const inputRef = useRef<HTMLInputElement>(null);\n  const [tags, setTags] = useState<Option[]>(initial);\n  const [query, setQuery] = useState(startQuery);\n  const [open, setOpen] = useState(startOpen);\n  const [active, setActive] = useState(0);\n  const [notice, setNotice] = useState(\"\");\n  const [focused, setFocused] = useState(startOpen);\n  const [shake, setShake] = useState<string | null>(null);\n\n  const full = tags.length >= max;\n  const has = (v: string) => tags.some((t) => t.value.toLowerCase() === v.toLowerCase());\n\n  const matches = useMemo(() => {\n    const q = query.trim().toLowerCase();\n    const pool = suggestions.filter((s) => !has(s.value) && (q === \"\" || s.value.toLowerCase().includes(q)));\n    // Words that start with the query come first, then words that merely contain it.\n    const rank = (s: Option) => (s.value.toLowerCase().startsWith(q) ? 0 : 1);\n    return [...pool].sort((a, b) => rank(a) - rank(b)).slice(0, 6);\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [query, suggestions, tags]);\n\n  const showList = open && suggestions.length > 0 && matches.length > 0 && !full;\n\n  useEffect(() => setActive(0), [query]);\n\n  // The demo opens one list before anyone focuses it; close it once the visitor works elsewhere.\n  const rootRef = useRef<HTMLDivElement>(null);\n  useEffect(() => {\n    if (!open && !focused) return;\n    const away = (e: Event) => {\n      if (!rootRef.current?.contains(e.target as Node)) {\n        setOpen(false);\n        setFocused(false);\n      }\n    };\n    document.addEventListener(\"pointerdown\", away);\n    document.addEventListener(\"focusin\", away);\n    return () => {\n      document.removeEventListener(\"pointerdown\", away);\n      document.removeEventListener(\"focusin\", away);\n    };\n  }, [open, focused]);\n  useEffect(() => {\n    if (!shake) return;\n    const t = setTimeout(() => setShake(null), 500);\n    return () => clearTimeout(t);\n  }, [shake]);\n\n  function add(raw: string | Option): boolean {\n    const opt: Option = typeof raw === \"string\" ? suggestions.find((s) => s.value.toLowerCase() === raw.trim().toLowerCase()) ?? { value: raw.trim(), category: coloured ? \"custom\" : undefined } : raw;\n    if (!opt.value) return false;\n    if (has(opt.value)) {\n      setShake(tags.find((t) => t.value.toLowerCase() === opt.value.toLowerCase())!.value);\n      setNotice(`\"${opt.value}\" is already added`);\n      return false;\n    }\n    if (tags.length >= max) {\n      setNotice(`You can add up to ${max} tags`);\n      return false;\n    }\n    setTags((prev) => [...prev, opt]);\n    setNotice(`Added ${opt.value}`);\n    return true;\n  }\n\n  function remove(value: string) {\n    setTags((prev) => prev.filter((t) => t.value !== value));\n    setNotice(`Removed ${value}`);\n    inputRef.current?.focus();\n  }\n\n  function addMany(parts: string[]) {\n    let count = 0;\n    const seen = new Set(tags.map((t) => t.value.toLowerCase()));\n    const next = [...tags];\n    for (const p of parts.map((s) => s.trim()).filter(Boolean)) {\n      if (seen.has(p.toLowerCase()) || next.length >= max) continue;\n      seen.add(p.toLowerCase());\n      next.push(suggestions.find((s) => s.value.toLowerCase() === p.toLowerCase()) ?? { value: p, category: coloured ? \"custom\" : undefined });\n      count++;\n    }\n    setTags(next);\n    setNotice(`Added ${count} tag${count === 1 ? \"\" : \"s\"} from paste`);\n  }\n\n  function onKeyDown(e: React.KeyboardEvent<HTMLInputElement>) {\n    if (e.key === \"ArrowDown\" && suggestions.length) {\n      e.preventDefault();\n      setOpen(true);\n      setActive((a) => (matches.length ? (a + 1) % matches.length : 0));\n    } else if (e.key === \"ArrowUp\" && showList) {\n      e.preventDefault();\n      setActive((a) => (a - 1 + matches.length) % matches.length);\n    } else if (e.key === \"Enter\" || e.key === \",\" || (e.key === \"Tab\" && query.trim())) {\n      if (e.key === \"Enter\" && showList && matches[active]) {\n        e.preventDefault();\n        if (add(matches[active])) setQuery(\"\");\n        return;\n      }\n      if (!query.trim()) return;\n      e.preventDefault();\n      if (add(query)) setQuery(\"\");\n    } else if (e.key === \"Backspace\" && query === \"\" && tags.length) {\n      remove(tags[tags.length - 1].value);\n    } else if (e.key === \"Escape\") {\n      setOpen(false);\n    }\n  }\n\n  function onChange(v: string) {\n    if (SPLIT.test(v)) {\n      addMany(v.split(SPLIT));\n      setQuery(\"\");\n      return;\n    }\n    setQuery(v);\n    setOpen(true);\n    setNotice(\"\");\n  }\n\n  function onPaste(e: React.ClipboardEvent<HTMLInputElement>) {\n    const text = e.clipboardData.getData(\"text\");\n    if (!SPLIT.test(text)) return;\n    e.preventDefault();\n    addMany((query + text).split(SPLIT));\n    setQuery(\"\");\n  }\n\n  const listId = `${id}-list`;\n  const optId = (i: number) => `${id}-opt-${i}`;\n  const chipClass = (t: Option) =>\n    coloured ? CATEGORIES[t.category ?? \"custom\"].chip : \"bg-slate-900 text-white ring-slate-900\";\n\n  return (\n    <div ref={rootRef} className=\"relative\">\n      <div className=\"mb-2 flex items-baseline justify-between gap-3\">\n        <label htmlFor={id} className=\"text-sm font-semibold text-slate-900\">\n          {label}\n        </label>\n        <span className={`text-xs tabular-nums ${full ? \"font-semibold text-rose-600\" : \"text-slate-500\"}`}>\n          {full ? \"Limit reached \\u00b7 \" : \"\"}\n          {tags.length}/{max}\n        </span>\n      </div>\n\n      <div className=\"relative\">\n      <div\n        onMouseDown={(e) => {\n          if (e.target === e.currentTarget) {\n            e.preventDefault();\n            inputRef.current?.focus();\n          }\n        }}\n        className={`flex min-h-[48px] cursor-text flex-wrap items-center gap-1.5 rounded-xl border border-slate-300 bg-white p-1.5 shadow-sm transition-colors ${focused ? \"border-slate-900 ring-4 ring-slate-900/10\" : \"hover:border-slate-400\"}`}\n      >\n        <ul className=\"contents\" aria-label={`${label} selected`}>\n          <AnimatePresence initial={false}>\n            {tags.map((t) => (\n              <motion.li\n                key={t.value}\n                layout={!reduce}\n                initial={reduce ? false : { opacity: 0, scale: 0.8 }}\n                animate={shake === t.value && !reduce ? { opacity: 1, scale: 1, x: [0, -5, 5, -3, 3, 0] } : { opacity: 1, scale: 1, x: 0 }}\n                exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.8, transition: { duration: 0.12 } }}\n                transition={{ type: \"spring\", stiffness: 520, damping: 32 }}\n                className={`inline-flex h-8 items-center gap-1.5 rounded-lg pl-2.5 pr-1 text-[13px] font-medium ring-1 ring-inset ${chipClass(t)}`}\n              >\n                {coloured && <span aria-hidden=\"true\" className={`h-1.5 w-1.5 rounded-full ${CATEGORIES[t.category ?? \"custom\"].dot}`} />}\n                <span>{t.value}</span>\n                <button\n                  type=\"button\"\n                  onClick={() => remove(t.value)}\n                  aria-label={`Remove ${t.value}`}\n                  className={`grid h-6 w-6 place-items-center rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 ${coloured ? \"hover:bg-black/5 focus-visible:ring-slate-900\" : \"hover:bg-white/15 focus-visible:ring-white\"}`}\n                >\n                  <svg viewBox=\"0 0 20 20\" className=\"h-3.5 w-3.5\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"2\" strokeLinecap=\"round\" aria-hidden=\"true\">\n                    <path d=\"M6 6l8 8M14 6l-8 8\" />\n                  </svg>\n                </button>\n              </motion.li>\n            ))}\n          </AnimatePresence>\n        </ul>\n        <input\n          ref={inputRef}\n          id={id}\n          value={query}\n          onChange={(e) => onChange(e.target.value)}\n          onKeyDown={onKeyDown}\n          onPaste={onPaste}\n          onFocus={() => {\n            setOpen(true);\n            setFocused(true);\n          }}\n          onBlur={() => {\n            setOpen(false);\n            setFocused(false);\n          }}\n          placeholder={full ? \"\" : tags.length ? \"\" : placeholder}\n          aria-describedby={`${id}-hint`}\n          role={suggestions.length ? \"combobox\" : undefined}\n          aria-autocomplete={suggestions.length ? \"list\" : undefined}\n          aria-expanded={suggestions.length ? showList : undefined}\n          aria-controls={suggestions.length ? listId : undefined}\n          aria-activedescendant={showList ? optId(active) : undefined}\n          className={`h-8 flex-1 bg-transparent ${full ? \"w-0 min-w-0\" : \"min-w-[5rem]\"} px-1.5 text-sm text-slate-900 placeholder:text-slate-400 focus:outline-none`}\n        />\n      </div>\n\n      <AnimatePresence>\n        {showList && (\n          <motion.ul\n            id={listId}\n            role=\"listbox\"\n            aria-label={`${label} suggestions`}\n            initial={reduce ? false : { opacity: 0, y: -4 }}\n            animate={{ opacity: 1, y: 0 }}\n            exit={reduce ? { opacity: 0 } : { opacity: 0, y: -4, transition: { duration: 0.1 } }}\n            transition={{ type: \"spring\", stiffness: 600, damping: 38 }}\n            className=\"absolute left-0 right-0 top-full z-20 mt-1.5 overflow-hidden rounded-xl border border-slate-200 bg-white p-1 shadow-lg shadow-slate-900/10\"\n          >\n            {matches.map((m, i) => {\n              const cat = m.category ? CATEGORIES[m.category] : null;\n              const q = query.trim();\n              const at = q ? m.value.toLowerCase().indexOf(q.toLowerCase()) : -1;\n              return (\n                <li\n                  key={m.value}\n                  id={optId(i)}\n                  role=\"option\"\n                  aria-selected={i === active}\n                  onMouseDown={(e) => {\n                    e.preventDefault();\n                    if (add(m)) setQuery(\"\");\n                  }}\n                  onMouseEnter={() => setActive(i)}\n                  className={`flex h-10 cursor-pointer items-center justify-between gap-3 rounded-lg px-3 text-sm ${i === active ? \"bg-slate-100 text-slate-900\" : \"text-slate-700\"}`}\n                >\n                  <span className=\"flex items-center gap-2.5\">\n                    {cat && <span aria-hidden=\"true\" className={`h-2 w-2 rounded-full ${cat.dot}`} />}\n                    <span>\n                      {at >= 0 ? (\n                        <>\n                          {m.value.slice(0, at)}\n                          <span className=\"font-semibold text-slate-900\">{m.value.slice(at, at + q.length)}</span>\n                          {m.value.slice(at + q.length)}\n                        </>\n                      ) : (\n                        m.value\n                      )}\n                    </span>\n                  </span>\n                  {cat ? <span className=\"text-xs text-slate-500\">{cat.label}</span> : i === active ? <kbd className=\"rounded border border-slate-300 px-1.5 text-[11px] font-sans text-slate-500\">Enter</kbd> : null}\n                </li>\n              );\n            })}\n          </motion.ul>\n        )}\n      </AnimatePresence>\n      </div>\n\n      <p id={`${id}-hint`} className=\"mt-2 text-xs leading-5 text-slate-600\">\n        {hint}\n      </p>\n      <p className=\"sr-only\" aria-live=\"polite\">\n        {notice}\n      </p>\n      <AnimatePresence>\n        {notice && (notice.startsWith('\"') || notice.startsWith(\"You can\")) && (\n          <motion.p\n            initial={reduce ? false : { opacity: 0, y: -2 }}\n            animate={{ opacity: 1, y: 0 }}\n            exit={{ opacity: 0 }}\n            aria-hidden=\"true\"\n            className=\"mt-1 text-xs font-medium text-rose-600\"\n          >\n            {notice}\n          </motion.p>\n        )}\n      </AnimatePresence>\n    </div>\n  );\n}\n\n/* ---------- Demo: three variants ---------- */\n\nexport default function ReactTagInputDemo() {\n  return (\n    <section className=\"min-h-[760px] bg-stone-50 px-4 pb-72 pt-14 sm:px-8\" style={{ fontFamily: '\"Inter Tight\", Inter, ui-sans-serif, system-ui, sans-serif' }}>\n      <div className=\"mx-auto max-w-2xl\">\n        <h2 className=\"text-2xl font-semibold tracking-tight text-slate-900\">Tag input</h2>\n        <p className=\"mt-1 text-sm text-slate-600\">Press Enter or comma to add. Backspace removes the last tag. Paste a comma separated list to add many.</p>\n\n        <div className=\"mt-10 space-y-12\">\n          <TagInput\n            label=\"Skills\"\n            hint=\"Plain: free text, no list. Duplicates are refused and the existing chip shakes.\"\n            placeholder=\"Add a skill\"\n            initial={[{ value: \"React\" }, { value: \"TypeScript\" }, { value: \"Figma\" }]}\n            max={8}\n          />\n          <TagInput\n            label=\"Issue labels\"\n            hint=\"Coloured by category: area, priority and team. Anything typed that is not on the list becomes a grey custom label.\"\n            placeholder=\"Add a label\"\n            initial={[\n              { value: \"checkout\", category: \"area\" },\n              { value: \"urgent\", category: \"priority\" },\n              { value: \"platform\", category: \"team\" },\n              { value: \"needs-repro\", category: \"custom\" },\n            ]}\n            suggestions={LABELS}\n            coloured\n            max={8}\n          />\n          <TagInput\n            label=\"Tech stack\"\n            hint=\"With suggestions: use the arrow keys to move through the list and Enter to pick.\"\n            placeholder=\"Search technologies\"\n            initial={[{ value: \"Tailwind\" }, { value: \"Postgres\" }]}\n            suggestions={SKILLS}\n            max={6}\n            startQuery=\"t\"\n            startOpen\n          />\n        </div>\n      </div>\n    </section>\n  );\n}\n"}]}
