{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"tag-input","type":"registry:component","title":"Tag input","description":"Your typed words stay put while a chip forms around them.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/tag-input.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// A chip is a small physical thing, so it lands with the faintest settle.\nconst POP = { type: \"spring\", visualDuration: 0.25, bounce: 0.15 } as const;\n// Exits are quicker than the pop, so removing never holds the eye.\nconst LEAVE = { duration: 0.15, ease: [0.23, 1, 0.32, 1] } as const;\n// No bounce on the slide: the row closing up should read as settled.\nconst SLIDE = { type: \"spring\", visualDuration: 0.25, bounce: 0 } as const;\n\nconst key = (tag: string) => tag.toLowerCase();\n\nexport function TagInput({\n  label,\n  tags,\n  onTagsChange,\n  placeholder = \"Add a tag\",\n  className,\n}: {\n  label: string;\n  tags: string[];\n  onTagsChange: (tags: string[]) => void;\n  placeholder?: string;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const id = useId();\n  const [draft, setDraft] = useState(\"\");\n  // Index of the chip the first Backspace armed; the second one removes it.\n  const [armed, setArmed] = useState(-1);\n  // The tag just typed into the field, if any. It becomes a chip right\n  // where its letters already are: the words stay put and the chip forms\n  // around them, rather than the text vanishing and a chip popping in.\n  const [formed, setFormed] = useState<string | null>(null);\n  const [announcement, setAnnouncement] = useState(\"\");\n  const inputRef = useRef<HTMLInputElement>(null);\n  const chipRefs = useRef(new Map<string, HTMLSpanElement>());\n  const shakes = useRef(new Map<string, Animation>());\n\n  useEffect(() => {\n    const running = shakes.current;\n    return () => running.forEach((a) => a.cancel());\n  }, []);\n\n  const nudge = (tag: string) => {\n    const el = chipRefs.current.get(key(tag));\n    if (!el) return;\n    shakes.current.get(key(tag))?.cancel();\n    // Motion owns the chip's transform for layout, so the shake runs on an\n    // inner span through `translate`, which never fights it. Decaying 4px\n    // swings say \"already here\" without reading as an error.\n    const animation = reduceMotion\n      ? el.animate({ opacity: [1, 0.4, 1] }, { duration: 300 })\n      : el.animate(\n          { translate: [\"0\", \"-4px\", \"4px\", \"-3px\", \"2px\", \"0\"] },\n          { duration: 300, easing: \"cubic-bezier(0.23, 1, 0.32, 1)\" },\n        );\n    shakes.current.set(key(tag), animation);\n  };\n\n  const add = (raw: string[], typed = false) => {\n    const next = [...tags];\n    const added: string[] = [];\n    for (const part of raw) {\n      const tag = part.trim();\n      if (!tag) continue;\n      const existing = next.find((t) => key(t) === key(tag));\n      if (existing) {\n        nudge(existing);\n        setAnnouncement(`${existing} is already added`);\n        continue;\n      }\n      next.push(tag);\n      added.push(tag);\n    }\n    if (added.length) {\n      // Only a single typed tag sits where the draft was. Pasted lists pop\n      // in as usual, since most of their chips land away from the caret.\n      setFormed(typed && added.length === 1 ? key(added[0]) : null);\n      onTagsChange(next);\n      setAnnouncement(`Added ${added.join(\", \")}`);\n    }\n    setDraft(\"\");\n    setArmed(-1);\n  };\n\n  const remove = (index: number) => {\n    const tag = tags[index];\n    onTagsChange(tags.filter((_, i) => i !== index));\n    setAnnouncement(`Removed ${tag}`);\n    setArmed(-1);\n  };\n\n  return (\n    <div className={cn(\"flex w-[min(440px,100%)] flex-col gap-2\", className)}>\n      <label htmlFor={id} className=\"text-sm font-medium text-foreground\">\n        {label}\n      </label>\n      {/* Clicking the field's empty space types into it, like a real input.\n          The field grows downward as chips wrap. */}\n      <div\n        className=\"rounded-[14px] bg-muted p-1.5 shadow-raised outline-offset-2 outline-foreground has-[input:focus-visible]:outline-2 has-[input:focus-visible]:outline-solid\"\n        onPointerDown={(e) => {\n          const target = e.target as HTMLElement;\n          if (target !== e.currentTarget && !target.dataset.fill) return;\n          e.preventDefault();\n          inputRef.current?.focus();\n        }}\n      >\n        <ul\n          aria-label={`${label}, ${tags.length} added`}\n          data-fill=\"true\"\n          className=\"relative flex flex-wrap gap-1.5\"\n        >\n          <AnimatePresence mode=\"popLayout\" initial={false}>\n            {tags.map((tag, i) => (\n              <motion.li\n                key={key(tag)}\n                layout=\"position\"\n                initial={\n                  formed === key(tag)\n                    ? // Its letters are already on screen, so the chip\n                      // itself does not fade or blur; only its body forms.\n                      { opacity: 1, scale: 1, filter: \"blur(0px)\" }\n                    : reduceMotion\n                      ? { opacity: 0, scale: 1, filter: \"blur(0px)\" }\n                      : { opacity: 0, scale: 0.9, filter: \"blur(4px)\" }\n                }\n                animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n                exit={{\n                  opacity: 0,\n                  scale: reduceMotion ? 1 : 0.9,\n                  filter: reduceMotion ? \"blur(0px)\" : \"blur(2px)\",\n                  transition: LEAVE,\n                }}\n                transition={{ ...POP, layout: SLIDE }}\n                className=\"max-w-full\"\n              >\n                <span\n                  ref={(el) => {\n                    if (el) chipRefs.current.set(key(tag), el);\n                    else chipRefs.current.delete(key(tag));\n                  }}\n                  className={cn(\n                    \"relative flex h-8 max-w-full items-center gap-0.5 pr-1 pl-2.5 text-sm transition-[color] duration-150 ease-out\",\n                    armed === i ? \"text-background\" : \"text-foreground\",\n                  )}\n                >\n                  {/* The chip's body, separate from its text, so a freshly\n                      typed tag can grow a chip around words that never move. */}\n                  <motion.span\n                    aria-hidden\n                    initial={\n                      formed === key(tag) && !reduceMotion\n                        ? { opacity: 0, scale: 0.9 }\n                        : formed === key(tag)\n                          ? { opacity: 0 }\n                          : false\n                    }\n                    animate={{ opacity: 1, scale: 1 }}\n                    transition={POP}\n                    className={cn(\n                      // 8px radius inside 6px padding keeps the 14px field concentric.\n                      \"absolute inset-0 rounded-lg transition-[background-color] duration-150 ease-out\",\n                      armed === i\n                        ? \"bg-foreground\"\n                        : \"bg-background shadow-raised\",\n                    )}\n                  />\n                  <span className=\"relative truncate\">{tag}</span>\n                  <motion.span\n                    className=\"relative flex\"\n                    // The remove button arrives just after the body, as the\n                    // last piece of the chip, with the icon swap's values.\n                    initial={\n                      formed === key(tag)\n                        ? reduceMotion\n                          ? { opacity: 0 }\n                          : { opacity: 0, scale: 0.25, filter: \"blur(4px)\" }\n                        : false\n                    }\n                    animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n                    transition={{\n                      type: \"spring\",\n                      duration: 0.3,\n                      bounce: 0,\n                      delay: 0.06,\n                    }}\n                  >\n                    <button\n                      type=\"button\"\n                      aria-label={`Remove ${tag}`}\n                      // Keeps focus in the input, so typing carries straight on.\n                      onPointerDown={(e) => e.preventDefault()}\n                      onClick={() => {\n                        remove(i);\n                        inputRef.current?.focus();\n                      }}\n                      className={cn(\n                        \"relative flex size-6 shrink-0 items-center justify-center rounded-md outline-hidden transition-[scale,color,background-color] duration-150 ease-out focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\",\n                        // Grows the hit area to 32px without growing the icon.\n                        \"after:absolute after:-inset-1\",\n                        armed === i\n                          ? \"text-background/70 hover:text-background\"\n                          : \"text-muted-foreground hover:bg-foreground/[0.06] hover:text-foreground\",\n                      )}\n                    >\n                      <svg\n                        viewBox=\"0 0 16 16\"\n                        aria-hidden\n                        className=\"size-3.5\"\n                        fill=\"none\"\n                        stroke=\"currentColor\"\n                        strokeWidth={1.5}\n                        strokeLinecap=\"round\"\n                      >\n                        <path d=\"m4.5 4.5 7 7M11.5 4.5l-7 7\" />\n                      </svg>\n                    </button>\n                  </motion.span>\n                </span>\n              </motion.li>\n            ))}\n            <motion.li\n              key=\"input\"\n              layout=\"position\"\n              transition={{ layout: SLIDE }}\n              className=\"flex min-w-[120px] flex-1\"\n            >\n              <input\n                ref={inputRef}\n                id={id}\n                value={draft}\n                placeholder={placeholder}\n                autoComplete=\"off\"\n                enterKeyHint=\"enter\"\n                onChange={(e) => {\n                  const value = e.target.value;\n                  // Mobile keyboards often never fire a comma keydown.\n                  if (value.includes(\",\")) add(value.split(\",\"), true);\n                  else {\n                    setDraft(value);\n                    setArmed(-1);\n                  }\n                }}\n                onBlur={() => setArmed(-1)}\n                onPaste={(e) => {\n                  const text = e.clipboardData.getData(\"text\");\n                  if (!/[,\\n]/.test(text)) return;\n                  e.preventDefault();\n                  add((draft + text).split(/[,\\n]/));\n                }}\n                onKeyDown={(e) => {\n                  if (e.key === \"Enter\" || e.key === \",\") {\n                    e.preventDefault();\n                    add([draft], true);\n                  } else if (\n                    e.key === \"Backspace\" &&\n                    draft === \"\" &&\n                    tags.length\n                  ) {\n                    e.preventDefault();\n                    const last = tags.length - 1;\n                    if (armed === last) remove(last);\n                    else setArmed(last);\n                  } else if (e.key === \"Escape\") {\n                    setArmed(-1);\n                  }\n                }}\n                // 10px in, the same as a chip's text, so a typed tag becomes a\n                // chip without its letters shifting.\n                className=\"h-8 w-full min-w-0 bg-transparent pr-2 pl-2.5 text-sm text-foreground outline-hidden placeholder:text-muted-foreground\"\n              />\n            </motion.li>\n          </AnimatePresence>\n        </ul>\n      </div>\n      <p className=\"text-xs text-muted-foreground\">\n        Press Enter or comma to add. Backspace twice removes the last tag.\n      </p>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {announcement}\n      </span>\n    </div>\n  );\n}\n\nexport default function TagInputDemo() {\n  const [tags, setTags] = useState([\"motion\", \"design\", \"react\"]);\n  return <TagInput label=\"Topics\" tags={tags} onTagsChange={setTags} />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/tag-input"}