{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "command-palette-morph",
  "title": "Command palette morph",
  "description": "A search field morphs into a command palette through a shared layout animation, with fuzzy matching, highlighted letters, grouped results, a sliding selection, arrow keys, Enter, Esc and Ctrl/Cmd+K.",
  "dependencies": [
    "lucide-react",
    "motion"
  ],
  "registryDependencies": [
    "https://goodui.dev/r/goodui-motion.json",
    "https://goodui.dev/r/locale.json"
  ],
  "files": [
    {
      "path": "registry/components/navigation/command-palette-morph.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, motion, useReducedMotion, type Transition } from \"motion/react\"\nimport { CornerDownLeft, Search } from \"lucide-react\"\nimport { cn } from \"@/lib/utils\"\nimport { useLabels } from \"@/lib/goodui-locale\"\nimport { GooduiTokens, spring as springs } from \"@/lib/goodui-motion\"\n\nexport type CommandPaletteItem = {\n  /** Unique key of the item. */\n  id: string\n  /** Text that is shown, fuzzy-matched and highlighted. */\n  label: string\n  /** Group heading the item is listed under. */\n  group?: string\n  /** Icon component (e.g. a lucide icon) shown before the label. */\n  icon?: React.ComponentType<{ className?: string }>\n  /** Secondary text on the right, e.g. \"Client\" or \"Overdue · $240\". */\n  hint?: string\n  /** Keys shown on the right, e.g. [\"G\", \"C\"]. Display only. */\n  shortcut?: string[]\n  /** Extra words that should match, e.g. an email or invoice number. */\n  keywords?: string[]\n  /** Runs when this item is chosen (click or Enter); the palette then closes. */\n  onSelect?: () => void\n  /** Shown in the pane beside the list while this item is active. Giving any item a preview turns the pane on. */\n  preview?: React.ReactNode\n}\n\nexport type CommandPaletteMorphLabels = {\n  dialog: string\n  results: string\n  close: string\n  navigate: string\n  select: string\n  resultCount: (count: number) => string\n  /** Heading of the default empty state. */\n  noResults: string\n  /** Line under it, with the current query. */\n  noMatch: (query: string) => string\n}\nconst DEFAULT_LABELS: CommandPaletteMorphLabels = {\n  dialog: \"Command palette\",\n  results: \"Results\",\n  close: \"Esc\",\n  navigate: \"navigate\",\n  select: \"select\",\n  resultCount: (count) => `${count} ${count === 1 ? \"result\" : \"results\"}`,\n  noResults: \"No results\",\n  noMatch: (query) => `Nothing matches “${query}”.`,\n}\n\nexport type CommandPaletteMorphProps = Omit<React.ComponentProps<\"button\">, \"onSelect\" | \"children\"> & {\n  /** Everything the palette can find; items are listed in this order (grouped by group) until the user types. */\n  items: CommandPaletteItem[]\n  /** Whether the palette is open (controlled). */\n  open?: boolean\n  /** Initial open state when uncontrolled. */\n  defaultOpen?: boolean\n  /** Called when the palette opens or closes (trigger, hotkey, Esc, backdrop or a selection). */\n  onOpenChange?: (open: boolean) => void\n  /** Called with the chosen item, after the item's own onSelect. */\n  onSelect?: (item: CommandPaletteItem) => void\n  /** Placeholder of the search input inside the palette. */\n  placeholder?: string\n  /** Text on the field trigger. */\n  triggerLabel?: string\n  /** `field` looks like a search input; `icon` is a round icon button. */\n  variant?: \"field\" | \"icon\"\n  /** Open and close with Ctrl+K / Cmd+K. Enable it on one palette per page. */\n  hotkey?: boolean\n  /** Shown when nothing matches; defaults to \"No results\" with the query. */\n  emptyMessage?: React.ReactNode\n  /**\n   * Raycast-style pane beside the list, from 640px up. On by default when an item has a `preview`; items without one\n   * show their icon, label and hint.\n   */\n  showPreview?: boolean\n  /** Text for built-in controls and screen readers; pass translations here. */\n  labels?: Partial<CommandPaletteMorphLabels>\n}\n\nfunction useControllable<T>(value: T | undefined, defaultValue: T, onChange?: (v: T) => void) {\n  const [inner, setInner] = React.useState(defaultValue)\n  const controlled = value !== undefined\n  const current = controlled ? value : inner\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next)\n      onChange?.(next)\n    },\n    [controlled, onChange],\n  )\n  return [current, set] as const\n}\n\nconst BOUNDARY = /[\\s\\-_/.·#@]/\n\n/** Subsequence match with bonuses for word starts and consecutive letters. Returns null when it does not match. */\nfunction fuzzy(query: string, text: string): { score: number; indices: number[] } | null {\n  const q = query.trim().toLowerCase()\n  const t = text.toLowerCase()\n  if (!q) return { score: 0, indices: [] }\n  const sub = t.indexOf(q)\n  if (sub >= 0) {\n    const atWord = sub === 0 || BOUNDARY.test(t[sub - 1]!)\n    return { score: 100 + (atWord ? 40 : 0) - sub - t.length * 0.05, indices: Array.from({ length: q.length }, (_, k) => sub + k) }\n  }\n  let from = 0\n  let prev = -2\n  let score = 0\n  const indices: number[] = []\n  for (const ch of q) {\n    if (ch === \" \") continue\n    const at = t.indexOf(ch, from)\n    if (at < 0) return null\n    score += at === prev + 1 ? 6 : at === 0 || BOUNDARY.test(t[at - 1]!) ? 4 : 1\n    score -= Math.min(at - from, 6) * 0.25\n    indices.push(at)\n    prev = at\n    from = at + 1\n  }\n  return { score, indices }\n}\n\nfunction Highlight({ text, indices }: { text: string; indices: number[] }) {\n  if (!indices.length) return <>{text}</>\n  const set = new Set(indices)\n  return (\n    <>\n      {[...text].map((ch, i) =>\n        set.has(i) ? (\n          <span key={i} className=\"font-semibold text-foreground underline decoration-primary/40 underline-offset-[3px]\">\n            {ch}\n          </span>\n        ) : (\n          <span key={i}>{ch}</span>\n        ),\n      )}\n    </>\n  )\n}\n\nfunction DefaultPreview({ item }: { item: CommandPaletteItem }) {\n  const Icon = item.icon\n  return (\n    <div className=\"flex h-full flex-col items-center justify-center gap-2 text-center\">\n      {Icon && (\n        <span className=\"grid size-12 place-items-center rounded-xl bg-muted shadow-[var(--pc-e1)]\">\n          <Icon className=\"size-5 text-muted-foreground\" />\n        </span>\n      )}\n      <div className=\"text-sm font-medium\">{item.label}</div>\n      {item.hint && <div className=\"text-xs text-muted-foreground\">{item.hint}</div>}\n    </div>\n  )\n}\n\n/**\n * A search field (or icon button) that morphs into a command palette through a shared layout animation.\n * Fuzzy filtering with highlighted matches, grouped results, arrow keys + Enter, Esc closes, Ctrl/Cmd+K opens.\n * A click morphs; the keyboard opens it instantly. The list height follows the results, and items can carry a preview.\n * Uses `position: fixed` without a portal, so keep it out of transformed ancestors.\n */\nexport function CommandPaletteMorph({\n  items,\n  open: openProp,\n  defaultOpen = false,\n  onOpenChange,\n  onSelect,\n  placeholder = \"Search or type a command…\",\n  triggerLabel = \"Search…\",\n  variant = \"field\",\n  hotkey = true,\n  emptyMessage,\n  showPreview,\n  labels,\n  className,\n  ...props\n}: CommandPaletteMorphProps) {\n  const l = useLabels(\"command-palette-morph\", DEFAULT_LABELS, labels)\n  const uid = React.useId()\n  const reduce = useReducedMotion() ?? false\n  const [open, setOpen] = useControllable(openProp, defaultOpen, onOpenChange)\n  const [query, setQuery] = React.useState(\"\")\n  const [active, setActive] = React.useState(0)\n  const [mod, setMod] = React.useState(\"⌘\")\n  const triggerRef = React.useRef<HTMLButtonElement>(null)\n  const inputRef = React.useRef<HTMLInputElement>(null)\n  const listRef = React.useRef<HTMLDivElement>(null)\n  const keyboardNav = React.useRef(false)\n  const contentRef = React.useRef<HTMLDivElement>(null)\n  const [listHeight, setListHeight] = React.useState<number | null>(null)\n  // Opened from the keyboard: no animation at all, a frequent action stays quiet. A click gets the morph.\n  const [instant, setInstant] = React.useState(false)\n  const quiet = reduce || instant\n  const preview = showPreview ?? items.some((i) => i.preview != null)\n\n  const spring: Transition = quiet ? { duration: 0 } : springs.morph\n  const radius = variant === \"icon\" ? 18 : 8\n\n  // Grouped, scored results.\n  const groups = React.useMemo(() => {\n    const scored = items\n      .map((item, order) => {\n        const m = fuzzy(query, item.label)\n        if (m) return { item, order, ...m }\n        const k = (item.keywords ?? []).map((w) => fuzzy(query, w)).find(Boolean)\n        return k ? { item, order, score: k.score - 10, indices: [] as number[] } : null\n      })\n      .filter((x): x is NonNullable<typeof x> => x !== null)\n    if (query.trim()) scored.sort((a, b) => b.score - a.score || a.order - b.order)\n    const map = new Map<string, typeof scored>()\n    for (const s of scored) {\n      const g = s.item.group ?? \"\"\n      if (!map.has(g)) map.set(g, [])\n      map.get(g)!.push(s)\n    }\n    return [...map.entries()].map(([name, list]) => ({ name, list }))\n  }, [items, query])\n  const flat = React.useMemo(() => groups.flatMap((g) => g.list), [groups])\n  const count = flat.length\n\n  const close = React.useCallback(() => setOpen(false), [setOpen])\n\n  // Hotkey, platform label.\n  React.useEffect(() => {\n    if (!/Mac|iPhone|iPad/.test(navigator.platform || navigator.userAgent)) setMod(\"Ctrl\")\n    if (!hotkey) return\n    const onKey = (e: KeyboardEvent) => {\n      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"k\") {\n        e.preventDefault()\n        setInstant(true)\n        setOpen(!open)\n      }\n    }\n    window.addEventListener(\"keydown\", onKey)\n    return () => window.removeEventListener(\"keydown\", onKey)\n  }, [hotkey, open, setOpen])\n\n  // Reset on open, lock page scroll, return focus on close.\n  const wasOpen = React.useRef(open)\n  React.useEffect(() => {\n    if (open) {\n      setQuery(\"\")\n      setActive(0)\n      const prev = document.body.style.overflow\n      document.body.style.overflow = \"hidden\"\n      const t = window.setTimeout(() => inputRef.current?.focus(), 0)\n      wasOpen.current = true\n      return () => {\n        window.clearTimeout(t)\n        document.body.style.overflow = prev\n      }\n    }\n    if (wasOpen.current) {\n      wasOpen.current = false\n      triggerRef.current?.focus()\n    }\n  }, [open])\n\n  // The list is as tall as its results, up to the cap, and the whole palette follows.\n  React.useLayoutEffect(() => {\n    const el = contentRef.current\n    if (!open || !el) {\n      setListHeight(null)\n      return\n    }\n    const measure = () => setListHeight(Math.min(el.offsetHeight + 16, 320))\n    measure()\n    const ro = new ResizeObserver(measure)\n    ro.observe(el)\n    return () => ro.disconnect()\n  }, [open])\n\n  // Keep the active option in view when moving with the keyboard.\n  React.useEffect(() => {\n    if (!open || !keyboardNav.current) return\n    listRef.current?.querySelector<HTMLElement>(`[data-index=\"${active}\"]`)?.scrollIntoView({ block: \"nearest\" })\n  }, [active, open])\n\n  const choose = (item: CommandPaletteItem | undefined) => {\n    if (!item) return\n    item.onSelect?.()\n    onSelect?.(item)\n    close()\n  }\n\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    if (e.key === \"Escape\") {\n      e.preventDefault()\n      e.stopPropagation()\n      close()\n    } else if (e.key === \"Tab\") {\n      // Focus trap: the input is the only tab stop inside the dialog.\n      e.preventDefault()\n      inputRef.current?.focus()\n    } else if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n      e.preventDefault()\n      if (!count) return\n      keyboardNav.current = true\n      setActive((a) => (e.key === \"ArrowDown\" ? (a + 1) % count : (a - 1 + count) % count))\n    } else if (e.key === \"Enter\") {\n      e.preventDefault()\n      choose(flat[active]?.item)\n    }\n  }\n\n  const optionId = (i: number) => `${uid}-opt-${i}`\n  let index = -1\n\n  return (\n    <>\n      <GooduiTokens />\n      <button\n        ref={triggerRef}\n        type=\"button\"\n        aria-haspopup=\"dialog\"\n        aria-expanded={open}\n        aria-label={variant === \"icon\" ? triggerLabel : undefined}\n        onClick={(e) => {\n          setInstant(e.detail === 0)\n          setOpen(true)\n        }}\n        className={cn(\n          \"pc-press pc-press-soft group relative inline-flex shrink-0 cursor-pointer items-center text-sm text-muted-foreground outline-none focus-visible:ring-3 focus-visible:ring-ring/50\",\n          variant === \"field\" ? \"h-9 w-full max-w-72 gap-2 rounded-lg px-3\" : \"size-9 justify-center rounded-full\",\n          className,\n        )}\n        {...props}\n      >\n        {!open && (\n          <motion.span\n            layoutId={`${uid}-shell`}\n            aria-hidden=\"true\"\n            className=\"absolute inset-0 bg-background shadow-[var(--pc-e1)] transition-colors group-hover:bg-muted/60 dark:bg-input/30 dark:group-hover:bg-input/50\"\n            style={{ borderRadius: radius }}\n            transition={spring}\n          />\n        )}\n        {!open ? (\n          <motion.span layoutId={`${uid}-icon`} className=\"relative flex\" transition={spring}>\n            <Search className=\"size-4\" />\n          </motion.span>\n        ) : (\n          <span className=\"size-4\" />\n        )}\n        {variant === \"field\" && (\n          <>\n            <span className={cn(\"relative flex-1 truncate text-start transition-opacity\", open && \"opacity-0\")}>{triggerLabel}</span>\n            {hotkey && (\n              <kbd\n                className={cn(\n                  \"relative hidden h-5 items-center rounded-[5px] bg-background px-1.5 font-sans text-[10px] font-medium text-foreground/70 shadow-[0_0_0_1px_var(--pc-hair),0_1px_0_1px_var(--pc-hair)] transition-opacity sm:inline-flex\",\n                  open && \"opacity-0\",\n                )}\n              >\n                {mod === \"⌘\" ? \"⌘K\" : \"Ctrl K\"}\n              </kbd>\n            )}\n          </>\n        )}\n      </button>\n\n      <AnimatePresence>\n        {open && (\n          <div key=\"palette\" className=\"fixed inset-0 z-50 flex items-start justify-center p-3 pt-[10vh] sm:p-6 sm:pt-[12vh]\">\n            <motion.div\n              aria-hidden=\"true\"\n              className=\"absolute inset-0 bg-black/30 dark:bg-black/55\"\n              initial={{ opacity: 0 }}\n              animate={{ opacity: 1 }}\n              exit={{ opacity: 0 }}\n              transition={{ duration: quiet ? 0 : 0.2 }}\n              onClick={close}\n            />\n            <div\n              role=\"dialog\"\n              aria-modal=\"true\"\n              aria-label={l.dialog}\n              className={cn(\"relative w-full max-w-xl text-popover-foreground\", preview && \"sm:max-w-3xl\")}\n              onKeyDown={onKeyDown}\n            >\n              <motion.div\n                layoutId={`${uid}-shell`}\n                aria-hidden=\"true\"\n                className=\"absolute inset-0 bg-popover shadow-[var(--pc-e3)]\"\n                style={{ borderRadius: 14 }}\n                transition={spring}\n              />\n              <div className=\"relative flex h-14 items-center gap-3 border-b border-[var(--pc-hair)] px-4\">\n                <motion.span layoutId={`${uid}-icon`} className=\"flex text-muted-foreground\" transition={spring}>\n                  <Search className=\"size-4\" />\n                </motion.span>\n                <motion.div\n                  className=\"flex flex-1 items-center gap-2\"\n                  initial={{ opacity: 0 }}\n                  animate={{ opacity: 1, transition: { delay: quiet ? 0 : 0.08, duration: quiet ? 0 : 0.15 } }}\n                  exit={{ opacity: 0, transition: { duration: quiet ? 0 : 0.08 } }}\n                >\n                  <input\n                    ref={inputRef}\n                    role=\"combobox\"\n                    aria-expanded=\"true\"\n                    aria-controls={`${uid}-list`}\n                    aria-autocomplete=\"list\"\n                    aria-activedescendant={count ? optionId(active) : undefined}\n                    value={query}\n                    onChange={(e) => {\n                      setQuery(e.target.value)\n                      setActive(0)\n                    }}\n                    placeholder={placeholder}\n                    className=\"h-10 min-w-0 flex-1 bg-transparent text-[15px] outline-none placeholder:text-muted-foreground\"\n                    spellCheck={false}\n                    autoComplete=\"off\"\n                  />\n                  <button\n                    type=\"button\"\n                    onClick={close}\n                    tabIndex={-1}\n                    className=\"pc-press h-5 cursor-pointer rounded-[5px] bg-background px-1.5 text-[10px] font-medium text-foreground/70 shadow-[0_0_0_1px_var(--pc-hair),0_1px_0_1px_var(--pc-hair)] hover:text-foreground\"\n                  >\n                    {l.close}\n                  </button>\n                </motion.div>\n              </div>\n\n              <motion.div\n                className=\"relative\"\n                initial={{ opacity: 0, y: quiet ? 0 : -4 }}\n                animate={{ opacity: 1, y: 0, transition: { delay: quiet ? 0 : 0.1, duration: quiet ? 0 : 0.18 } }}\n                exit={{ opacity: 0, transition: { duration: quiet ? 0 : 0.08 } }}\n              >\n                <div className=\"flex\">\n                <motion.div\n                  ref={listRef}\n                  id={`${uid}-list`}\n                  role=\"listbox\"\n                  aria-label={l.results}\n                  layoutScroll\n                  className={cn(\"max-h-[46vh] min-w-0 flex-1 overflow-y-auto overscroll-contain\", preview && \"sm:min-h-[280px]\")}\n                  initial={false}\n                  animate={{ height: listHeight ?? 320 }}\n                  transition={reduce ? { duration: 0 } : springs.ui}\n                  onPointerMove={() => {\n                    keyboardNav.current = false\n                  }}\n                >\n                  <div ref={contentRef} className=\"p-2\">\n                  {count === 0 ? (\n                    <div className=\"flex min-h-28 flex-col items-center justify-center gap-1 text-center text-sm text-muted-foreground\">\n                      {emptyMessage ?? (\n                        <>\n                          <span className=\"font-medium text-foreground\">{l.noResults}</span>\n                          <span>{l.noMatch(query)}</span>\n                        </>\n                      )}\n                    </div>\n                  ) : (\n                    groups.map((g, gi) => (\n                      // Heading ids use the group's position: names can contain spaces, which break aria-labelledby.\n                      <div key={g.name || \"_\"} role=\"group\" aria-labelledby={g.name ? `${uid}-g-${gi}` : undefined} className=\"mb-1 last:mb-0\">\n                        {g.name && (\n                          <div id={`${uid}-g-${gi}`} className=\"px-2.5 pt-2 pb-1 text-[11px] font-medium text-muted-foreground\">\n                            {g.name}\n                          </div>\n                        )}\n                        {g.list.map(({ item, indices }) => {\n                          index += 1\n                          const i = index\n                          const selected = i === active\n                          const Icon = item.icon\n                          return (\n                            <div\n                              key={item.id}\n                              id={optionId(i)}\n                              data-index={i}\n                              role=\"option\"\n                              aria-selected={selected}\n                              onPointerMove={() => !selected && setActive(i)}\n                              onClick={() => choose(item)}\n                              className={cn(\n                                \"relative flex h-10 cursor-pointer items-center gap-3 rounded-[8px] px-2.5 text-sm select-none\",\n                                selected ? \"text-foreground\" : \"text-foreground/80\",\n                              )}\n                            >\n                              {selected && (\n                                <motion.span\n                                  layoutId={`${uid}-active`}\n                                  aria-hidden=\"true\"\n                                  className=\"absolute inset-0 rounded-[8px] bg-foreground/[.06] shadow-[inset_0_0_0_1px_var(--pc-hair)]\"\n                                  transition={reduce ? { duration: 0 } : springs.snap}\n                                />\n                              )}\n                              {Icon && <Icon className=\"relative size-4 shrink-0 text-muted-foreground\" />}\n                              <span className=\"relative flex-1 truncate\">\n                                <Highlight text={item.label} indices={indices} />\n                              </span>\n                              {item.hint && <span className=\"relative hidden truncate text-xs text-foreground/65 sm:block\">{item.hint}</span>}\n                              {item.shortcut && (\n                                <span className=\"relative hidden gap-1 sm:flex\">\n                                  {item.shortcut.map((k) => (\n                                    <kbd key={k} className=\"flex h-5 min-w-5 items-center justify-center rounded-[5px] bg-background px-1 font-sans text-[10px] font-medium text-muted-foreground shadow-[0_0_0_1px_var(--pc-hair),0_1px_0_1px_var(--pc-hair)]\">\n                                      {k}\n                                    </kbd>\n                                  ))}\n                                </span>\n                              )}\n                              {selected && <CornerDownLeft className=\"relative size-3.5 shrink-0 text-muted-foreground\" />}\n                            </div>\n                          )\n                        })}\n                      </div>\n                    ))\n                  )}\n                  </div>\n                </motion.div>\n                {preview && (\n                  <div className=\"relative hidden w-[42%] shrink-0 overflow-hidden border-s border-[var(--pc-hair)] sm:block\">\n                    {flat[active] && (\n                      <motion.div\n                        key={flat[active].item.id}\n                        className=\"absolute inset-0 overflow-y-auto p-4\"\n                        initial={reduce ? false : { opacity: 0, filter: \"blur(4px)\" }}\n                        animate={{ opacity: 1, filter: \"blur(0px)\" }}\n                        transition={{ duration: 0.15 }}\n                      >\n                        {flat[active].item.preview ?? <DefaultPreview item={flat[active].item} />}\n                      </motion.div>\n                    )}\n                  </div>\n                )}\n                </div>\n                <div className=\"flex items-center gap-4 border-t border-[var(--pc-hair)] px-4 py-2.5 text-[11px] text-muted-foreground\">\n                  <span className=\"flex items-center gap-1\">\n                    <kbd className=\"rounded-[4px] bg-background px-1 font-sans text-foreground/70 shadow-[0_0_0_1px_var(--pc-hair),0_1px_0_1px_var(--pc-hair)]\">↑</kbd>\n                    <kbd className=\"rounded-[4px] bg-background px-1 font-sans text-foreground/70 shadow-[0_0_0_1px_var(--pc-hair),0_1px_0_1px_var(--pc-hair)]\">↓</kbd> {l.navigate}\n                  </span>\n                  <span className=\"flex items-center gap-1\">\n                    <kbd className=\"rounded-[4px] bg-background px-1 font-sans text-foreground/70 shadow-[0_0_0_1px_var(--pc-hair),0_1px_0_1px_var(--pc-hair)]\">↵</kbd> {l.select}\n                  </span>\n                  <span className=\"ms-auto\" aria-live=\"polite\">\n                    {l.resultCount(count)}\n                  </span>\n                </div>\n              </motion.div>\n            </div>\n          </div>\n        )}\n      </AnimatePresence>\n    </>\n  )\n}\n",
      "type": "registry:component",
      "target": "components/goodui/command-palette-morph.tsx"
    }
  ],
  "categories": [
    "components",
    "navigation"
  ],
  "type": "registry:component"
}