{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"combobox","type":"registry:component","title":"Combobox","description":"The person you pick flies out of the list and into the field.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/combobox.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useLayoutEffect, useRef, useState } from \"react\";\nimport { motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\nexport type Person = {\n  id: string;\n  name: string;\n  email: string;\n  avatar?: string;\n};\n\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\n// Every option row is h-12.\nconst ROW = 48;\n\nconst initials = (name: string) =>\n  name\n    .split(\" \")\n    .map((part) => part[0])\n    .join(\"\")\n    .slice(0, 2);\n\nexport function Combobox({\n  label,\n  people,\n  value,\n  onChange,\n  placeholder = \"Search people\",\n  className,\n}: {\n  label: string;\n  people: Person[];\n  value: Person | null;\n  onChange: (person: Person | null) => void;\n  placeholder?: string;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const id = useId();\n  const listId = `${id}-list`;\n  const inputRef = useRef<HTMLInputElement>(null);\n  // True once the highlight reflects intent (typing, arrows or the mouse),\n  // so tabbing past a list opened by a click doesn't pick the first person.\n  const engaged = useRef(false);\n  const [query, setQuery] = useState(\"\");\n  const [open, setOpen] = useState(false);\n  const [active, setActive] = useState(0);\n  // Only keyboard moves scroll the list; the mouse is already where it is.\n  const scrollToActive = useRef(false);\n\n  const needle = query.trim().toLowerCase();\n  const results = needle\n    ? people.filter(\n        (p) =>\n          p.name.toLowerCase().includes(needle) ||\n          p.email.toLowerCase().includes(needle),\n      )\n    : people;\n  const highlighted = open ? results[active] : undefined;\n\n  // One highlight for the whole list, gliding from row to row, so arrowing\n  // down reads as a single thing moving rather than rows blinking on and off.\n  const pillRef = useRef<HTMLLIElement>(null);\n  // Set whenever the list is rebuilt (opened or filtered): the highlight\n  // lands in place instead of sliding in from wherever it last was.\n  const pillJump = useRef(true);\n  // Scroll smoothly only for moves within a list that is already showing.\n  const scrollJump = useRef(true);\n  const slotRef = useRef<HTMLSpanElement>(null);\n  // Where the chosen person's avatar was in the list, for the flight into\n  // the field.\n  const flight = useRef<DOMRect | null>(null);\n  const [flying, setFlying] = useState(false);\n\n  useEffect(() => {\n    if (!scrollToActive.current || !highlighted) return;\n    const jump = scrollJump.current;\n    scrollJump.current = false;\n    scrollToActive.current = false;\n    document\n      .getElementById(`${id}-${highlighted.id}`)\n      ?.scrollIntoView({\n        block: \"nearest\",\n        behavior: jump || reduceMotion ? \"instant\" : \"smooth\",\n      });\n  }, [highlighted, id, reduceMotion]);\n\n  useLayoutEffect(() => {\n    const pill = pillRef.current;\n    if (!pill) return;\n    const jump = pillJump.current || !!reduceMotion;\n    pillJump.current = false;\n    pill.style.transition = jump ? \"none\" : \"\";\n    // Rows are a fixed 48px, so the index is the offset.\n    pill.style.transform = `translateY(${active * ROW}px)`;\n    if (jump) {\n      // Commits the jump before the transition comes back.\n      void pill.offsetHeight;\n      pill.style.transition = \"\";\n    }\n  }, [active, open, query, reduceMotion]);\n\n  // The avatar leaves its row and lands in the field's leading slot, scaling\n  // from 32px down to 24px on the way: the pick is carried, not swapped.\n  useLayoutEffect(() => {\n    const from = flight.current;\n    const el = slotRef.current;\n    flight.current = null;\n    if (!from || !el || !value) return;\n    const to = el.getBoundingClientRect();\n    const animation = el.animate(\n      [\n        {\n          transform: `translate(${from.left - to.left}px, ${from.top - to.top}px) scale(${from.width / to.width})`,\n        },\n        { transform: \"none\" },\n      ],\n      // 280ms on the iOS drawer curve: long enough to follow a 100px trip,\n      // settled before the next keystroke is likely.\n      { duration: 280, easing: \"cubic-bezier(0.32, 0.72, 0, 1)\" },\n    );\n    animation.onfinish = animation.oncancel = () => setFlying(false);\n    return () => animation.cancel();\n  }, [value]);\n\n  const openList = (text = query) => {\n    engaged.current = text.length > 0;\n    // Starts on the chosen person when there is one and nothing typed.\n    const start = text || !value ? 0 : Math.max(people.indexOf(value), 0);\n    setActive(start);\n    scrollToActive.current = true;\n    scrollJump.current = true;\n    pillJump.current = true;\n    setOpen(true);\n  };\n\n  const choose = (person: Person) => {\n    if (!reduceMotion && person.id !== value?.id) {\n      const from = document\n        .getElementById(`${id}-${person.id}`)\n        ?.querySelector(\"[data-avatar]\")\n        ?.getBoundingClientRect();\n      if (from) {\n        flight.current = from;\n        setFlying(true);\n      }\n    }\n    onChange(person);\n    setQuery(\"\");\n    setOpen(false);\n  };\n\n  const clear = () => {\n    onChange(null);\n    setQuery(\"\");\n    inputRef.current?.focus();\n  };\n\n  const move = (delta: number) => {\n    if (!open) return openList();\n    if (results.length === 0) return;\n    engaged.current = true;\n    scrollToActive.current = true;\n    setActive((i) => (i + delta + results.length) % results.length);\n  };\n\n  const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    switch (e.key) {\n      case \"ArrowDown\":\n        e.preventDefault();\n        move(1);\n        break;\n      case \"ArrowUp\":\n        e.preventDefault();\n        move(-1);\n        break;\n      case \"Home\":\n      case \"End\":\n        if (!open || results.length === 0) return;\n        e.preventDefault();\n        scrollToActive.current = true;\n        setActive(e.key === \"Home\" ? 0 : results.length - 1);\n        break;\n      case \"Enter\":\n        if (!highlighted) return;\n        e.preventDefault();\n        choose(highlighted);\n        break;\n      case \"Tab\":\n        // Accepts and lets focus move on as usual.\n        if (highlighted && engaged.current) choose(highlighted);\n        else setOpen(false);\n        break;\n      case \"Escape\":\n        e.preventDefault();\n        // First press closes, the next one clears.\n        if (open) setOpen(false);\n        else if (query || value) clear();\n        break;\n    }\n  };\n\n  const text = value && !query ? value.name : query;\n  const hasText = text.length > 0;\n\n  return (\n    <div className={cn(\"w-[360px] max-w-full\", className)}>\n      <label\n        htmlFor={`${id}-input`}\n        className=\"mb-2 block text-sm font-medium text-foreground\"\n      >\n        {label}\n      </label>\n      <div className=\"relative\">\n        <div className=\"relative flex h-11 items-center rounded-xl bg-background shadow-raised transition-[box-shadow] duration-150 ease-out focus-within:shadow-[0_0_0_1.5px_var(--foreground)]\">\n          {/* Leading slot swaps the search icon for the chosen avatar. */}\n          <span aria-hidden className=\"pointer-events-none grid size-11 shrink-0 place-items-center\">\n            <SwapSlot visible={!value} reduceMotion={reduceMotion}>\n              <svg {...STROKE} className=\"size-4 text-muted-foreground\">\n                <circle cx=\"7.25\" cy=\"7.25\" r=\"4.5\" />\n                <path d=\"m10.5 10.5 3 3\" />\n              </svg>\n            </SwapSlot>\n            {/* A flying avatar is already visible, so it skips the pop in.\n                z-30 carries it over the closing list (z-20) on the way up. */}\n            <SwapSlot\n              visible={!!value}\n              reduceMotion={reduceMotion}\n              instant={flying}\n            >\n              <span ref={slotRef} className=\"relative z-30 block origin-top-left\">\n                {value && <Avatar person={value} size=\"sm\" />}\n              </span>\n            </SwapSlot>\n          </span>\n          <input\n            ref={inputRef}\n            id={`${id}-input`}\n            role=\"combobox\"\n            aria-expanded={open}\n            aria-controls={listId}\n            aria-autocomplete=\"list\"\n            aria-activedescendant={\n              highlighted ? `${id}-${highlighted.id}` : undefined\n            }\n            autoComplete=\"off\"\n            spellCheck={false}\n            value={text}\n            placeholder={placeholder}\n            onChange={(e) => {\n              const next = e.target.value;\n              // Editing the chosen name means searching again.\n              if (value) onChange(null);\n              setQuery(next);\n              openList(next);\n            }}\n            onClick={() => {\n              if (!open) openList();\n            }}\n            onKeyDown={onKeyDown}\n            onBlur={() => setOpen(false)}\n            className=\"h-full min-w-0 flex-1 bg-transparent pr-11 text-[15px] text-foreground outline-hidden placeholder:text-muted-foreground\"\n          />\n          <button\n            type=\"button\"\n            aria-label=\"Clear\"\n            inert={!hasText}\n            // Keeps focus in the input, where typing continues.\n            onMouseDown={(e) => e.preventDefault()}\n            onClick={clear}\n            className={cn(\n              \"absolute right-1 grid size-9 place-items-center rounded-lg text-muted-foreground outline-hidden select-none\",\n              \"transition-[scale,color,background-color] duration-150 ease-out hover:bg-foreground/[0.06] hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[color,background-color]\",\n            )}\n          >\n            <SwapSlot visible={hasText} reduceMotion={reduceMotion}>\n              <svg aria-hidden {...STROKE} className=\"size-4\">\n                <path d=\"m4.5 4.5 7 7M11.5 4.5l-7 7\" />\n              </svg>\n            </SwapSlot>\n          </button>\n        </div>\n\n        {/* Always mounted so it can fade out. Grows from its top edge, the\n            side touching the input. Enters in 150ms, leaves in 100ms. */}\n        <div\n          className={cn(\n            \"absolute inset-x-0 top-full z-20 mt-2 origin-top rounded-xl bg-background p-1 shadow-raised\",\n            \"transition-[opacity,scale,visibility] ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-[opacity,visibility]\",\n            open\n              ? \"visible scale-100 opacity-100 duration-150\"\n              : \"invisible scale-[0.97] opacity-0 duration-100 motion-reduce:scale-100\",\n          )}\n        >\n          <ul\n            id={listId}\n            role=\"listbox\"\n            aria-label={label}\n            // Just under five 48px rows, so the clipped fifth shows it scrolls.\n            className=\"relative max-h-[232px] overflow-y-auto overscroll-contain\"\n          >\n            {/* Inside the scroller so it scrolls with the rows. 180ms\n                ease-out: quick enough to keep up with held arrow keys. */}\n            <li\n              ref={pillRef}\n              role=\"presentation\"\n              aria-hidden\n              className={cn(\n                \"pointer-events-none absolute inset-x-0 top-0 h-12 rounded-lg bg-foreground/[0.06]\",\n                \"transition-[transform,opacity] duration-180 ease-[cubic-bezier(0.23,1,0.32,1)]\",\n                highlighted ? \"opacity-100\" : \"opacity-0\",\n              )}\n            />\n            {results.map((person, i) => {\n              const isActive = i === active;\n              const isChosen = value?.id === person.id;\n              return (\n                <li\n                  key={person.id}\n                  id={`${id}-${person.id}`}\n                  role=\"option\"\n                  aria-selected={isChosen}\n                  // Keeps focus in the input so the list doesn't close\n                  // before the click lands.\n                  onMouseDown={(e) => e.preventDefault()}\n                  onClick={() => choose(person)}\n                  // Move rather than enter: scrolling the list under a\n                  // resting cursor shouldn't steal the highlight.\n                  onPointerMove={(e) => {\n                    if (e.pointerType === \"touch\" || isActive) return;\n                    engaged.current = true;\n                    setActive(i);\n                  }}\n                  className=\"relative flex h-12 cursor-default items-center gap-3 rounded-lg px-2.5 select-none\"\n                >\n                  <Avatar person={person} />\n                  <span className=\"min-w-0 flex-1\">\n                    <span className=\"block truncate text-sm text-foreground\">\n                      <Highlight text={person.name} needle={needle} />\n                    </span>\n                    <span className=\"block truncate text-xs text-muted-foreground\">\n                      {person.email}\n                    </span>\n                  </span>\n                  <svg\n                    aria-hidden\n                    {...STROKE}\n                    className={cn(\n                      \"size-4 shrink-0 text-foreground\",\n                      !isChosen && \"invisible\",\n                    )}\n                  >\n                    <path d=\"m3.5 8.5 3 3 6-7\" />\n                  </svg>\n                </li>\n              );\n            })}\n          </ul>\n          {results.length === 0 && (\n            <p className=\"flex h-12 items-center px-2.5 text-sm text-muted-foreground\">\n              No one matches &ldquo;{query.trim()}&rdquo;\n            </p>\n          )}\n        </div>\n      </div>\n      <span className=\"sr-only\" aria-live=\"polite\">\n        {open\n          ? results.length === 0\n            ? \"No results\"\n            : `${results.length} result${results.length === 1 ? \"\" : \"s\"}`\n          : \"\"}\n      </span>\n    </div>\n  );\n}\n\nfunction Highlight({ text, needle }: { text: string; needle: string }) {\n  const at = needle ? text.toLowerCase().indexOf(needle) : -1;\n  if (at < 0) return <span className=\"text-foreground\">{text}</span>;\n  // Dims the rest rather than bolding the match, so the name never\n  // reflows as letters change weight.\n  return (\n    <span className=\"text-muted-foreground\">\n      {text.slice(0, at)}\n      <mark className=\"bg-transparent text-foreground\">\n        {text.slice(at, at + needle.length)}\n      </mark>\n      {text.slice(at + needle.length)}\n    </span>\n  );\n}\n\nfunction Avatar({ person, size = \"md\" }: { person: Person; size?: \"sm\" | \"md\" }) {\n  const box = size === \"sm\" ? \"size-6\" : \"size-8\";\n  return person.avatar ? (\n    // eslint-disable-next-line @next/next/no-img-element -- tiny local SVGs gain nothing from next/image.\n    <img\n      data-avatar\n      src={person.avatar}\n      alt=\"\"\n      className={cn(\n        box,\n        // The line art is black, so it keeps a light plate in both themes.\n        \"shrink-0 rounded-full bg-[oklch(0.97_0_0)] outline-1 -outline-offset-1 outline-[oklch(0_0_0/0.1)] dark:outline-[oklch(1_0_0/0.1)]\",\n      )}\n    />\n  ) : (\n    <span\n      data-avatar\n      aria-hidden\n      className={cn(\n        box,\n        \"grid shrink-0 place-items-center rounded-full bg-foreground/[0.08] font-medium text-foreground\",\n        size === \"sm\" ? \"text-[10px]\" : \"text-xs\",\n      )}\n    >\n      {initials(person.name)}\n    </span>\n  );\n}\n\nfunction SwapSlot({\n  visible,\n  reduceMotion,\n  instant = false,\n  children,\n}: {\n  visible: boolean;\n  reduceMotion: boolean | null;\n  instant?: boolean;\n  children: React.ReactNode;\n}) {\n  const hidden = reduceMotion\n    ? { opacity: 0 }\n    : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" };\n  return (\n    <motion.span\n      className=\"col-start-1 row-start-1 grid place-items-center\"\n      initial={false}\n      animate={visible ? { scale: 1, opacity: 1, filter: \"blur(0px)\" } : hidden}\n      transition={instant ? { duration: 0 } : ICON_SWAP}\n    >\n      {children}\n    </motion.span>\n  );\n}\n\nconst STROKE = {\n  viewBox: \"0 0 16 16\",\n  fill: \"none\",\n  stroke: \"currentColor\",\n  strokeWidth: 1.5,\n  strokeLinecap: \"round\",\n  strokeLinejoin: \"round\",\n} as const;\n\nconst PEOPLE: Person[] = [\n  { id: \"ava\", name: \"Ava Moreno\", email: \"ava@acme.dev\", avatar: \"/avatars/ava.svg\" },\n  { id: \"ben\", name: \"Ben Okafor\", email: \"ben@acme.dev\", avatar: \"/avatars/ben.svg\" },\n  { id: \"cara\", name: \"Cara Lindqvist\", email: \"cara@acme.dev\", avatar: \"/avatars/cara.svg\" },\n  { id: \"dev\", name: \"Dev Raman\", email: \"dev@acme.dev\", avatar: \"/avatars/dev.svg\" },\n  { id: \"fay\", name: \"Fay Nakamura\", email: \"fay@acme.dev\", avatar: \"/avatars/fay.svg\" },\n  { id: \"hugo\", name: \"Hugo Brandt\", email: \"hugo@acme.dev\" },\n  { id: \"isla\", name: \"Isla Carvalho\", email: \"isla@acme.dev\" },\n  { id: \"jonah\", name: \"Jonah Weiss\", email: \"jonah@acme.dev\" },\n];\n\nexport default function ComboboxDemo() {\n  const [assignee, setAssignee] = useState<Person | null>(null);\n  return <Combobox label=\"Assign to\" people={PEOPLE} value={assignee} onChange={setAssignee} />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/combobox"}