# Animated Listbox for UI SDK (/docs/components/listbox)

One highlight glides between options and checks pop in as you choose.

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

import { Listbox, ListboxItem, ListboxItemIndicator } from "@/components/keyframery/listbox"

/* The demo plays itself: toppings are added and removed (the check draws, the box pops) while the
   highlight glides between rows; then the crust changes and changes back. */
const topping = (n: number) => `[aria-labelledby="toppings-label"] > [data-slot=listbox-item]:nth-child(${n})`
const crust = (n: number) => `[aria-labelledby="crust-label"] > [data-slot=listbox-item]:nth-child(${n})`

const crusts = [
  { value: "thin", label: "Thin and crisp" },
  { value: "classic", label: "Classic" },
  { value: "sourdough", label: "Sourdough, 48h" },
]

const toppings = [
  { value: "basil", label: "Fresh basil", price: 0.5 },
  { value: "burrata", label: "Burrata", price: 3 },
  { value: "mushroom", label: "Wild mushrooms", price: 2 },
  { value: "olive", label: "Black olives", price: 1 },
  { value: "nduja", label: "’Nduja", price: 2.5 },
  { value: "anchovy", label: "Anchovies", price: 2, disabled: true },
]

const base = 9
const euro = (n: number) => `€${n.toFixed(2)}`

export default function ListboxDemo() {
  const [picked, setPicked] = React.useState<string[]>(["basil", "burrata"])
  const total = base + toppings.filter((t) => picked.includes(t.value)).reduce((sum, t) => sum + t.price, 0)

  return (
    <div className="w-[460px]">
      <div className="flex items-baseline justify-between">
        <h3 className="text-[15px] font-semibold tracking-tight">Build your pizza</h3>
        <span className="text-[13px] font-medium tabular-nums">{euro(total)}</span>
      </div>
      <div className="mt-4 grid grid-cols-[160px_1fr] gap-3">
        <div>
          <div id="crust-label" className="mb-2 text-[12px] font-medium text-muted-foreground">
            Crust
          </div>
          <Listbox aria-labelledby="crust-label" defaultValue="sourdough">
            {crusts.map((c) => (
              <ListboxItem key={c.value} value={c.value}>
                {c.label}
                <ListboxItemIndicator />
              </ListboxItem>
            ))}
          </Listbox>
        </div>
        <div>
          <div id="toppings-label" className="mb-2 flex justify-between text-[12px] font-medium text-muted-foreground">
            Toppings
            <span className="tabular-nums">{picked.length} chosen</span>
          </div>
          <Listbox
            aria-labelledby="toppings-label"
            multiple
            value={picked}
            onValueChange={(value) => setPicked(value)}
          >
            {toppings.map((t) => (
              <ListboxItem key={t.value} value={t.value} label={t.label} disabled={t.disabled}>
                <span className="min-w-0 flex-1 truncate">{t.label}</span>
                <span className="text-[12px] text-muted-foreground tabular-nums">
                  {t.disabled ? "Out today" : `+${euro(t.price)}`}
                </span>
                <ListboxItemIndicator className="ms-1" />
              </ListboxItem>
            ))}
          </Listbox>
        </div>
      </div>
    </div>
  )
}
```

## Installation [#installation]

```bash
npx shadcn@latest add @keyframery/listbox
```

This adds `components/keyframery/listbox.tsx` and its primitive, `components/keyframery/primitives/listbox.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 {
  Listbox,
  ListboxGroup,
  ListboxGroupLabel,
  ListboxItem,
  ListboxItemIcon,
  ListboxItemIndicator,
  ListboxItems,
  ListboxSeparator,
} from "@/components/keyframery/listbox"
```

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

## What moves [#what-moves]

| Move      | What you see                          |
| --------- | ------------------------------------- |
| **Glide** | One highlight glides between options. |
| **Pop**   | A check pops in as you choose.        |

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 listbox 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/listbox"

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

## Parts [#parts]

The finished component exports 8 parts:

`Listbox`, `ListboxGroup`, `ListboxGroupLabel`, `ListboxItem`, `ListboxItemIcon`, `ListboxItemIndicator`, `ListboxItems`, `ListboxSeparator`

## Accessibility [#accessibility]

Keyboard, focus and screen-reader behaviour come from UI SDK and are not changed. With reduced motion turned on, nothing in the listbox 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/listbox.tsx**

```tsx
"use client"

/* Styled listbox: the animated primitive plus the Keyframery look. */

import {
  createListboxController,
  type ListData,
  Listbox as ListboxRoot,
  ListboxGroup as ListboxGroupPart,
  ListboxGroupLabel as ListboxGroupLabelPart,
  ListboxItem as ListboxItemPart,
  ListboxItemIcon as ListboxItemIconPart,
  ListboxItemIndicator as ListboxItemIndicatorPart,
  type ListboxProps,
  ListboxSeparator as ListboxSeparatorPart,
} from "@/components/keyframery/primitives/listbox"
import * as React from "react"

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

function CheckIcon() {
  return (
    <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="m3.5 8.5 3 3 6-7" />
    </svg>
  )
}

/* The frame is a field that holds rows. It takes the field's focus ring while a row inside
   has keyboard focus. */
function Listbox<T = string, Multiple extends boolean | undefined = false>({
  className,
  ...props
}: ListboxProps<T, Multiple>) {
  return (
    <ListboxRoot<T, Multiple>
      {...({
        ...props,
        className: cn(
          "group/listbox flex max-h-72 flex-col gap-px overflow-y-auto overscroll-contain rounded-[12px] bg-background p-1.5 text-[13px] outline-none scroll-py-1.5",
          "data-[orientation=horizontal]:flex-row data-[orientation=horizontal]:overflow-x-auto data-[orientation=horizontal]:overflow-y-hidden",
          "shadow-[0_0_0_1px_rgb(0_0_0/0.09),0_1px_2px_rgb(0_0_0/0.05)] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.1)]",
          "transition-shadow duration-[calc(150ms*var(--kf-speed,1))] motion-reduce:transition-none!",
          "before:rounded-[8px] before:bg-accent",
          "hover:shadow-[0_0_0_1px_rgb(0_0_0/0.16),0_1px_2px_rgb(0_0_0/0.05)] dark:hover:shadow-[0_0_0_1px_rgb(255_255_255/0.16)]",
          "has-focus-visible:shadow-[0_0_0_1px_var(--ring)] has-focus-visible:ring-[3px] has-focus-visible:ring-ring/25 dark:has-focus-visible:shadow-[0_0_0_1px_var(--ring)]",
          "focus-visible:shadow-[0_0_0_1px_var(--ring)] focus-visible:ring-[3px] focus-visible:ring-ring/25 dark:focus-visible:shadow-[0_0_0_1px_var(--ring)]",
          "aria-invalid:shadow-[0_0_0_1px_var(--destructive)] dark:aria-invalid:shadow-[0_0_0_1px_var(--destructive)]",
          "data-disabled:cursor-not-allowed data-disabled:opacity-50 data-readonly:bg-muted/40",
          className,
        ),
      } as ListboxProps<T, Multiple>)}
    />
  )
}

/* A row. No background of its own: the primitive's highlight glides under it. */
function ListboxItem<T = string>({
  className,
  ...props
}: React.ComponentProps<typeof ListboxItemPart<T>>) {
  return (
    <ListboxItemPart<T>
      className={cn(
        "group/item relative flex min-h-8 shrink-0 cursor-default items-center gap-2 rounded-[8px] px-2 py-1.5 leading-4 text-foreground outline-none select-none",
        "data-disabled:cursor-not-allowed data-disabled:text-muted-foreground/60",
        "group-data-readonly/listbox:cursor-default",
        "[[data-has-icons]_&:not([data-has-icon])]:ps-8",
        className,
      )}
      {...props}
    />
  )
}

/* The selection mark. A single list shows a check; a multiple list a small box that fills.
   The primitive draws the check and pops the mark in. */
function ListboxItemIndicator({
  className,
  children,
  keepMounted = true,
  ...props
}: React.ComponentProps<typeof ListboxItemIndicatorPart>) {
  return (
    <ListboxItemIndicatorPart
      keepMounted={keepMounted}
      className={cn(
        "ms-auto grid size-4 shrink-0 place-items-center text-foreground [&_svg]:size-4",
        /* Multiple: a small box, empty until chosen. */
        "group-aria-multiselectable/listbox:rounded-[5px] group-aria-multiselectable/listbox:text-primary-foreground group-aria-multiselectable/listbox:[&_svg]:size-3",
        "group-aria-multiselectable/listbox:shadow-[inset_0_0_0_1px_rgb(0_0_0/0.18)] dark:group-aria-multiselectable/listbox:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.2)]",
        "group-aria-multiselectable/listbox:transition-[background-color,box-shadow] group-aria-multiselectable/listbox:duration-[calc(150ms*var(--kf-speed,1))]",
        "group-aria-multiselectable/listbox:data-selected:bg-primary group-aria-multiselectable/listbox:data-selected:shadow-[inset_0_1px_0_rgb(255_255_255/0.14),0_1px_2px_rgb(0_0_0/0.2)]",
        "dark:group-aria-multiselectable/listbox:data-selected:shadow-[inset_0_1px_0_rgb(255_255_255/0.6)]",
        "group-aria-multiselectable/listbox:[&_svg]:[stroke-width:2] group-data-disabled/item:opacity-50",
        "motion-reduce:transition-none!",
        className,
      )}
      {...props}
    >
      {children ?? <CheckIcon />}
    </ListboxItemIndicatorPart>
  )
}

function ListboxItemIcon({
  className,
  ...props
}: React.ComponentProps<typeof ListboxItemIconPart>) {
  return (
    <ListboxItemIconPart
      className={cn(
        "grid size-4 shrink-0 place-items-center text-muted-foreground transition-colors duration-[calc(150ms*var(--kf-speed,1))] [&_svg]:size-4",
        "group-data-highlighted/item:text-current group-data-highlighted/item:duration-0 group-data-selected/item:text-foreground",
        "rtl:data-mirror:-scale-x-100 motion-reduce:transition-none!",
        className,
      )}
      {...props}
    />
  )
}

function ListboxGroup({
  className,
  ...props
}: React.ComponentProps<typeof ListboxGroupPart>) {
  return <ListboxGroupPart className={cn("flex flex-col gap-px", className)} {...props} />
}

function ListboxGroupLabel({
  className,
  ...props
}: React.ComponentProps<typeof ListboxGroupLabelPart>) {
  return (
    <ListboxGroupLabelPart
      className={cn(
        "px-2 pt-1.5 pb-1 text-[11px] leading-4 font-medium text-muted-foreground select-none",
        "[[data-has-icons]_&]:ps-8",
        className,
      )}
      {...props}
    />
  )
}

function ListboxSeparator({
  className,
  ...props
}: React.ComponentProps<typeof ListboxSeparatorPart>) {
  return (
    <ListboxSeparatorPart
      className={cn(
        "-mx-1.5 my-1 h-px shrink-0 bg-border",
        "group-data-[orientation=horizontal]/listbox:mx-1 group-data-[orientation=horizontal]/listbox:my-0 group-data-[orientation=horizontal]/listbox:h-auto group-data-[orientation=horizontal]/listbox:w-px",
        className,
      )}
      {...props}
    />
  )
}

/* Renders items passed as data with the styled parts above. */
function ListboxItems({ items }: { items?: ListData<unknown> }) {
  return (items ?? []).map((entry, index) => {
    if (typeof entry === "string") {
      return (
        <ListboxItem key={entry} value={entry}>
          {entry}
          <ListboxItemIndicator />
        </ListboxItem>
      )
    }
    if ("type" in entry && entry.type === "separator") {
      return <ListboxSeparator key={`separator-${index}`} />
    }
    if ("type" in entry && entry.type === "group") {
      return (
        <ListboxGroup key={`group-${entry.label ?? index}`}>
          {entry.label && <ListboxGroupLabel>{entry.label}</ListboxGroupLabel>}
          <ListboxItems items={entry.items} />
        </ListboxGroup>
      )
    }
    const { value, label, disabled } = entry
    return (
      <ListboxItem<unknown>
        key={typeof value === "string" ? value : index}
        value={value}
        label={label}
        disabled={disabled}
      >
        {label}
        <ListboxItemIndicator />
      </ListboxItem>
    )
  })
}

export type { ListData } from "@/components/keyframery/primitives/listbox"
export {
  createListboxController,
  Listbox,
  ListboxGroup,
  ListboxGroupLabel,
  ListboxItem,
  ListboxItemIcon,
  ListboxItemIndicator,
  ListboxItems,
  ListboxSeparator,
}
```

**components/keyframery/primitives/listbox.tsx**

```tsx
"use client"

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

   - Glide: one highlight springs from row to row (CSS anchor positioning): to the row under the
     pointer, or to the focused row while the list has focus. Its neutral surface follows the text
     colour; give `before:bg-…` and `before:rounded-…` to restyle it.
   - Draw: a chosen row's check draws itself, and its indicator pops in (`ease-pop`, 0.6 to 1). */

import {
  Listbox as ListboxPart,
  ListboxItem as ListboxItemPart,
  ListboxItemIndicator as ListboxItemIndicatorPart,
  type ListboxProps,
} from "@ui-sdk/react/listbox"
import * as React from "react"

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

export * from "@ui-sdk/react/listbox"

const keyframes = "@keyframes kf-pop-in{from{scale:0.6}}"

function Listbox<T = string, Multiple extends boolean | undefined = false>({
  className,
  ...props
}: ListboxProps<T, Multiple>) {
  /* Hold the pop until after the first paint, so chosen rows don't pop on load. */
  const [ready, setReady] = React.useState(false)
  React.useEffect(() => {
    const timer = setTimeout(() => setReady(true), 150)
    return () => clearTimeout(timer)
  }, [])
  return (
    <>
      <style href="kf-listbox-pop" precedence="default">
        {keyframes}
      </style>
      <ListboxPart<T, Multiple>
        {...({
          ...props,
          "data-kf-ready": ready || undefined,
          className: cn(
            "group/kf-lb relative isolate [anchor-scope:--kf-hl]",
            "before:pointer-events-none before:absolute before:-z-10 before:hidden before:bg-[color-mix(in_oklch,currentColor_9%,transparent)]",
            "before:[position-anchor:--kf-hl] before:top-[anchor(top)] before:right-[anchor(right)] before:bottom-[anchor(bottom)] before:left-[anchor(left)]",
            "before:[transition:top_calc(260ms*var(--kf-speed,1))_var(--ease-spring),right_calc(260ms*var(--kf-speed,1))_var(--ease-spring),bottom_calc(260ms*var(--kf-speed,1))_var(--ease-spring),left_calc(260ms*var(--kf-speed,1))_var(--ease-spring),opacity_calc(150ms*var(--kf-speed,1))_var(--ease-house)]",
            "has-[[data-slot=listbox-item]:hover]:before:block focus-within:has-[[data-highlighted]]:before:block starting:before:opacity-0",
            "motion-reduce:before:[transition:none]!",
            className,
          ),
        } as ListboxProps<T, Multiple>)}
      />
    </>
  )
}

/* The highlight follows the pointer; without one, the focused row. */
function ListboxItem<T = string>({ className, ...props }: React.ComponentProps<typeof ListboxItemPart<T>>) {
  return (
    <ListboxItemPart<T>
      className={cn(
        "hover:[anchor-name:--kf-hl] data-highlighted:[anchor-name:--kf-hl]",
        "group-has-[[data-slot=listbox-item]:hover]/kf-lb:data-highlighted:not-hover:[anchor-name:none]",
        className,
      )}
      {...props}
    />
  )
}

/* Draw: the check's stroke draws in as its row is chosen, and the indicator pops.
   Works with any check path up to 24 units long. */
function ListboxItemIndicator({ className, ...props }: React.ComponentProps<typeof ListboxItemIndicatorPart>) {
  return (
    <ListboxItemIndicatorPart
      className={cn(
        "[&_:is(path,polyline)]:[stroke-dasharray:24] [&_:is(path,polyline)]:[stroke-dashoffset:24]",
        "[&_:is(path,polyline)]:transition-[stroke-dashoffset] [&_:is(path,polyline)]:duration-[calc(260ms*var(--kf-speed,1))] [&_:is(path,polyline)]:ease-house",
        "data-selected:[&_:is(path,polyline)]:[stroke-dashoffset:0] data-selected:[&_:is(path,polyline)]:delay-[calc(75ms*var(--kf-speed,1))]",
        "data-selected:[&_:is(path,polyline)]:starting:[stroke-dashoffset:24]",
        "motion-reduce:animate-none! group-data-kf-ready/kf-lb:data-selected:[animation:kf-pop-in_calc(380ms*var(--kf-speed,1))_var(--ease-pop)]",
        "motion-reduce:[&_:is(path,polyline)]:transition-none motion-reduce:animate-none!",
        className,
      )}
      {...props}
    />
  )
}

export { Listbox, ListboxItem, ListboxItemIndicator }
```

## Questions

### How does the animated Listbox for UI SDK move?

Glide: One highlight glides between options. Pop: A check pops in as you choose.

### Do I need Motion or Framer Motion for the animated Listbox?

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/listbox` instead. It has the same parts and props as `@ui-sdk/react/listbox` and adds motion only.

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

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