# Animated Token Input for UI SDK (/docs/components/token-input)

Tokens pop into the field as you add them, and the remove buttons press in.

```tsx title="example.tsx"
import * as React from "react"

import {
  createTokenInputController,
  TokenInput,
  TokenInputEditor,
  TokenInputToken,
  TokenInputTokenRemove,
} from "@/components/keyframery/token-input"

/* The demo plays itself: two suggested people are added and pop in as tokens, then removed. */
const lastRemove = '[data-slot="token-input-host"]:last-of-type [data-slot="token-input-token-remove"]'

const suggested = ["leo@grantstudio.co", "fatima.noor@outlook.com"]

type Value = React.ComponentProps<typeof TokenInput>["defaultValue"] & {}
type Segment = Value[number]

const typos = ["gmial.com", "gmal.com", "hotmial.com", "yaho.com"]

function emailToken(email: string): Segment {
  const domain = email.split("@")[1] ?? ""
  return {
    type: "email",
    value: email.toLowerCase(),
    label: email.toLowerCase(),
    status: typos.includes(domain.toLowerCase()) ? "unresolved" : undefined,
  }
}

/* An address followed by a space, comma or semicolon becomes a token. */
function tokenize(value: Value): Value {
  const out: Value = []
  for (const segment of value) {
    if (typeof segment !== "string") {
      out.push(segment)
      continue
    }
    const parts = segment.split(/([^\s,;]+@[^\s,;]+\.[a-z]{2,})[\s,;]+/i)
    parts.forEach((part, index) => {
      if (index % 2 === 1) out.push(emailToken(part))
      else if (part) out.push(part)
    })
  }
  return out
}

const initial: Value = [
  emailToken("dana@whitfield.uk"),
  emailToken("marcus@gmial.com"),
  emailToken("joanna.park@hey.com"),
]

function initials(email: string) {
  return email.slice(0, 1).toUpperCase()
}

export default function TokenInputDemo() {
  const [value, setValue] = React.useState<Value>(initial)
  const [invites] = React.useState(createTokenInputController)
  const people = value.filter((segment) => typeof segment !== "string")
  const left = suggested.filter((email) => !people.some((token) => token.value === email))
  const typo = people.some((token) => token.status === "unresolved")

  return (
    <div className="w-[420px]">
      <div className="mb-2 flex items-baseline justify-between">
        <span id="invite-label" className="text-[13px] leading-none font-medium">
          Invite to “Ski week”
        </span>
        <span className="text-[12px] text-muted-foreground tabular-nums">{people.length} people</span>
      </div>
      <TokenInput
        value={value}
        controller={invites}
        onValueChange={(next) => setValue(tokenize(next))}
        renderToken={(token) => (
          <TokenInputToken>
            <span className="-ml-1 grid size-4 place-items-center rounded-full bg-muted text-[9px] font-semibold text-muted-foreground in-data-selected:bg-primary-foreground/20 in-data-selected:text-primary-foreground in-data-unresolved:bg-destructive/15 in-data-unresolved:text-destructive">
              {initials(token.label)}
            </span>
            {token.label}
            <TokenInputTokenRemove />
          </TokenInputToken>
        )}
      >
        <TokenInputEditor aria-labelledby="invite-label" placeholder="Add emails, separated by commas" />
      </TokenInput>
      <div className="mt-3 flex min-h-7 flex-wrap items-center gap-1.5">
        {left.length > 0 && <span className="mr-0.5 text-[12px] text-muted-foreground">Suggested</span>}
        {left.map((email) => (
            <button
              key={email}
              type="button"
              data-suggest={email}
              onClick={() => invites.insert(emailToken(email), { at: "end" })}
              className="inline-flex h-7 cursor-pointer items-center gap-1 rounded-full px-2.5 text-[12px] leading-none font-medium text-muted-foreground shadow-[inset_0_0_0_1px_var(--border)] outline-none transition-[color,background-color,scale] duration-200 ease-pop hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring active:scale-[0.96] motion-reduce:transition-none"
            >
              <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" aria-hidden="true" className="size-3">
                <path d="M8 3.5v9M3.5 8h9" />
              </svg>
              {email}
            </button>
          ))}
      </div>
      <p className={"mt-2 text-[12px] " + (typo ? "text-destructive" : "text-muted-foreground")}>
        {typo ? "One address looks mistyped. Did you mean gmail.com?" : "Type an email and press space or comma."}
      </p>
      <div className="mt-5 flex justify-end gap-2">
        <button
          type="button"
          className="h-8 cursor-pointer rounded-[9px] bg-background px-3 text-[13px] leading-none font-medium shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_1px_rgb(0_0_0/0.05),0_3px_6px_-2px_rgb(0_0_0/0.1)] transition-[scale,translate] duration-100 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 active:translate-y-px active:scale-[0.985] dark:bg-accent dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07),inset_0_1px_0_rgb(255_255_255/0.08),0_2px_6px_-1px_rgb(0_0_0/0.6)]"
        >
          Copy invite link
        </button>
        <button
          type="button"
          disabled={people.length === 0}
          className="h-8 cursor-pointer rounded-[9px] bg-primary px-3 text-[13px] leading-none font-medium text-primary-foreground shadow-[inset_0_1px_0_rgb(255_255_255/0.14),0_1px_2px_rgb(0_0_0/0.25)] transition-[scale,translate,opacity] duration-100 outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 active:translate-y-px active:scale-[0.985] disabled:pointer-events-none disabled:opacity-50"
        >
          Send {people.length} {people.length === 1 ? "invite" : "invites"}
        </button>
      </div>
    </div>
  )
}
```

## Installation [#installation]

```bash
npx shadcn@latest add @keyframery/token-input
```

This adds `components/keyframery/token-input.tsx` and its primitive, `components/keyframery/primitives/token-input.tsx`, to your project, and installs `@ui-sdk/react`. The motion tokens are added to your global CSS the first time you install a component.

## Usage [#usage]

```tsx
import {
  TokenInput,
  TokenInputEditor,
  TokenInputToken,
  TokenInputTokenRemove,
} from "@/components/keyframery/token-input"
```

The parts and props are the same as UI SDK's Token Input. For every prop, see the [UI SDK token input reference](https://ui-sdk.dev/docs/components/token-input).

## What moves [#what-moves]

| Move      | What you see                               |
| --------- | ------------------------------------------ |
| **Pop**   | Tokens pop into the field as you add them. |
| **Press** | The remove buttons press in.               |

Timing and springiness follow the [motion style](/docs/motion-styles) you set, so this component moves like the rest of your app.

## Swap the import [#swap-the-import]

Already using UI SDK's token input with your own styles? Keep your markup and change one line. The primitive adds motion and nothing else.

```tsx
// Before
import { … } from "@ui-sdk/react/token-input"

// After: same parts, same props, now animated
import { … } from "@/components/keyframery/primitives/token-input"
```

## Parts [#parts]

The finished component exports 4 parts:

`TokenInput`, `TokenInputEditor`, `TokenInputToken`, `TokenInputTokenRemove`

## Accessibility [#accessibility]

Keyboard, focus and screen-reader behaviour come from UI SDK and are not changed. With reduced motion turned on, nothing in the token input moves: changes happen at once or with a short fade. More in [Accessibility](/docs/accessibility).

## Source [#source]

The code that lands in your project. It is yours to change.

**components/keyframery/token-input.tsx**

```tsx
"use client"

/* Styled token input: the animated primitive plus the Keyframery look. */

import {
  TokenInput as TokenInputRoot,
  TokenInputEditor as TokenInputEditorPart,
  TokenInputToken as TokenInputTokenPart,
  TokenInputTokenRemove as TokenInputTokenRemovePart,
  createTokenInputController,
  defaultCodec,
  fromText,
  toLabel,
  toText,
  type Token,
} from "@/components/keyframery/primitives/token-input"
import * as React from "react"

import { cn } from "@/lib/utils"

function XIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="m4.5 4.5 7 7m0-7-7 7" />
    </svg>
  )
}

/* Without a renderToken of its own, each token is a small key with its label and an x. */
function defaultRenderToken(token: Token) {
  return (
    <TokenInputToken>
      {token.label}
      <TokenInputTokenRemove />
    </TokenInputToken>
  )
}

/* Renders no element of its own. */
function TokenInput({
  renderToken = defaultRenderToken,
  ...props
}: React.ComponentProps<typeof TokenInputRoot>) {
  return <TokenInputRoot renderToken={renderToken} {...props} />
}

/* The field: text and tokens wrap inside one box that grows with them. */
function TokenInputEditor({
  className,
  ...props
}: React.ComponentProps<typeof TokenInputEditorPart>) {
  return (
    <TokenInputEditorPart
      className={cn(
        "relative min-h-9 w-full min-w-0 cursor-text rounded-[10px] bg-background px-2 py-[5px] text-[13px] leading-[26px] break-words whitespace-pre-wrap text-foreground outline-none",
        "[--field-line:rgb(0_0_0/0.09)] dark:[--field-line:rgb(255_255_255/0.1)]",
        "shadow-[0_0_0_1px_var(--field-line),0_1px_2px_rgb(0_0_0/0.05)] dark:shadow-[0_0_0_1px_var(--field-line)]",
        "transition-[box-shadow] duration-[calc(150ms*var(--kf-speed,1))] ease-house motion-reduce:transition-none!",
        "hover:[--field-line:rgb(0_0_0/0.16)] dark:hover:[--field-line:rgb(255_255_255/0.18)]",
        "focus-visible:ring-[3px] focus-visible:ring-ring/25 focus-visible:[--field-line:var(--ring)] dark:focus-visible:[--field-line:var(--ring)]",
        "aria-invalid:ring-destructive/25 aria-invalid:[--field-line:var(--destructive)] dark:aria-invalid:[--field-line:var(--destructive)]",
        "data-empty:before:pointer-events-none data-empty:before:absolute data-empty:before:text-muted-foreground data-empty:before:content-[attr(aria-placeholder)]",
        "data-readonly:bg-muted/50",
        "data-disabled:cursor-not-allowed data-disabled:bg-muted data-disabled:text-muted-foreground data-disabled:[--field-line:rgb(0_0_0/0.06)] dark:data-disabled:[--field-line:rgb(255_255_255/0.06)]",
        className,
      )}
      {...props}
    />
  )
}

/* A token is a small key; the primitive pops it in when it is added. */
function TokenInputToken({
  className,
  ...props
}: React.ComponentProps<typeof TokenInputTokenPart>) {
  return (
    <TokenInputTokenPart
      className={cn(
        "mx-[2px] inline-flex h-[22px] max-w-full items-center gap-1 rounded-[7px] bg-background pr-0.5 pl-2 align-middle text-[12px] leading-none font-medium whitespace-nowrap text-foreground select-none",
        "shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_1px_rgb(0_0_0/0.05),0_3px_6px_-2px_rgb(0_0_0/0.1)]",
        "dark:bg-accent dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07),inset_0_1px_0_rgb(255_255_255/0.08),0_2px_6px_-1px_rgb(0_0_0/0.6)]",
        "[&>svg]:size-3.5 [&>svg]:shrink-0 [&>svg]:text-muted-foreground",
        /* Selected for removal or in the selection. */
        "data-selected:bg-primary data-selected:text-primary-foreground data-selected:[&>svg]:text-primary-foreground/70",
        "data-selected:shadow-[inset_0_1px_0_rgb(255_255_255/0.14),0_1px_2px_rgb(0_0_0/0.25)]",
        /* Loading. */
        "data-pending:opacity-60",
        /* Needs the user, like an address that doesn't look right. */
        "data-unresolved:bg-destructive/10 data-unresolved:text-destructive data-unresolved:shadow-[0_0_0_1px_color-mix(in_oklab,var(--destructive)_35%,transparent)] dark:data-unresolved:bg-destructive/15",
        "data-disabled:opacity-60",
        className,
      )}
      {...props}
    />
  )
}

function TokenInputTokenRemove({
  className,
  children,
  ...props
}: React.ComponentProps<typeof TokenInputTokenRemovePart>) {
  return (
    <TokenInputTokenRemovePart
      className={cn(
        "grid size-[18px] cursor-pointer place-items-center rounded-[5px] text-muted-foreground",
        "hover:bg-foreground/[0.08] hover:text-foreground",
        "in-data-selected:text-primary-foreground/70 in-data-selected:hover:bg-primary-foreground/15 in-data-selected:hover:text-primary-foreground",
        "data-disabled:pointer-events-none data-disabled:opacity-40 data-readonly:hidden",
        "[&_svg]:size-3",
        className,
      )}
      {...props}
    >
      {children ?? <XIcon />}
    </TokenInputTokenRemovePart>
  )
}

export {
  createTokenInputController,
  defaultCodec,
  fromText,
  toLabel,
  TokenInput,
  TokenInputEditor,
  TokenInputToken,
  TokenInputTokenRemove,
  toText,
}
```

**components/keyframery/primitives/token-input.tsx**

```tsx
"use client"

/* Animated drop-in for `@ui-sdk/react/token-input`: same parts, same props. Swap the import and keep your code.
   This file adds motion only. Colours, radii, shadows and spacing stay yours.

   - Token: pops in when added (scale 0.4 to 1 on `ease-pop`, with a short blur).
   - Token remove: Press. */

import {
  TokenInputToken as TokenInputTokenPart,
  TokenInputTokenRemove as TokenInputTokenRemovePart,
} from "@ui-sdk/react/token-input"
import * as React from "react"

import { cn } from "@/lib/utils"

export * from "@ui-sdk/react/token-input"

function TokenInputToken({ className, ...props }: React.ComponentProps<typeof TokenInputTokenPart>) {
  return (
    <TokenInputTokenPart
      className={cn(
        "inline-block origin-center motion-reduce:transition-none! transition-[scale,opacity,filter] duration-[calc(420ms*var(--kf-speed,1))] ease-pop",
        "starting:scale-[0.4] starting:opacity-0 starting:blur-[3px]",
        "motion-reduce:transition-none!",
        className,
      )}
      {...props}
    />
  )
}

function TokenInputTokenRemove({ className, ...props }: React.ComponentProps<typeof TokenInputTokenRemovePart>) {
  return (
    <TokenInputTokenRemovePart
      className={cn(
        "transition-[scale,color,background-color] duration-[calc(200ms*var(--kf-speed,1))] ease-pop active:scale-[0.8] motion-reduce:transition-none!",
        className,
      )}
      {...props}
    />
  )
}

export { TokenInputToken, TokenInputTokenRemove }
```

## Questions

### How does the animated Token Input for UI SDK move?

Pop: Tokens pop into the field as you add them. Press: The remove buttons press in.

### Do I need Motion or Framer Motion for the animated Token Input?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### Can I keep my own styling and only take the motion?

Yes. Import from `@/components/keyframery/primitives/token-input` instead. It has the same parts and props as `@ui-sdk/react/token-input` and adds motion only.

### What happens to the Token Input when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
