{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "tag-input",
  "title": "Tag input",
  "description": "Several values held as chips in one field: typed, pasted or picked from suggestions. A tag that comes or goes moves the others to their new places, across lines too, and a tag typed again is pointed out instead of added twice.",
  "dependencies": [
    "@ui-sdk/react",
    "@ui-sdk/core"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/combobox.json",
    "https://kinoui.com/r/announce.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/tag-input.tsx",
      "content": "'use client'\n\nimport {\n  Combobox,\n  ComboboxChip,\n  ComboboxChips,\n  ComboboxContent,\n  ComboboxCreate,\n  ComboboxEmpty,\n  ComboboxInput,\n  ComboboxItem,\n  ComboboxList,\n  ComboboxValue,\n} from '@/registry/components/kino/combobox'\nimport { announce } from '@/registry/lib/announce'\nimport { isComposing } from '@ui-sdk/core'\nimport { createComboboxController } from '@ui-sdk/react/combobox'\nimport {\n  type ComponentProps,\n  createContext,\n  type ReactNode,\n  use,\n  useRef,\n  useState,\n} from 'react'\n\n/*\n * Several values held as chips in one field: typed, pasted or picked from\n * suggestions. It is the Combobox with many values, as strings, so its chips\n * glide and leave the same way: a tag that comes or goes moves the others to\n * their new places, and the field grows a line at a time. Whatever adds a\n * tag (a pick, Enter, a comma, a paste, leaving the field) goes through the\n * Combobox's value, so `onValueChange` hears every one.\n */\n\n/** Whether `query` adds a new tag: typed text that names a tag or a suggestion adds that one instead. */\nfunction addsNew(query: string, tags: readonly string[], suggestions: readonly string[]) {\n  const typed = query.trim()\n  return typed !== '' && !findTag(tags, typed) && !findTag(suggestions, typed)\n}\n\n/** Whether two tags are the same, ignoring case and the spaces around them. */\nfunction sameTag(a: string, b: string) {\n  return a.trim().toLocaleLowerCase() === b.trim().toLocaleLowerCase()\n}\n\n/** The tag in `tags` that `text` names, if there is one. */\nfunction findTag(tags: readonly string[], text: string) {\n  return tags.find((tag) => sameTag(tag, text))\n}\n\n/** Whether two lists hold the same tags in the same order. */\nfunction sameTags(a: readonly string[], b: readonly string[]) {\n  return a.length === b.length && a.every((tag, index) => tag === b[index])\n}\n\n/** What a paste holds: one tag per line or per `delimiters` character, a comma by default. */\nfunction splitTags(text: string, delimiters: readonly string[] = [',']) {\n  return text\n    .split(delimiterPattern(delimiters))\n    .map((part) => part.trim())\n    .filter(Boolean)\n}\n\n/** Matches a line break or any one of `delimiters`. */\nfunction delimiterPattern(delimiters: readonly string[]) {\n  const escaped = delimiters.map((delimiter) =>\n    delimiter.replace(/[\\\\^$.*+?()[\\]{}|-]/g, '\\\\$&'),\n  )\n  return new RegExp(`[\\\\r\\\\n${escaped.join('')}]`)\n}\n\ninterface Added {\n  /** The tags after the change. */\n  value: string[]\n  added: string[]\n  /** Tags typed again, as they were already written. */\n  repeated: string[]\n}\n\n/**\n * Adds `texts` to `value` as tags: each trimmed, in a suggestion's spelling\n * when it names one, and never twice.\n */\nfunction addTags(\n  value: readonly string[],\n  texts: readonly string[],\n  suggestions: readonly string[] = [],\n): Added {\n  const next = [...value]\n  const added: string[] = []\n  const repeated: string[] = []\n  for (const text of texts.map((part) => part.trim()).filter(Boolean)) {\n    const existing = findTag(next, text)\n    if (existing) {\n      if (!added.includes(existing)) repeated.push(existing)\n      continue\n    }\n    const tag = findTag(suggestions, text) ?? text\n    next.push(tag)\n    added.push(tag)\n  }\n  return { value: next, added, repeated }\n}\n\n/** What a screen reader hears after a change. */\nfunction announcement(\n  added: readonly string[],\n  removed: readonly string[],\n  repeated: readonly string[],\n) {\n  if (added.length > 1) return `${added.length} tags added`\n  if (added.length === 1) return `${added[0]} added`\n  if (removed.length > 1) return `${removed.length} tags removed`\n  if (removed.length === 1) return `${removed[0]} removed`\n  if (repeated.length > 0) return `${repeated[0]} is already added`\n  return ''\n}\n\nconst TagInputContext = createContext<{\n  add: (texts: readonly string[]) => void\n  tags: readonly string[]\n  suggestions: readonly string[]\n  query: string\n  flash: { tag: string; key: number } | undefined\n  button: boolean\n  delimiters: readonly string[]\n  split: (text: string) => string[]\n} | null>(null)\n\nfunction useTagInput() {\n  const context = use(TagInputContext)\n  if (!context) throw new Error('Tag input parts go inside a TagInput.')\n  return context\n}\n\ntype TagInputProps = Omit<\n  ComponentProps<typeof Combobox<string, true>>,\n  'multiple' | 'items' | 'allowCustomValue'\n> & {\n  /** Tags to offer as you type. Without them, the field takes whatever is typed and opens no list. */\n  suggestions?: readonly string[]\n  /**\n   * Opened from a `ComboboxTrigger` that shows the tags, with the\n   * `TagInputInput` in the popup, rather than typed into in place: the list\n   * opens with no suggestions too, to add one, and lists the tags added,\n   * ticked, so one can be taken off there. Text left typed when it closes\n   * is dropped, not added.\n   */\n  button?: boolean\n  /**\n   * The characters that end a tag as they are typed, and split a paste into\n   * tags beside its lines: a comma by default. Emails take `[',', ' ', ';']`.\n   */\n  delimiters?: readonly string[]\n  /**\n   * The tags a paste with delimiters or lines holds: split on them by\n   * default. Emails copied from a mail app (`Ana Lima <ana@kino.app>`) take\n   * a split that keeps only the addresses.\n   */\n  split?: (text: string) => string[]\n}\n\n/**\n * The root. Enter, a comma or leaving the field adds what was typed as a\n * tag, a paste adds one per comma or line, and a tag typed again is pointed\n * out instead of added twice. Every change is announced.\n */\nfunction TagInput({\n  value: valueProp,\n  defaultValue = [],\n  onValueChange,\n  suggestions = [],\n  controller: controllerProp,\n  query: queryProp,\n  defaultQuery = '',\n  onQueryChange,\n  button = false,\n  delimiters = defaultDelimiters,\n  split = (text) => splitTags(text, delimiters),\n  children,\n  ...props\n}: TagInputProps) {\n  const [ownController] = useState(() => createComboboxController<string, true>())\n  const controller = controllerProp ?? ownController\n  // The tags as the Combobox last gave them, to list the suggestions not\n  // added yet and to tell what a change added or removed.\n  const [ownTags, setOwnTags] = useState<readonly string[]>(defaultValue)\n  const tags = valueProp ?? ownTags\n  const [ownQuery, setOwnQuery] = useState(defaultQuery)\n  const query = queryProp ?? ownQuery\n  const [flash, setFlash] = useState<{ tag: string; key: number }>()\n  const repeatedRef = useRef<readonly string[]>([])\n\n  const point = (repeated: readonly string[]) => {\n    if (!repeated[0]) return\n    setFlash((last) => ({ tag: repeated[0], key: (last?.key ?? 0) + 1 }))\n  }\n\n  const add = (texts: readonly string[]) => {\n    const result = addTags(controller.getValue(), texts, suggestions)\n    if (result.added.length === 0) {\n      announce(announcement([], [], result.repeated))\n      point(result.repeated)\n    } else {\n      repeatedRef.current = result.repeated\n      controller.setValue(result.value)\n    }\n    controller.setQuery('')\n  }\n\n  // Without suggestions there is no list in the field: Enter adds what was typed.\n  const listed = button || suggestions.length > 0\n\n  return (\n    <TagInputContext\n      value={{ add, tags, suggestions, query, flash, button, delimiters, split }}\n    >\n      <Combobox<string, true>\n        multiple\n        // Enter with nothing highlighted, or no list, adds what was typed.\n        allowCustomValue\n        controller={controller}\n        {...(listed ? {} : { open: false })}\n        value={valueProp}\n        defaultValue={defaultValue}\n        onValueChange={(next, details) => {\n          // A suggestion picked or text kept is added as a tag is: in a\n          // suggestion's spelling, and never twice.\n          const kept = tags.filter((tag) => next.includes(tag))\n          const result = addTags(\n            kept,\n            next.filter((tag) => !tags.includes(tag)),\n            suggestions,\n          )\n          if (!sameTags(result.value, next)) {\n            details.cancel()\n            if (sameTags(result.value, tags)) {\n              // The value stays, so no change follows to say so.\n              announce(announcement([], [], result.repeated))\n              point(result.repeated)\n              return\n            }\n            repeatedRef.current = result.repeated\n            controller.setValue(result.value)\n            return\n          }\n          const repeated = repeatedRef.current\n          repeatedRef.current = []\n          announce(\n            announcement(\n              next.filter((tag) => !tags.includes(tag)),\n              tags.filter((tag) => !next.includes(tag)),\n              repeated,\n            ),\n          )\n          point(repeated)\n          setOwnTags(next)\n          onValueChange?.(next, details)\n        }}\n        query={query}\n        onQueryChange={(next, details) => {\n          setOwnQuery(next)\n          onQueryChange?.(next, details)\n        }}\n        {...props}\n      >\n        {children}\n      </Combobox>\n    </TagInputContext>\n  )\n}\n\nconst defaultDelimiters: readonly string[] = [',']\n\n/** Where the tags show: the field, with the input after the last chip. */\nconst TagInputChips = ComboboxChips\n\n/**\n * The tags, as chips. Give it a function child to draw a tag's content,\n * such as an icon beside its name.\n */\nfunction TagInputValue({\n  children,\n  invalid,\n}: {\n  children?: (tag: string) => ReactNode\n  /** Whether a tag can't be taken as it is, such as an email with no domain: its chip shows the invalid look. Say why beside the field. */\n  invalid?: (tag: string) => boolean\n}) {\n  return (\n    <ComboboxValue>\n      {(state) =>\n        (state.value as string[]).map((tag) => (\n          <TagInputChip\n            key={tag}\n            value={tag}\n            data-invalid={invalid?.(tag) ? '' : undefined}\n          >\n            {children ? children(tag) : tag}\n          </TagInputChip>\n        ))\n      }\n    </ComboboxValue>\n  )\n}\n\n/** A tag. It is pointed out for a moment when the same tag is typed again. */\nfunction TagInputChip({\n  value,\n  onTransitionEnd,\n  ...props\n}: ComponentProps<typeof ComboboxChip<string>> & { value: string }) {\n  const { flash } = useTagInput()\n  const key = flash?.tag === value ? flash.key : undefined\n  // A chip that arrives after a flash, such as a tag removed and added\n  // again, takes that flash as already shown.\n  const [shown, setShown] = useState(key)\n  const flashing = key !== undefined && key !== shown\n  return (\n    <ComboboxChip<string>\n      value={value}\n      data-tag={value}\n      data-flash={flashing ? '' : undefined}\n      onTransitionEnd={(event) => {\n        onTransitionEnd?.(event)\n        // Back once it has turned, so it shows for a whole `press`.\n        if (flashing && event.target === event.currentTarget) setShown(key)\n      }}\n      {...props}\n    />\n  )\n}\n\n/**\n * The text you type. Enter, or a delimiter such as a comma, adds it as a\n * tag; a paste with delimiters or lines adds one tag for each, and what is\n * left typed when focus goes is kept as a tag.\n */\nfunction TagInputInput({\n  onKeyDown,\n  onPaste,\n  onBlur,\n  ...props\n}: ComponentProps<typeof ComboboxInput>) {\n  const { add, tags, button, delimiters, split } = useTagInput()\n  return (\n    <ComboboxInput\n      enterKeyHint='enter'\n      onKeyDown={(event) => {\n        onKeyDown?.(event)\n        if (event.defaultPrevented || isComposing(event.nativeEvent)) return\n        const typed = event.currentTarget.value\n        // Enter on a tag already added, with no suggestion highlighted, is\n        // no change to the Combobox: it is pointed out and said here.\n        const repeated =\n          event.key === 'Enter' &&\n          !event.currentTarget.hasAttribute('aria-activedescendant') &&\n          findTag(tags, typed) !== undefined\n        if (!delimiters.includes(event.key) && !repeated) return\n        event.preventDefault()\n        add([typed])\n      }}\n      onPaste={(event) => {\n        onPaste?.(event)\n        if (event.defaultPrevented) return\n        const pasted = event.clipboardData.getData('text')\n        if (!delimiterPattern(delimiters).test(pasted)) return\n        event.preventDefault()\n        const input = event.currentTarget\n        const text =\n          input.value.slice(0, input.selectionStart ?? input.value.length) +\n          pasted +\n          input.value.slice(input.selectionEnd ?? input.value.length)\n        add(split(text))\n      }}\n      onBlur={(event) => {\n        onBlur?.(event)\n        // From a button, leaving the search closes the list: Escape or a press outside cancels.\n        if (!button && event.currentTarget.value.trim() !== '')\n          add([event.currentTarget.value])\n      }}\n      {...props}\n    />\n  )\n}\n\n/** The suggestions' box, under the field. */\nconst TagInputContent = ComboboxContent\n\n/**\n * What shows when no suggestion matches and nothing new can be added. When\n * the typed text names a tag already added, it says so instead.\n */\nfunction TagInputEmpty({ children, ...props }: ComponentProps<typeof ComboboxEmpty>) {\n  const { tags, suggestions, query } = useTagInput()\n  const taken = query.trim() ? findTag(tags, query) : undefined\n  // While the list's last row adds what was typed, nothing is empty to say.\n  if (addsNew(query, tags, suggestions)) return null\n  return (\n    <ComboboxEmpty {...props}>\n      {taken ? `${taken} is already added` : children}\n    </ComboboxEmpty>\n  )\n}\n\n/**\n * The suggestions not added yet that match what was typed, and a last row\n * that adds it as a new tag; from a button, the tags added too, ticked. Give\n * it a function child to draw a row of your own.\n */\nfunction TagInputList({\n  children,\n  ...props\n}: Omit<ComponentProps<typeof ComboboxList>, 'children'> & {\n  children?: (tag: string) => ReactNode\n}) {\n  const { add, tags, suggestions, query, button } = useTagInput()\n  // From a button the list is where a tag comes off, so the added ones stay in it.\n  const rows = button\n    ? [...suggestions, ...tags.filter((tag) => !findTag(suggestions, tag))]\n    : suggestions.filter((suggestion) => !findTag(tags, suggestion))\n  const creates = addsNew(query, tags, suggestions)\n  return (\n    <ComboboxList {...props}>\n      {rows.map((tag) =>\n        children ? children(tag) : <TagInputItem key={tag} value={tag} />,\n      )}\n      {creates ? (\n        <ComboboxCreate onCreate={(text) => add([text])}>\n          {(state) => (\n            <>\n              {/* Isolated, so the quotes stay around a tag in the other direction. */}\n              Add <bdi className='font-medium'>“{state.query.trim()}”</bdi>\n            </>\n          )}\n        </ComboboxCreate>\n      ) : null}\n    </ComboboxList>\n  )\n}\n\n/** A suggestion. Children replace its content, such as an icon beside its name. */\nfunction TagInputItem({\n  value,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof ComboboxItem>, 'value' | 'indicator'> & {\n  value: string\n}) {\n  // In the field its chip shows it is added; from a button, its tick does.\n  const { button } = useTagInput()\n  return (\n    <ComboboxItem value={value} label={value} indicator={button} {...props}>\n      {children ?? value}\n    </ComboboxItem>\n  )\n}\n\nexport {\n  TagInput,\n  TagInputChip,\n  TagInputChips,\n  TagInputContent,\n  TagInputEmpty,\n  TagInputInput,\n  TagInputItem,\n  TagInputList,\n  TagInputValue,\n}\nexport { addsNew, addTags, announcement, findTag, sameTag, splitTags }\nexport type { TagInputProps }\n",
      "type": "registry:component",
      "target": "@components/kino/tag-input.tsx"
    }
  ],
  "type": "registry:component"
}