{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tags-input",
  "title": "Tags Input",
  "description": "A field for many short values: add with Enter or comma, paste a whole list, walk tags with the arrows, with limits, validation and suggestions.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "utils",
    "https://miseui.junsu4621.workers.dev/r/motion.json"
  ],
  "files": [
    {
      "path": "registry/miseui/ui/tags-input.tsx",
      "content": "import type * as React from \"react\"\nimport { useEffect, useId, useRef } from \"react\"\nimport { useReducedMotion } from \"motion/react\"\nimport { TagsField } from \"@/registry/miseui/ui/tags-input-field\"\nimport { DEFAULT_TAG_MESSAGES, type TagMessages } from \"@/registry/miseui/ui/tags-input-math\"\nimport type { TagsInputLabels, TagsInputVariant } from \"@/registry/miseui/ui/tags-input-parts\"\nimport { useTagsInputState } from \"@/registry/miseui/ui/tags-input-state\"\nimport { cn } from \"@/registry/miseui/lib/utils\"\n\ntype TagsInputEffect = \"pop\"\n\nconst DEFAULT_LABELS: TagsInputLabels = {\n  remove: (tag) => `Remove ${tag}`,\n  tag: (tag) => `${tag}. Press Backspace to remove.`,\n  add: \"Add\",\n  added: (tags) => `Added ${tags.join(\", \")}`,\n  removed: (tag) => `Removed ${tag}`,\n  count: (count, max) => `${count} of ${max}`,\n}\n\ntype RootAttributes = Omit<React.ComponentProps<\"div\">, \"children\" | \"defaultValue\" | \"onChange\">\n\ninterface TagsInputProps extends RootAttributes {\n  value?: readonly string[]\n  defaultValue?: readonly string[]\n  onValueChange?: (tags: string[]) => void\n  /** `plain` chips in a field, `inline` words on a rule, `stacked` a field over a list of rows, `compact` one scrolling line. */\n  variant?: TagsInputVariant\n  /** `pop` scales tags in and out on a spring, and the others slide over to make room. */\n  effect?: TagsInputEffect\n  max?: number\n  /** Return a sentence to refuse a tag, or nothing to accept it. */\n  validate?: (tag: string, tags: readonly string[]) => string | null | undefined\n  /** Offered as you type. Free text is still allowed. */\n  suggestions?: readonly string[]\n  placeholder?: string\n  disabled?: boolean\n  /** Posts each tag with the surrounding form. */\n  name?: string\n  labels?: Partial<TagsInputLabels>\n  messages?: Partial<TagMessages>\n}\n\nconst EMPTY: readonly string[] = []\n\nfunction TagsInput({\n  value, defaultValue = EMPTY, onValueChange, variant = \"plain\", effect, max, validate, suggestions = EMPTY,\n  placeholder, disabled = false, name, labels, messages, className, \"aria-label\": ariaLabel, ...props\n}: TagsInputProps) {\n  const errorId = useId()\n  const inputRef = useRef<HTMLInputElement>(null)\n  const listRef = useRef<HTMLUListElement>(null)\n  const reduceMotion = useReducedMotion() ?? false\n  const merged = { ...DEFAULT_LABELS, ...labels }\n  const state = useTagsInputState(\n    {\n      controlled: value, initial: defaultValue, suggestions, disabled, max, validate, onValueChange,\n      messages: { ...DEFAULT_TAG_MESSAGES, ...messages },\n      onAnnounce: (added, removed) => (removed === null ? merged.added(added) : merged.removed(removed)),\n    },\n    { inputRef, listRef },\n  )\n  const { tags } = state\n  // Compact is one line, so a new tag would otherwise land out of sight.\n  useEffect(() => {\n    const list = listRef.current\n    if (list && variant === \"compact\") list.scrollLeft = list.scrollWidth\n  }, [tags.length, variant])\n  return (\n    <div data-slot=\"tags-input\" data-variant={variant} data-effect={effect} className={cn(\"grid w-full min-w-0 grid-cols-[minmax(0,1fr)] gap-1\", className)} {...props}>\n      {name ? tags.map((tag) => <input key={tag} type=\"hidden\" name={name} value={tag} />) : null}\n      <TagsField\n        state={state} variant={variant} labels={merged} pop={effect === \"pop\" && !reduceMotion} placeholder={placeholder} ariaLabel={ariaLabel}\n        errorId={errorId} hasSuggestions={suggestions.length > 0} inputRef={inputRef} listRef={listRef}\n      />\n      <div className=\"flex items-start justify-between gap-2 text-[13px]\">\n        {state.error ? <p id={errorId} role=\"alert\" className=\"min-w-0 break-words text-destructive\">{state.error}</p> : <span />}\n        {max !== undefined ? <span data-slot=\"tags-input-count\" className=\"shrink-0 text-muted-foreground tabular-nums\">{merged.count(tags.length, max)}</span> : null}\n      </div>\n      <span className=\"sr-only\" aria-live=\"polite\">{state.status}</span>\n    </div>\n  )\n}\n\nexport { TagsInput, type TagsInputProps, type TagsInputVariant, type TagsInputEffect, type TagsInputLabels, type TagMessages }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/miseui/ui/tags-input-field.tsx",
      "content": "import type * as React from \"react\"\nimport { AnimatePresence } from \"motion/react\"\nimport { Suggestions, Tag, type TagsInputLabels, type TagsInputVariant } from \"@/registry/miseui/ui/tags-input-parts\"\nimport type { TagsInputState } from \"@/registry/miseui/ui/tags-input-state\"\nimport { cn } from \"@/registry/miseui/lib/utils\"\n\nconst FIELD_FOCUS_CLASS = \"focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50\"\nconst FIELD_CLASS: Record<TagsInputVariant, string> = {\n  plain: cn(\"flex min-h-9 flex-wrap items-center gap-1 rounded-md border border-input px-2 py-1 shadow-xs pointer-coarse:min-h-10\", FIELD_FOCUS_CLASS),\n  inline: \"flex min-h-9 flex-wrap items-center gap-x-2 gap-y-1 border-b border-input py-1 focus-within:border-foreground\",\n  stacked: \"flex items-center gap-2\",\n  compact: cn(\"flex h-8 items-center gap-1 rounded-md border border-input px-2 shadow-xs pointer-coarse:h-10\", FIELD_FOCUS_CLASS),\n}\nconst LIST_CLASS: Record<TagsInputVariant, string> = {\n  plain: \"contents\",\n  inline: \"contents\",\n  stacked: \"grid\",\n  // A horizontal scroller: its clip is square on purpose, and the rounded field around it has room to spare.\n  compact: \"flex min-w-0 items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\",\n}\nconst BARE_INPUT_CLASS = \"h-6 flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground\"\nconst INPUT_CLASS: Record<TagsInputVariant, string> = {\n  // Wider on the layouts that wrap, so the field moves to its own line before a placeholder is cut off.\n  plain: cn(BARE_INPUT_CLASS, \"min-w-24 md:text-sm\"),\n  inline: cn(BARE_INPUT_CLASS, \"min-w-24 md:text-sm\"),\n  stacked: cn(\n    \"h-9 w-full min-w-0 flex-1 rounded-md border border-input bg-transparent px-3 text-base shadow-xs outline-none placeholder:text-muted-foreground md:text-sm pointer-coarse:h-10\",\n    \"focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50\",\n  ),\n  compact: cn(BARE_INPUT_CLASS, \"min-w-16 md:text-[13px]\"),\n}\n\n/** Only as a stacked row does the commit need a button: there the field has no tags around it to explain the pattern. */\nfunction AddButton({ state, label }: { state: TagsInputState; label: string }) {\n  return (\n    <button\n      type=\"button\"\n      disabled={state.disabled || !state.draft.trim()}\n      className=\"h-9 shrink-0 rounded-md border px-3 text-sm font-medium outline-none hover:bg-accent focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 pointer-coarse:h-10\"\n      onClick={() => {\n        state.commit(state.draft)\n        state.focusInput()\n      }}\n    >\n      {label}\n    </button>\n  )\n}\n\ninterface TagsFieldProps {\n  state: TagsInputState\n  variant: TagsInputVariant\n  labels: TagsInputLabels\n  pop: boolean\n  placeholder?: string\n  ariaLabel?: string\n  errorId: string\n  hasSuggestions: boolean\n  inputRef: React.RefObject<HTMLInputElement | null>\n  listRef: React.RefObject<HTMLUListElement | null>\n}\n\ntype TagsInputBoxProps = Pick<TagsFieldProps, \"state\" | \"variant\" | \"placeholder\" | \"ariaLabel\" | \"errorId\" | \"hasSuggestions\" | \"inputRef\">\n\nfunction TagsInputBox({ state, variant, placeholder, ariaLabel, errorId, hasSuggestions, inputRef }: TagsInputBoxProps) {\n  const activeId = state.active ? `${state.listboxId}-${state.activeIndex}` : undefined\n  return (\n    <input\n      ref={inputRef}\n      data-slot=\"tags-input-field\"\n      role={hasSuggestions ? \"combobox\" : undefined}\n      aria-label={ariaLabel}\n      aria-expanded={hasSuggestions ? state.matches.length > 0 : undefined}\n      aria-controls={hasSuggestions && state.matches.length > 0 ? state.listboxId : undefined}\n      aria-autocomplete={hasSuggestions ? \"list\" : undefined}\n      aria-activedescendant={activeId}\n      aria-invalid={state.error ? true : undefined}\n      aria-describedby={state.error ? errorId : undefined}\n      autoComplete=\"off\"\n      disabled={state.disabled}\n      placeholder={placeholder}\n      value={state.draft}\n      className={INPUT_CLASS[variant]}\n      onChange={state.onChange}\n      onKeyDown={state.onInputKeyDown}\n      onPaste={state.onPaste}\n      onFocus={() => state.setOpen(true)}\n      onBlur={() => state.setOpen(false)}\n    />\n  )\n}\n\nfunction TagsList({ state, variant, labels, pop, listRef }: Pick<TagsFieldProps, \"state\" | \"variant\" | \"labels\" | \"pop\" | \"listRef\">) {\n  if (state.tags.length === 0 && variant === \"stacked\") return null\n  const rows = state.tags.map((tag) => <Tag key={tag} tag={tag} variant={variant} labels={labels} pop={pop} state={state} />)\n  return (\n    <ul ref={listRef} data-slot=\"tags-input-list\" className={LIST_CLASS[variant]}>\n      {pop ? <AnimatePresence initial={false} mode=\"popLayout\">{rows}</AnimatePresence> : rows}\n    </ul>\n  )\n}\n\nfunction TagsField({ state, variant, labels, pop, listRef, ...input }: TagsFieldProps) {\n  const box = <TagsInputBox state={state} variant={variant} {...input} />\n  const list = <TagsList state={state} variant={variant} labels={labels} pop={pop} listRef={listRef} />\n  if (variant === \"stacked\") {\n    return (\n      <>\n        <div className={cn(\"relative\", FIELD_CLASS.stacked)}>\n          {box}\n          <AddButton state={state} label={labels.add} />\n          <Suggestions state={state} label={input.ariaLabel} />\n        </div>\n        {list}\n      </>\n    )\n  }\n  return (\n    <div\n      data-slot=\"tags-input-frame\"\n      className={cn(\"relative cursor-text\", FIELD_CLASS[variant], state.disabled && \"pointer-events-none opacity-50\")}\n      onClick={(event) => {\n        if (event.target === event.currentTarget) state.focusInput()\n      }}\n    >\n      {list}\n      {box}\n      <Suggestions state={state} label={input.ariaLabel} />\n    </div>\n  )\n}\n\nexport { TagsField }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/miseui/ui/tags-input-keys.ts",
      "content": "interface InputKeyContext {\n  draft: string\n  tags: readonly string[]\n  matchCount: number\n  suggestionCount: number\n  active: string | null\n  commit: (text: string, keepOnRefusal?: boolean) => void\n  removeLast: () => void\n  focusTag: (tag: string) => void\n  moveActive: (delta: 1 | -1) => void\n  setOpen: (open: boolean) => void\n}\n\n/** Each action returns whether it used the key, which decides whether the browser still gets it. */\nfunction inputKeyActions(field: HTMLInputElement, context: InputKeyContext): Record<string, () => boolean> {\n  const { draft, tags, matchCount, suggestionCount, active, commit, removeLast, focusTag, moveActive, setOpen } = context\n  return {\n    Enter: () => {\n      // An empty field lets Enter through, so the surrounding form still submits.\n      if (!active && !draft.trim()) return false\n      commit(active ?? draft)\n      setOpen(false)\n      return true\n    },\n    \",\": () => {\n      commit(draft)\n      return true\n    },\n    Backspace: () => {\n      if (draft) return false\n      removeLast()\n      return true\n    },\n    ArrowLeft: () => {\n      const atStart = field.selectionStart === 0 && field.selectionEnd === 0\n      if (!atStart || tags.length === 0) return false\n      focusTag(tags[tags.length - 1])\n      return true\n    },\n    ArrowDown: () => {\n      setOpen(true)\n      moveActive(1)\n      return suggestionCount > 0\n    },\n    ArrowUp: () => {\n      moveActive(-1)\n      return matchCount > 0\n    },\n    Escape: () => {\n      setOpen(false)\n      return matchCount > 0\n    },\n  }\n}\n\nfunction tagKeyActions(tag: string, tags: readonly string[], focusInput: () => void, focusTag: (tag: string) => void, removeWithFocus: (tag: string, next: string) => void): Record<string, () => void> {\n  const index = tags.indexOf(tag)\n  const remove = () => removeWithFocus(tag, tags[index - 1] ?? tags[index + 1] ?? \"input\")\n  return {\n    ArrowLeft: () => {\n      if (index > 0) focusTag(tags[index - 1])\n    },\n    ArrowRight: () => {\n      if (index + 1 < tags.length) focusTag(tags[index + 1])\n      else focusInput()\n    },\n    End: focusInput,\n    Backspace: remove,\n    Delete: remove,\n  }\n}\n\nexport { inputKeyActions, tagKeyActions }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/miseui/ui/tags-input-math.ts",
      "content": "interface TagMessages {\n  duplicate: (tag: string) => string\n  max: (max: number) => string\n}\n\ninterface TagRules {\n  max?: number\n  /** Return a sentence to refuse the tag, or nothing to accept it. */\n  validate?: (tag: string, tags: readonly string[]) => string | null | undefined\n  messages: TagMessages\n}\n\nconst DEFAULT_TAG_MESSAGES: TagMessages = {\n  duplicate: (tag) => `${tag} is already added.`,\n  max: (max) => (max === 1 ? \"Only one tag can be added.\" : `Only ${max} tags can be added.`),\n}\n\n/** Comma from typing; new lines and tabs because a pasted spreadsheet column separates with those. */\nfunction parseTags(text: string) {\n  return text.split(/[,\\n\\r\\t]+/).map((part) => part.trim()).filter(Boolean)\n}\n\nfunction refusal(tag: string, tags: readonly string[], rules: TagRules) {\n  const lower = tag.toLowerCase()\n  if (tags.some((entry) => entry.toLowerCase() === lower)) return rules.messages.duplicate(tag)\n  if (rules.max !== undefined && tags.length >= rules.max) return rules.messages.max(rules.max)\n  return rules.validate?.(tag, tags) ?? null\n}\n\n/** Each candidate is checked against the tags accepted before it, so a paste cannot slip duplicates past the limit. */\nfunction addTags(current: readonly string[], candidates: readonly string[], rules: TagRules) {\n  return candidates.reduce<{ tags: readonly string[]; errors: readonly string[] }>(\n    (result, tag) => {\n      const reason = refusal(tag, result.tags, rules)\n      return reason ? { ...result, errors: [...result.errors, reason] } : { ...result, tags: [...result.tags, tag] }\n    },\n    { tags: current, errors: [] },\n  )\n}\n\nfunction filterSuggestions(suggestions: readonly string[], query: string, tags: readonly string[]) {\n  const needle = query.trim().toLowerCase()\n  const taken = new Set(tags.map((tag) => tag.toLowerCase()))\n  return suggestions.filter((entry) => {\n    const lower = entry.toLowerCase()\n    return !taken.has(lower) && lower.includes(needle)\n  })\n}\n\nexport { DEFAULT_TAG_MESSAGES, addTags, filterSuggestions, parseTags, type TagMessages, type TagRules }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/miseui/ui/tags-input-parts.tsx",
      "content": "import type * as React from \"react\"\nimport { X } from \"lucide-react\"\nimport { motion } from \"motion/react\"\nimport { SPRING_DEFAULT } from \"@/registry/miseui/lib/motion\"\nimport type { TagsInputState } from \"@/registry/miseui/ui/tags-input-state\"\nimport { cn } from \"@/registry/miseui/lib/utils\"\n\ntype TagsInputVariant = \"plain\" | \"inline\" | \"stacked\" | \"compact\"\n\ninterface TagsInputLabels {\n  remove: (tag: string) => string\n  /** Read out for a focused tag, which has no visible instructions. */\n  tag: (tag: string) => string\n  add: string\n  added: (tags: readonly string[]) => string\n  removed: (tag: string) => string\n  count: (count: number, max: number) => string\n}\n\nconst TAG_CLASS: Record<TagsInputVariant, string> = {\n  plain: \"min-h-6 max-w-full gap-1 rounded-sm bg-secondary pr-1 pl-2 text-[13px] text-secondary-foreground\",\n  // No surface: words with commas between them, reading as a line of text.\n  inline: \"min-h-6 max-w-full gap-1 text-sm font-medium after:text-muted-foreground after:content-[','] last:after:content-none\",\n  stacked: \"min-h-10 w-full justify-between gap-2 border-b py-1 text-sm\",\n  compact: \"h-6 shrink-0 gap-1 rounded-sm bg-secondary px-1 text-[13px] text-secondary-foreground\",\n}\n\nconst REMOVE_CLASS = cn(\n  \"relative flex size-4 shrink-0 items-center justify-center rounded-sm text-muted-foreground\",\n  // A 16 px glyph with a 40 px touch target that sits over the gap around it.\n  \"after:absolute after:top-1/2 after:left-1/2 after:size-6 after:-translate-x-1/2 after:-translate-y-1/2 pointer-coarse:after:size-10\",\n  \"transition-colors duration-(--duration-fast) ease-(--ease-mise) hover:bg-accent hover:text-foreground\",\n  \"[&_svg]:size-3\",\n)\n\ninterface TagProps {\n  tag: string\n  variant: TagsInputVariant\n  labels: TagsInputLabels\n  pop: boolean\n  state: TagsInputState\n}\n\nfunction Tag({ tag, variant, labels, pop, state }: TagProps) {\n  const shared = {\n    \"data-slot\": \"tags-input-tag\",\n    \"data-tag\": tag,\n    tabIndex: state.disabled ? undefined : -1,\n    \"aria-label\": labels.tag(tag),\n    className: cn(\n      \"flex items-center rounded-sm outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50\",\n      TAG_CLASS[variant],\n    ),\n    onKeyDown: (event: React.KeyboardEvent<HTMLElement>) => state.onTagKeyDown(event, tag),\n  }\n  const children = (\n    <>\n      <span className=\"min-w-0 break-words\" title={tag}>{tag}</span>\n      {state.disabled ? null : (\n        <button\n          type=\"button\"\n          // Out of the tab order: arrows reach the tag and Backspace removes it, and a stop per chip would make the field a long walk.\n          tabIndex={-1}\n          aria-label={labels.remove(tag)}\n          className={REMOVE_CLASS}\n          onClick={() => state.removeByButton(tag)}\n        >\n          <X aria-hidden=\"true\" />\n        </button>\n      )}\n    </>\n  )\n  if (!pop) return <li {...shared}>{children}</li>\n  return (\n    <motion.li\n      {...shared}\n      layout=\"position\"\n      initial={{ scale: 0.8, opacity: 0 }}\n      animate={{ scale: 1, opacity: 1 }}\n      exit={{ scale: 0.8, opacity: 0 }}\n      transition={SPRING_DEFAULT}\n    >\n      {children}\n    </motion.li>\n  )\n}\n\nfunction Suggestions({ state, label }: { state: TagsInputState; label?: string }) {\n  if (state.matches.length === 0) return null\n  return (\n    <ul\n      id={state.listboxId}\n      role=\"listbox\"\n      aria-label={label}\n      data-slot=\"tags-input-suggestions\"\n      className=\"absolute top-full right-0 left-0 z-20 mt-1 grid max-h-56 overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md\"\n      // Keeps focus in the input, or the blur would close the list before the click lands.\n      onMouseDown={(event) => event.preventDefault()}\n    >\n      {state.matches.map((entry, index) => (\n        <li\n          key={entry}\n          id={`${state.listboxId}-${index}`}\n          role=\"option\"\n          aria-selected={index === state.activeIndex}\n          className={cn(\n            \"flex min-h-8 cursor-default items-center rounded-sm px-2 text-sm pointer-coarse:min-h-10\",\n            index === state.activeIndex ? \"bg-accent\" : \"hover:bg-accent/50\",\n          )}\n          onClick={() => {\n            state.commit(entry)\n            state.setOpen(false)\n          }}\n          onMouseEnter={() => state.setActiveIndex(index)}\n        >\n          {entry}\n        </li>\n      ))}\n    </ul>\n  )\n}\n\nexport { Suggestions, Tag, type TagsInputLabels, type TagsInputVariant }\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/miseui/ui/tags-input-state.ts",
      "content": "import type * as React from \"react\"\nimport { useEffect, useId, useRef, useState } from \"react\"\nimport { inputKeyActions, tagKeyActions } from \"@/registry/miseui/ui/tags-input-keys\"\nimport { addTags, filterSuggestions, parseTags, type TagRules } from \"@/registry/miseui/ui/tags-input-math\"\n\ninterface TagsStateOptions extends TagRules {\n  controlled?: readonly string[]\n  initial: readonly string[]\n  suggestions: readonly string[]\n  disabled: boolean\n  onValueChange?: (tags: string[]) => void\n  onAnnounce: (added: readonly string[], removed: string | null) => string\n}\n\ninterface TagsRefs {\n  inputRef: React.RefObject<HTMLInputElement | null>\n  listRef: React.RefObject<HTMLUListElement | null>\n}\n\n/** The value, what was last refused and the sentence read out to assistive tech. */\nfunction useTagsValue(options: TagsStateOptions) {\n  const { controlled, initial, max, validate, messages, onValueChange, onAnnounce } = options\n  const [uncontrolled, setUncontrolled] = useState(initial)\n  const [error, setError] = useState<string | null>(null)\n  const [status, setStatus] = useState(\"\")\n  const tags = controlled ?? uncontrolled\n  const replace = (next: readonly string[]) => {\n    setUncontrolled(next)\n    onValueChange?.([...next])\n  }\n  const add = (candidates: readonly string[]) => {\n    const result = addTags(tags, candidates, { max, validate, messages })\n    const added = result.tags.slice(tags.length)\n    setError(result.errors[0] ?? null)\n    if (added.length) {\n      replace(result.tags)\n      setStatus(onAnnounce(added, null))\n    }\n    return result.errors.length === 0\n  }\n  const remove = (tag: string) => {\n    replace(tags.filter((entry) => entry !== tag))\n    setError(null)\n    setStatus(onAnnounce([], tag))\n  }\n  return { tags, error, setError, status, add, remove }\n}\n\nfunction findTag(list: HTMLElement | null, tag: string) {\n  const rows = list?.querySelectorAll<HTMLElement>(\"[data-slot='tags-input-tag']\") ?? []\n  return Array.from(rows).find((row) => row.dataset.tag === tag)\n}\n\n/** Reads the rendered tags because the value only changes on the next render, which is when the focus has to land. */\nfunction useTagFocus(tags: readonly string[], { inputRef, listRef }: TagsRefs) {\n  const pending = useRef<string | \"input\" | null>(null)\n  const focusTag = (tag: string) => findTag(listRef.current, tag)?.focus()\n  useEffect(() => {\n    const target = pending.current\n    if (target === null) return\n    pending.current = null\n    if (target === \"input\") inputRef.current?.focus()\n    else findTag(listRef.current, target)?.focus()\n  }, [tags, inputRef, listRef])\n  const focusAfterRender = (target: string | \"input\") => {\n    pending.current = target\n  }\n  return { focusTag, focusAfterRender }\n}\n\nfunction useTagsDraft(add: (candidates: readonly string[]) => boolean, setError: (error: string | null) => void) {\n  const [draft, setDraft] = useState(\"\")\n  const [open, setOpen] = useState(false)\n  const [activeIndex, setActiveIndex] = useState(-1)\n  // Keeps a refused word in the field to fix; a paste of many has nothing single to keep.\n  const commit = (text: string, keepOnRefusal = true) => {\n    const candidates = parseTags(text)\n    if (candidates.length === 0) return\n    const accepted = add(candidates)\n    if (accepted || candidates.length > 1 || !keepOnRefusal) setDraft(\"\")\n    setActiveIndex(-1)\n  }\n  const onChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n    const value = event.target.value\n    // Phone keyboards send no comma keydown, so it can only be caught here. Not while an IME is still composing.\n    if (!(event.nativeEvent as InputEvent).isComposing && value.includes(\",\")) {\n      commit(value, false)\n      return\n    }\n    setDraft(value)\n    setError(null)\n    setOpen(true)\n    setActiveIndex(-1)\n  }\n  const onPaste = (event: React.ClipboardEvent<HTMLInputElement>) => {\n    const text = event.clipboardData.getData(\"text\")\n    if (!/[,\\n\\r\\t]/.test(text)) return\n    event.preventDefault()\n    commit(`${draft}${text}`, false)\n  }\n  return { draft, open, setOpen, activeIndex, setActiveIndex, commit, onChange, onPaste }\n}\n\nfunction useTagsInputState(options: TagsStateOptions, refs: TagsRefs) {\n  const { suggestions, disabled } = options\n  const listboxId = useId()\n  const { tags, error, setError, status, add, remove } = useTagsValue(options)\n  const { focusTag, focusAfterRender } = useTagFocus(tags, refs)\n  const { draft, open, setOpen, activeIndex, setActiveIndex, commit, onChange, onPaste } = useTagsDraft(add, setError)\n  const matches = open ? filterSuggestions(suggestions, draft, tags) : []\n  const active = matches[activeIndex] ?? null\n  const moveActive = (delta: 1 | -1) => {\n    if (matches.length) setActiveIndex((activeIndex + delta + matches.length) % matches.length)\n  }\n  const removeLast = () => {\n    const last = tags[tags.length - 1]\n    if (last !== undefined) remove(last)\n  }\n  const onInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {\n    // Enter during composition is the IME accepting a syllable, not the person accepting a tag.\n    if (event.nativeEvent.isComposing) return\n    const actions = inputKeyActions(event.currentTarget, {\n      draft, tags, matchCount: matches.length, suggestionCount: suggestions.length, active, commit, removeLast, focusTag, moveActive, setOpen,\n    })\n    if (actions[event.key]?.()) event.preventDefault()\n  }\n  const focusInput = () => refs.inputRef.current?.focus()\n  const removeWithFocus = (tag: string, next: string) => {\n    focusAfterRender(next)\n    remove(tag)\n  }\n  const onTagKeyDown = (event: React.KeyboardEvent<HTMLElement>, tag: string) => {\n    const action = tagKeyActions(tag, tags, focusInput, focusTag, removeWithFocus)[event.key]\n    if (!action) return\n    event.preventDefault()\n    action()\n  }\n  const removeByButton = (tag: string) => removeWithFocus(tag, \"input\")\n  return {\n    listboxId, tags, error, status, draft, matches, activeIndex, active, disabled,\n    onChange, onInputKeyDown, onPaste, onTagKeyDown, removeByButton, commit, setOpen, setActiveIndex, focusInput,\n  }\n}\n\ntype TagsInputState = ReturnType<typeof useTagsInputState>\n\nexport { useTagsInputState, type TagsInputState }\n",
      "type": "registry:ui"
    }
  ],
  "categories": [
    "forms"
  ],
  "type": "registry:ui"
}