{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"search-cell","type":"registry:ui","title":"Search Cell","description":"A command-style search field that widens on focus and unfolds grouped, ranked results with highlighted matches, a sliding selection and full keyboard navigation.","dependencies":["motion","lucide-react"],"registryDependencies":["utils"],"files":[{"path":"registry/ui/search-cell.tsx","type":"registry:ui","content":"\"use client\";\n\nimport { Fragment, useId, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { CornerDownLeft, Search, SearchX } from \"lucide-react\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface SearchItem {\n  id: string;\n  label: string;\n  description?: string;\n  /** Section heading the item is listed under. */\n  group?: string;\n  icon?: ReactNode;\n  /** Extra words that match but are not shown. */\n  keywords?: string[];\n  /** Shortcut hint shown on the right, e.g. [\"⌘\", \"N\"]. */\n  shortcut?: string[];\n}\n\nexport interface SearchCellProps {\n  items: SearchItem[];\n  placeholder?: string;\n  /** Fired with the chosen item (click or Enter). */\n  onSelect?: (item: SearchItem) => void;\n  /** Max rows shown at once. */\n  maxResults?: number;\n  /** Grow wider while open. */\n  expand?: boolean;\n  /** Start open (without stealing focus). */\n  defaultOpen?: boolean;\n  emptyMessage?: string;\n  className?: string;\n}\n\nconst escapeRe = (s: string) => s.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/** Wraps every query token found in `text` in a <mark>. */\nfunction Highlight({ text, tokens }: { text: string; tokens: string[] }) {\n  if (!tokens.length) return <>{text}</>;\n  const re = new RegExp(`(${tokens.map(escapeRe).join(\"|\")})`, \"gi\");\n  return (\n    <>\n      {text.split(re).map((part, i) =>\n        i % 2 ? (\n          <mark key={i} className=\"rounded-[3px] bg-primary/25 px-px text-foreground\">\n            {part}\n          </mark>\n        ) : (\n          <Fragment key={i}>{part}</Fragment>\n        ),\n      )}\n    </>\n  );\n}\n\nexport function SearchCell({\n  items,\n  placeholder = \"Search or jump to…\",\n  onSelect,\n  maxResults = 7,\n  expand = true,\n  defaultOpen = false,\n  emptyMessage = \"No results for\",\n  className,\n}: SearchCellProps) {\n  const id = useId();\n  const reduce = useReducedMotion();\n  const inputRef = useRef<HTMLInputElement>(null);\n  const listRef = useRef<HTMLDivElement>(null);\n  const [open, setOpen] = useState(defaultOpen);\n  const [query, setQuery] = useState(\"\");\n  const [active, setActive] = useState(0);\n\n  const tokens = useMemo(() => query.trim().toLowerCase().split(/\\s+/).filter(Boolean), [query]);\n  const results = useMemo(() => {\n    const hits = items.filter((it) => {\n      const hay = [it.label, it.description, ...(it.keywords ?? [])].join(\" \").toLowerCase();\n      return tokens.every((t) => hay.includes(t));\n    });\n    // Label prefix matches first, then label contains, then everything else; stable within a rank.\n    const rank = (it: SearchItem) => {\n      const l = it.label.toLowerCase();\n      return !tokens.length ? 0 : l.startsWith(tokens[0]) ? 0 : tokens.every((t) => l.includes(t)) ? 1 : 2;\n    };\n    return hits\n      .map((it, i) => ({ it, r: rank(it), i }))\n      .sort((a, b) => a.r - b.r || a.i - b.i)\n      .slice(0, maxResults)\n      .map((x) => x.it);\n  }, [items, tokens, maxResults]);\n\n  // Group while keeping ranked order of first appearance.\n  const groups = useMemo(() => {\n    const map = new Map<string, SearchItem[]>();\n    for (const it of results) {\n      const g = it.group ?? \"\";\n      if (!map.has(g)) map.set(g, []);\n      map.get(g)!.push(it);\n    }\n    return [...map];\n  }, [results]);\n  const flat = groups.flatMap(([, list]) => list);\n  const current = Math.min(active, Math.max(0, flat.length - 1));\n\n  const move = (d: number) => {\n    if (!flat.length) return;\n    const next = (current + d + flat.length) % flat.length;\n    setActive(next);\n    listRef.current?.querySelector(`[data-index=\"${next}\"]`)?.scrollIntoView({ block: \"nearest\" });\n  };\n\n  const choose = (it: SearchItem) => {\n    onSelect?.(it);\n    setQuery(\"\");\n    setActive(0);\n    setOpen(false);\n    (document.activeElement as HTMLElement | null)?.blur();\n  };\n\n  const optionId = (i: number) => `${id}-o${i}`;\n\n  return (\n    <div\n      className={cn(\n        \"relative max-w-full transition-[width] duration-500 ease-[cubic-bezier(.2,.9,.25,1)] motion-reduce:transition-none\",\n        open && expand ? \"w-[30rem]\" : \"w-72\",\n        className,\n      )}\n      onBlur={(e) => {\n        if (!e.currentTarget.contains(e.relatedTarget as Node)) setOpen(false);\n      }}\n    >\n      <div\n        className={cn(\n          \"overflow-hidden rounded-2xl border bg-popover text-popover-foreground transition-[box-shadow,border-color] duration-300\",\n          open ? \"border-border shadow-2xl shadow-black/40\" : \"border-border/80 shadow-md shadow-black/10 hover:border-foreground/20\",\n        )}\n      >\n        <div className=\"relative flex h-12 items-center gap-3 px-4\">\n          <motion.span\n            aria-hidden\n            animate={{ rotate: open && !reduce ? -12 : 0, scale: open ? 1.08 : 1 }}\n            className={cn(\"shrink-0 transition-colors\", open ? \"text-foreground\" : \"text-muted-foreground\")}\n          >\n            <Search className=\"size-4.5\" />\n          </motion.span>\n          <input\n            ref={inputRef}\n            role=\"combobox\"\n            aria-expanded={open}\n            aria-controls={`${id}-list`}\n            aria-autocomplete=\"list\"\n            aria-activedescendant={open && flat.length ? optionId(current) : undefined}\n            aria-label={placeholder}\n            placeholder={placeholder}\n            value={query}\n            onFocus={() => setOpen(true)}\n            onClick={() => setOpen(true)}\n            onChange={(e) => {\n              setQuery(e.target.value);\n              setActive(0);\n              setOpen(true);\n            }}\n            onKeyDown={(e) => {\n              if (e.key === \"ArrowDown\") {\n                e.preventDefault();\n                if (!open) setOpen(true);\n                else move(1);\n              } else if (e.key === \"ArrowUp\") {\n                e.preventDefault();\n                move(-1);\n              } else if (e.key === \"Home\" && open) {\n                e.preventDefault();\n                setActive(0);\n              } else if (e.key === \"End\" && open) {\n                e.preventDefault();\n                setActive(flat.length - 1);\n              } else if (e.key === \"Enter\" && open && flat[current]) {\n                e.preventDefault();\n                choose(flat[current]);\n              } else if (e.key === \"Escape\") {\n                if (query) setQuery(\"\");\n                else {\n                  setOpen(false);\n                  inputRef.current?.blur();\n                }\n              }\n            }}\n            className=\"h-full min-w-0 flex-1 bg-transparent text-sm text-foreground outline-none placeholder:text-muted-foreground\"\n          />\n          {open && (\n            <kbd className=\"hidden rounded-md border border-border bg-muted px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground sm:inline\">\n              Esc\n            </kbd>\n          )}\n        </div>\n\n        <AnimatePresence initial={false}>\n          {open && (\n            <motion.div\n              key=\"panel\"\n              initial={{ height: 0, opacity: 0 }}\n              animate={{ height: \"auto\", opacity: 1 }}\n              exit={{ height: 0, opacity: 0 }}\n              transition={{ duration: reduce ? 0 : 0.28, ease: [0.2, 0.9, 0.25, 1] }}\n              className=\"border-t border-border\"\n            >\n              <div ref={listRef} id={`${id}-list`} role=\"listbox\" aria-label=\"Results\" className=\"max-h-80 overflow-y-auto p-1.5 [scrollbar-width:thin]\">\n                {flat.length === 0 ? (\n                  <div className=\"grid place-items-center gap-2 px-4 py-10 text-center text-sm text-muted-foreground\" role=\"presentation\">\n                    <SearchX className=\"size-6 opacity-60\" aria-hidden />\n                    <p>\n                      {emptyMessage} <span className=\"font-medium text-foreground\">&ldquo;{query.trim()}&rdquo;</span>\n                    </p>\n                  </div>\n                ) : (\n                  groups.map(([group, list]) => (\n                    <div key={group || \"_\"} role=\"group\" aria-label={group || undefined}>\n                      {group && (\n                        <div className=\"px-2.5 pt-2 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase\" aria-hidden>\n                          {group}\n                        </div>\n                      )}\n                      {list.map((it) => {\n                        const i = flat.indexOf(it);\n                        const on = i === current;\n                        return (\n                          <motion.div\n                            key={it.id}\n                            id={optionId(i)}\n                            data-index={i}\n                            role=\"option\"\n                            aria-selected={on}\n                            initial={reduce ? false : { opacity: 0, y: 6 }}\n                            animate={{ opacity: 1, y: 0 }}\n                            transition={{ delay: reduce ? 0 : Math.min(i, 8) * 0.025 }}\n                            onMouseDown={(e) => e.preventDefault()}\n                            onMouseMove={() => active !== i && setActive(i)}\n                            onClick={() => choose(it)}\n                            className=\"relative flex cursor-pointer items-center gap-3 rounded-xl px-2.5 py-2\"\n                          >\n                            {on && (\n                              <motion.span\n                                layoutId={`${id}-hl`}\n                                aria-hidden\n                                className=\"absolute inset-0 rounded-xl bg-muted\"\n                                transition={{ type: \"spring\", stiffness: 600, damping: 45 }}\n                              />\n                            )}\n                            {it.icon && (\n                              <span\n                                aria-hidden\n                                className={cn(\n                                  \"relative grid size-8 shrink-0 place-items-center rounded-[9px] border border-border bg-background transition-colors [&_svg]:size-4\",\n                                  on ? \"text-foreground\" : \"text-muted-foreground\",\n                                )}\n                              >\n                                {it.icon}\n                              </span>\n                            )}\n                            <span className=\"relative min-w-0 flex-1\">\n                              <span className=\"block truncate text-sm font-medium text-foreground\">\n                                <Highlight text={it.label} tokens={tokens} />\n                              </span>\n                              {it.description && (\n                                <span className=\"block truncate text-xs text-muted-foreground\">\n                                  <Highlight text={it.description} tokens={tokens} />\n                                </span>\n                              )}\n                            </span>\n                            {on ? (\n                              <CornerDownLeft className=\"relative size-3.5 shrink-0 text-muted-foreground\" aria-hidden />\n                            ) : (\n                              it.shortcut && (\n                                <span className=\"relative flex shrink-0 gap-1\" aria-hidden>\n                                  {it.shortcut.map((k) => (\n                                    <kbd key={k} className=\"min-w-5 rounded-[5px] border border-border bg-background px-1 text-center font-mono text-[10px] leading-5 text-muted-foreground\">\n                                      {k}\n                                    </kbd>\n                                  ))}\n                                </span>\n                              )\n                            )}\n                          </motion.div>\n                        );\n                      })}\n                    </div>\n                  ))\n                )}\n              </div>\n              <div className=\"flex items-center justify-between border-t border-border px-3.5 py-2 text-[11px] text-muted-foreground\" aria-hidden>\n                <span className=\"flex items-center gap-3\">\n                  <span className=\"flex items-center gap-1\">\n                    <kbd className=\"rounded border border-border bg-muted px-1 font-mono\">↑</kbd>\n                    <kbd className=\"rounded border border-border bg-muted px-1 font-mono\">↓</kbd>\n                    navigate\n                  </span>\n                  <span className=\"flex items-center gap-1\">\n                    <kbd className=\"rounded border border-border bg-muted px-1 font-mono\">↵</kbd>\n                    open\n                  </span>\n                </span>\n                <span className=\"tabular-nums\">\n                  {flat.length} result{flat.length === 1 ? \"\" : \"s\"}\n                </span>\n              </div>\n            </motion.div>\n          )}\n        </AnimatePresence>\n      </div>\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {open ? `${flat.length} result${flat.length === 1 ? \"\" : \"s\"}` : \"\"}\n      </span>\n    </div>\n  );\n}\n"}]}