{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "token-input",
  "title": "Token input",
  "description": "Text with tokens in it, such as a message that mentions people and attaches files. A token is one piece: the caret steps over it, Backspace removes it, and undo, copy and paste keep it whole. It scales in and out of the text, shows a spinner while it loads, and a Trigger menu inside it suggests tokens as you type.",
  "dependencies": [
    "@ui-sdk/react"
  ],
  "registryDependencies": [
    "https://kinoui.com/r/cut.json",
    "https://kinoui.com/r/chip.json",
    "https://kinoui.com/r/flow.json",
    "https://kinoui.com/r/swap.json",
    "https://kinoui.com/r/refs.json",
    "https://kinoui.com/r/input.json",
    "https://kinoui.com/r/textarea.json",
    "https://kinoui.com/r/spinner.json",
    "https://kinoui.com/r/theme.json"
  ],
  "files": [
    {
      "path": "registry/components/kino/token-input.tsx",
      "content": "'use client'\n\nimport { InputInvalidIcon, inputBoxClassName } from '@/registry/components/kino/input'\nimport { Spinner, useSpinner } from '@/registry/components/kino/spinner'\nimport {\n  textareaRadiusClassName,\n  textareaSizeClassName,\n} from '@/registry/components/kino/textarea'\nimport {\n  ChipRemoveIcon,\n  chipClassName,\n  chipLeavingClassName,\n  chipRemoveClassName,\n} from '@/registry/lib/chip'\nimport { CutTooltip } from '@/registry/lib/cut'\nimport { fromWhereItIs, leaveAsCopy, returnFromCopy } from '@/registry/lib/flow'\nimport { markMounted, mergeRefs } from '@/registry/lib/refs'\nimport { Swap, swapIconClassName } from '@/registry/lib/swap'\nimport {\n  createTokenInputController,\n  defaultCodec,\n  fromText,\n  type Token,\n  type TokenCodec,\n  TokenInput as TokenInputPrimitive,\n  type TokenInputController,\n  TokenInputEditor as TokenInputEditorPrimitive,\n  type TokenInputProps,\n  TokenInputToken as TokenInputTokenPrimitive,\n  TokenInputTokenRemove as TokenInputTokenRemovePrimitive,\n  type TokenInputTokenState,\n  type TokenInputValue,\n  toLabel,\n  toText,\n} from '@ui-sdk/react/token-input'\nimport {\n  type ComponentProps,\n  createContext,\n  type PointerEvent,\n  type ReactNode,\n  use,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from 'react'\n\nimport { cn } from '@/lib/utils'\n\n/*\n * ui-sdk's Token input: text and tokens in one field, as in a message that\n * mentions people or attaches files. ui-sdk edits, deletes, undoes, copies\n * and writes the value as text for a form; this is the field's box, and the\n * chip each token is drawn as, which scales in, leaves from where it was,\n * and shows a spinner while it loads.\n */\n\n/** Where a chip that leaves was seen, to leave a copy of it there. */\ninterface Seen {\n  style: Partial<CSSStyleDeclaration>\n  from: ReturnType<typeof fromWhereItIs>\n}\n\n/*\n * What the chips learn of each change as ui-sdk asks for it, while every\n * chip it removes is still on screen: ui-sdk takes a removed token's host\n * out before React runs its chip's cleanup, and draws the hosts after a\n * change afresh, so a chip that mounts may be one that stays.\n */\ninterface TokenFlow {\n  box: HTMLElement | null\n  /** Notes the box the chips sit in, as it mounts. */\n  setBox: (box: HTMLElement | null) => void\n  /** The tokens the latest change brings in, which scale in. */\n  entering: ReadonlySet<string>\n  /** Where each chip the latest change removes was seen, by its token's id. */\n  leaving: Map<string, Seen>\n}\n\nconst TokenFlowContext = createContext<TokenFlow | null>(null)\n\n/** The root. Each token is drawn as Kino's chip unless `renderToken` draws it. */\nfunction TokenInput({\n  renderToken = defaultToken,\n  onValueChange,\n  ...props\n}: TokenInputProps) {\n  const [flow] = useState(() => {\n    const made: TokenFlow = {\n      box: null,\n      setBox: (box) => {\n        made.box = box\n      },\n      entering: new Set(),\n      leaving: new Map(),\n    }\n    return made\n  })\n  return (\n    <TokenFlowContext value={flow}>\n      <TokenInputPrimitive\n        renderToken={renderToken}\n        onValueChange={(value, details) => {\n          onValueChange?.(value, details)\n          if (!details.canceled) seeChange(flow, value, details.removed)\n        }}\n        {...props}\n      />\n    </TokenFlowContext>\n  )\n}\n\n/** Notes which tokens a change brings in, and where each chip it removes is now. */\nfunction seeChange(flow: TokenFlow, value: TokenInputValue, removed: readonly Token[]) {\n  const box = flow.box\n  const editor = box?.querySelector<HTMLElement>('[data-slot=token-input-editor]')\n  if (!box || !editor) return\n  const hosts = new Map(\n    [...editor.querySelectorAll<HTMLElement>('[data-token-id]')].map((host) => [\n      host.dataset.tokenId,\n      host,\n    ]),\n  )\n  flow.entering = new Set(\n    value.flatMap((part) =>\n      typeof part !== 'string' && part.id && !hosts.has(part.id) ? [part.id] : [],\n    ),\n  )\n  flow.leaving = new Map()\n  for (const token of removed) {\n    const chip = token.id\n      ? hosts.get(token.id)?.querySelector<HTMLElement>('[data-slot=token-input-token]')\n      : null\n    const seen = chip ? seeChip(chip, box, editor) : null\n    if (token.id && seen) flow.leaving.set(token.id, seen)\n  }\n}\n\nfunction defaultToken() {\n  return <TokenInputToken />\n}\n\n/** A press on the box, outside the text, puts the caret in the text. */\nfunction focusEditor(event: PointerEvent<HTMLElement>) {\n  if (event.target !== event.currentTarget) return\n  const editor = event.currentTarget.querySelector<HTMLElement>(\n    '[data-slot=token-input-editor]',\n  )\n  if (!editor) return\n  event.preventDefault()\n  editor.focus()\n}\n\n/**\n * The field: the text and its tokens, in the box every text control has. It\n * grows with its text, then scrolls. `className` goes on the box; every\n * other prop goes to ui-sdk's editor.\n */\nfunction TokenInputEditor({\n  className,\n  ...props\n}: Omit<ComponentProps<typeof TokenInputEditorPrimitive>, 'className'> & {\n  className?: string\n}) {\n  const flow = use(TokenFlowContext)\n  const boxRef = useMemo(\n    () =>\n      mergeRefs<HTMLDivElement>(markMounted, (box) => {\n        flow?.setBox(box)\n      }),\n    [flow],\n  )\n  return (\n    <div\n      ref={boxRef}\n      data-token-input-box=''\n      onPointerDown={focusEditor}\n      className={cn(\n        inputBoxClassName,\n        textareaRadiusClassName,\n        'cursor-text items-stretch has-data-disabled:pointer-events-none has-data-disabled:opacity-50',\n        className,\n      )}\n    >\n      <TokenInputEditorPrimitive\n        className={cn(\n          // A line fits a token with room around it, at every density.\n          textareaSizeClassName,\n          'scrollbar-thin relative min-w-0 overflow-y-auto py-1.5 leading-[calc(var(--control-height-xs)+0.25rem)] wrap-break-word whitespace-pre-wrap',\n          'data-readonly:text-muted-foreground',\n          // A token sits in the line as a word does. `align-middle` sits it a\n          // little low beside the text; a tenth of the font size centres it\n          // on the line, at every text size.\n          '[&_[data-slot=token-input-host]]:mx-px [&_[data-slot=token-input-host]]:inline-block [&_[data-slot=token-input-host]]:max-w-full [&_[data-slot=token-input-host]]:-translate-y-[0.1em] [&_[data-slot=token-input-host]]:align-middle',\n          // The placeholder, which ui-sdk gives as `aria-placeholder`.\n          'data-empty:before:text-muted-foreground data-empty:before:pointer-events-none data-empty:before:absolute data-empty:before:inset-x-(--control-padding) data-empty:before:truncate data-empty:before:content-[attr(aria-placeholder)]',\n        )}\n        {...props}\n      />\n      <InputInvalidIcon className='absolute end-0 top-2.5' />\n    </div>\n  )\n}\n\nconst tokenSpinnerSwap = cn(\n  swapIconClassName,\n  '-me-1 [--button-height:var(--control-height-xs)]',\n)\n\n/**\n * A token's chip, the Tag input's own: what it holds as children, or a\n * function of `{ token }` (its label by default). It shows a spinner while\n * it loads, a dashed edge when it is unresolved, and the focus ring while it\n * is selected.\n */\nfunction TokenInputToken({\n  className,\n  children,\n  ref,\n  ...props\n}: Omit<ComponentProps<typeof TokenInputTokenPrimitive>, 'className' | 'children'> & {\n  className?: string\n  children?: ReactNode | ((state: TokenInputTokenState) => ReactNode)\n}) {\n  const chip = useRef<HTMLSpanElement>(null)\n  const chipRef = useMemo(() => mergeRefs(chip, ref), [ref])\n  const flow = use(TokenFlowContext)\n  useTokenFlow(chip, flow)\n  return (\n    <TokenInputTokenPrimitive\n      ref={chipRef}\n      className={(state) =>\n        cn(\n          chipClassName,\n          chipLeavingClassName,\n          'px-2 whitespace-nowrap has-data-[slot=token-input-token-remove]:pe-0',\n          '[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing),scale_var(--motion-enter-duration)_var(--motion-enter-easing),color_var(--motion-press-duration)_var(--motion-press-fade-easing),box-shadow_var(--motion-press-duration)_var(--motion-press-fade-easing)] motion-reduce:[transition:opacity_var(--motion-enter-duration)_var(--motion-enter-easing)]',\n          // A token the change brings in scales in on `enter` once the field\n          // has painted, as a tag does; one whose chip is drawn afresh stays.\n          state.token.id &&\n            flow?.entering.has(state.token.id) &&\n            'in-data-mounted:starting:opacity-0 motion-safe:in-data-mounted:starting:scale-95',\n          'data-[selected]:ring-3 data-[selected]:ring-ring/50 forced-colors:data-[selected]:outline-2 forced-colors:data-[selected]:outline-[Highlight]',\n          // Selected wins over the dashed edge, where forced colours drop the ring.\n          'forced-colors:[&[data-selected][data-unresolved]]:outline-2 forced-colors:[&[data-selected][data-unresolved]]:outline-solid forced-colors:[&[data-selected][data-unresolved]]:outline-[Highlight]',\n          'data-unresolved:outline-muted-foreground data-unresolved:bg-transparent data-unresolved:outline-1 data-unresolved:-outline-offset-1 data-unresolved:outline-dashed',\n          className,\n        )\n      }\n      {...props}\n    >\n      {(state) => (\n        <TokenChip state={state}>\n          {typeof children === 'function' ? children(state) : children}\n        </TokenChip>\n      )}\n    </TokenInputTokenPrimitive>\n  )\n}\n\n/** What a chip holds: the spinner while it loads, then its label, whole on hover while it is cut. */\nfunction TokenChip({\n  state,\n  children,\n}: {\n  state: TokenInputTokenState\n  children: ReactNode\n}) {\n  const spinning = useSpinner(state.pending)\n  return (\n    <>\n      {/* The spinner rolls in and widens the chip, as on a Button; its box's\n          margin takes back the chip's gap while it is empty. */}\n      <Swap align='start' roll className={tokenSpinnerSwap}>\n        {spinning ? (\n          <span className='flex pe-1'>\n            <Spinner aria-hidden className='size-3' />\n          </span>\n        ) : null}\n      </Swap>\n      <CutTooltip\n        // Its label, or the spans that hold it, such as beside a picture.\n        labels='[data-token-label], [data-token-label] > span'\n        text={state.token.label}\n        render={\n          <span\n            data-token-label=''\n            className='flex min-w-0 items-center gap-1 [&>span]:min-w-0 [&>span]:truncate [&>span]:[unicode-bidi:plaintext]'\n          >\n            {children ?? state.token.label}\n          </span>\n        }\n      />\n    </>\n  )\n}\n\n/**\n * A chip that goes leaves as a copy from where it was, in the field's box,\n * on Backspace, undo, a cut or a failed upload; one an undo brings back\n * while its copy still leaves turns back from where the copy had got to.\n */\nfunction useTokenFlow(chip: { current: HTMLSpanElement | null }, flow: TokenFlow | null) {\n  useLayoutEffect(() => {\n    const element = chip.current\n    const box = element?.closest<HTMLElement>('[data-token-input-box]')\n    if (!element || !box) return\n    const id = tokenIdOf(element)\n    const copy = id\n      ? box.querySelector<HTMLElement>(\n          `:scope > [data-leaving-token=\"${CSS.escape(id)}\"]`,\n        )\n      : null\n    if (copy) returnFromCopy(element, copy)\n    return () => leaveChip(element, box, id, flow)\n  }, [chip, flow])\n}\n\n/** The id of the token a chip is drawn for, from the element ui-sdk holds it in. */\nfunction tokenIdOf(chip: HTMLElement) {\n  return chip.closest<HTMLElement>('[data-token-id]')?.dataset.tokenId ?? null\n}\n\n/** Where a chip is now, in its field's box, or null when the field shows none of it. */\nfunction seeChip(chip: HTMLElement, box: HTMLElement, editor: HTMLElement): Seen | null {\n  const seen = chip.getBoundingClientRect()\n  const frame = box.getBoundingClientRect()\n  // Only what showed of it leaves: the field clips a chip scrolled partly out.\n  const clip = clipInside(seen, editor.getBoundingClientRect())\n  if (clip === null) return null\n  return {\n    style: {\n      left: `${seen.left - frame.left - box.clientLeft}px`,\n      top: `${seen.top - frame.top - box.clientTop}px`,\n      width: `${seen.width}px`,\n      height: `${seen.height}px`,\n      clipPath: clip,\n    },\n    from: fromWhereItIs(chip),\n  }\n}\n\n/**\n * Leaves a copy of a chip whose token the latest change removed, from where\n * it was seen, once React has taken it out: an effect's cleanup also runs\n * for a chip that stays (Strict Mode), and for one drawn afresh.\n */\nfunction leaveChip(\n  chip: HTMLElement,\n  box: HTMLElement,\n  id: string | null,\n  flow: TokenFlow | null,\n) {\n  queueMicrotask(() => {\n    const seen = id ? flow?.leaving.get(id) : undefined\n    if (!id || !seen || chip.isConnected || !box.isConnected) return\n    flow?.leaving.delete(id)\n    const copy = leaveAsCopy(chip, { parent: box, ...seen })\n    copy.dataset.leavingToken = id\n  })\n}\n\n/**\n * The `clip-path` that shows only the part of `seen` inside `view`, or\n * null when none of it is: `inset()` in CSS pixels from each edge.\n */\nfunction clipInside(\n  seen: Pick<DOMRect, 'top' | 'right' | 'bottom' | 'left'>,\n  view: Pick<DOMRect, 'top' | 'right' | 'bottom' | 'left'>,\n) {\n  const top = Math.max(0, view.top - seen.top)\n  const right = Math.max(0, seen.right - view.right)\n  const bottom = Math.max(0, seen.bottom - view.bottom)\n  const left = Math.max(0, view.left - seen.left)\n  const height = seen.bottom - seen.top\n  const width = seen.right - seen.left\n  if (top + bottom >= height || left + right >= width) return null\n  return top + right + bottom + left === 0\n    ? ''\n    : `inset(${top}px ${right}px ${bottom}px ${left}px)`\n}\n\n/**\n * Removes its token. ui-sdk keeps it from screen readers and the tab order,\n * since Backspace removes a token from the keyboard, and it hides while the\n * field is disabled or read-only.\n */\nfunction TokenInputTokenRemove({\n  className,\n  children,\n  ...props\n}: Omit<ComponentProps<typeof TokenInputTokenRemovePrimitive>, 'className'> & {\n  className?: string\n}) {\n  return (\n    <TokenInputTokenRemovePrimitive\n      className={cn(\n        chipRemoveClassName,\n        'data-disabled:hidden data-readonly:hidden',\n        className,\n      )}\n      {...props}\n    >\n      {children ?? <ChipRemoveIcon />}\n    </TokenInputTokenRemovePrimitive>\n  )\n}\n\nexport {\n  TokenInput,\n  TokenInputEditor,\n  TokenInputToken,\n  TokenInputTokenRemove,\n  clipInside,\n  createTokenInputController,\n  defaultCodec,\n  fromText,\n  toLabel,\n  toText,\n}\nexport type { Token, TokenCodec, TokenInputController, TokenInputProps, TokenInputValue }\n",
      "type": "registry:component",
      "target": "@components/kino/token-input.tsx"
    }
  ],
  "type": "registry:component"
}