{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"command-palette","type":"registry:block","title":"Command palette","description":"A complete keyboard driven action surface with search, grouped results, and shortcuts.","categories":["blocks"],"dependencies":["lucide-react","motion"],"registryDependencies":["https://ui.teamofsilicons.com/r/silicon-motion-tokens.json"],"files":[{"path":"registry/components/command-palette/command-palette.tsx","type":"registry:component","target":"@components/silicon-ui/command-palette/command-palette.tsx","content":"\"use client\";\n\nimport { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent, ReactNode } from \"react\";\nimport { AnimatePresence, animate, motion, useMotionValue, useReducedMotion } from \"motion/react\";\nimport type { Transition, ValueAnimationTransition, Variants } from \"motion/react\";\nimport { Command as CommandIcon, Search, X } from \"lucide-react\";\nimport { motionTokens } from \"../lib/motion-tokens\";\nimport { useNearestItem } from \"../lib/fluid-hover\";\nimport styles from \"./command-palette.module.css\";\n\nexport interface CommandItem { id: string; label: string; description?: string; group?: string; keywords?: string[]; icon?: ReactNode; shortcut?: string; }\nexport interface CommandPaletteProps { items: CommandItem[]; placeholder?: string; onSelect?: (item: CommandItem) => void; onClose?: () => void; label?: string; /** Focus the search field on mount, for a palette that opens on demand. */ autoFocus?: boolean; }\n\nconst enter: Transition = { duration: motionTokens.duration.standard, ease: [...motionTokens.ease.enter] };\nconst leave: Transition = { duration: motionTokens.duration.instant, ease: [...motionTokens.ease.standard] };\nconst GLIDE_ROWS = 6;\n/** Rows fade out while the rest glide into their place; when the list snaps they leave at once so nothing overlaps the new rows. */\nconst rowExit: Variants = { exit: (glide: boolean) => ({ opacity: 0, transition: glide ? leave : { duration: 0 } }) };\n\nexport function CommandPalette({ items, placeholder = \"Search commands\", onSelect, onClose, label = \"Command palette\", autoFocus = false }: CommandPaletteProps) {\n  const inputId = useId();\n  const [query, setQuery] = useState(\"\");\n  const [activeIndex, setActiveIndex] = useState<number | null>(null);\n  const [listHeight, setListHeight] = useState<number | \"auto\">(\"auto\");\n  const reduced = useReducedMotion();\n  const inputRef = useRef<HTMLInputElement>(null);\n  const listRef = useRef<HTMLDivElement>(null);\n  const pointer = useRef(false);\n  const lastPointer = useRef({ x: -1, y: -1 });\n  const highlightShown = useRef(false);\n  const highlightY = useMotionValue(0);\n  const highlightHeight = useMotionValue(0);\n  const highlightOpacity = useMotionValue(0);\n  const filtered = useMemo(() => {\n    const normalized = query.trim().toLowerCase();\n    if (!normalized) return items;\n    return items.filter(item => [item.label, item.description, item.group, ...(item.keywords ?? [])].filter(Boolean).join(\" \").toLowerCase().includes(normalized));\n  }, [items, query]);\n  const groupedItems = useMemo(() => {\n    const grouped = new Map<string, Array<{ item: CommandItem; index: number }>>();\n    filtered.forEach((item, index) => {\n      const group = item.group ?? \"Actions\";\n      const entries = grouped.get(group) ?? [];\n      entries.push({ item, index });\n      grouped.set(group, entries);\n    });\n    return [...grouped.entries()];\n  }, [filtered]);\n  // When every remaining row moves within about a viewport, the list closes its gaps with a glide. A long jump (the first letters typed into a long list) snaps like a search result list instead of streaking rows through the frame; only the frame height morphs.\n  const [shift, setShift] = useState({ list: filtered, glide: true });\n  if (shift.list !== filtered) {\n    const before = new Map(shift.list.map((item, index) => [item.id, index]));\n    setShift({ list: filtered, glide: filtered.every((item, index) => Math.abs((before.get(item.id) ?? index) - index) <= GLIDE_ROWS) });\n  }\n  const glide = shift.glide && !reduced;\n  const safeActiveIndex = activeIndex === null\n    ? -1\n    : Math.min(activeIndex, Math.max(filtered.length - 1, 0));\n  const activeId = filtered[safeActiveIndex]?.id;\n\n  useEffect(() => {\n    if (autoFocus) inputRef.current?.focus({ preventScroll: true });\n  }, [autoFocus]);\n\n  useEffect(() => {\n    const focusShortcut = (event: KeyboardEvent) => {\n      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === \"k\") {\n        event.preventDefault();\n        inputRef.current?.focus();\n      }\n    };\n    document.addEventListener(\"keydown\", focusShortcut);\n    return () => document.removeEventListener(\"keydown\", focusShortcut);\n  }, []);\n\n  // The results frame follows the list height, so filtering closes or opens the gap instead of snapping.\n  useLayoutEffect(() => {\n    const list = listRef.current;\n    if (!list) return;\n    const observer = new ResizeObserver(([entry]) => setListHeight(Math.round(entry?.borderBoxSize?.[0]?.blockSize ?? list.offsetHeight)));\n    observer.observe(list);\n    return () => observer.disconnect();\n  }, []);\n\n  // Fluid hover: the mouse makes the nearest result active, group headings and padding included, and a click there runs it.\n  const nearest = useNearestItem<HTMLDivElement>({ items: '[role=\"option\"]', onPick: item => {\n    const index = Number(item.dataset.index);\n    if (index !== safeActiveIndex) { pointer.current = true; setActiveIndex(index); }\n  } });\n  function onListPointerMove(event: ReactPointerEvent<HTMLDivElement>) {\n    // Ignore the synthetic moves browsers send while the list scrolls under a still pointer.\n    if (event.clientX === lastPointer.current.x && event.clientY === lastPointer.current.y) return;\n    lastPointer.current = { x: event.clientX, y: event.clientY };\n    nearest.onPointerMove(event);\n  }\n\n  // One highlight follows the active result: a spring for the pointer, a 70ms slide for arrow keys, a fade when it first appears.\n  useLayoutEffect(() => {\n    const node = activeId ? document.getElementById(`${inputId}-${activeId}`) : null;\n    if (!node) {\n      highlightShown.current = false;\n      animate(highlightOpacity, 0, { duration: reduced ? 0 : .1 });\n      return;\n    }\n    const move: ValueAnimationTransition<number> = !highlightShown.current || reduced ? { duration: 0 } : pointer.current ? motionTokens.spring.snappy : { duration: motionTokens.duration.instant, ease: [...motionTokens.ease.enter] };\n    // Rows sit inside positioned groups, so their offset is summed up to the list (layout transforms stay out of it).\n    let top = 0;\n    for (let element: HTMLElement | null = node; element && element !== listRef.current; element = element.offsetParent as HTMLElement | null) top += element.offsetTop + (element === node ? 0 : element.clientTop);\n    animate(highlightY, top, move);\n    animate(highlightHeight, node.offsetHeight, move);\n    animate(highlightOpacity, 1, { duration: reduced ? 0 : .08 });\n    highlightShown.current = true;\n  }, [activeId, inputId, reduced, highlightY, highlightHeight, highlightOpacity]);\n\n  useEffect(() => {\n    if (!activeId) return;\n    document.getElementById(`${inputId}-${activeId}`)?.scrollIntoView({ block: \"nearest\" });\n  }, [activeId, inputId]);\n\n  function choose(item: CommandItem) {\n    onSelect?.(item);\n    setQuery(\"\");\n    setActiveIndex(null);\n    inputRef.current?.focus();\n  }\n  function handleKeyDown(event: ReactKeyboardEvent<HTMLInputElement>) {\n    pointer.current = false;\n    if (event.key === \"ArrowDown\") { event.preventDefault(); setActiveIndex(index => Math.min((index ?? -1) + 1, Math.max(filtered.length - 1, 0))); }\n    if (event.key === \"ArrowUp\") { event.preventDefault(); setActiveIndex(index => Math.max((index ?? filtered.length) - 1, 0)); }\n    if (event.key === \"Home\") { event.preventDefault(); setActiveIndex(0); }\n    if (event.key === \"End\") { event.preventDefault(); setActiveIndex(Math.max(filtered.length - 1, 0)); }\n    // Enter runs the highlighted result; after typing, with nothing highlighted yet, it runs the top match.\n    const target = filtered[safeActiveIndex] ?? (query ? filtered[0] : undefined);\n    if (event.key === \"Enter\" && target) { event.preventDefault(); choose(target); }\n    if (event.key === \"Escape\") {\n      event.preventDefault();\n      if (query) { setQuery(\"\"); setActiveIndex(null); }\n      else onClose?.();\n    }\n  }\n\n  return <motion.div className={styles.palette} initial={reduced ? false : { opacity: 0, y: 6, scale: .98 }} animate={{ opacity: 1, y: 0, scale: 1 }} transition={reduced ? { duration: 0 } : { default: motionTokens.spring.smooth, opacity: { duration: motionTokens.duration.fast, ease: [...motionTokens.ease.enter] } }}>\n    <div className={styles.searchRow}>\n      <span className={styles.searchIcon}><Search width={18} height={18} strokeWidth={1.75} aria-hidden=\"true\"/></span>\n      <label className={styles.visuallyHidden} htmlFor={inputId}>{label}</label>\n      <input ref={inputRef} id={inputId} role=\"combobox\" aria-autocomplete=\"list\" aria-expanded=\"true\" aria-controls={`${inputId}-results`} aria-activedescendant={activeId ? `${inputId}-${activeId}` : undefined} value={query} onChange={event => { setQuery(event.target.value); setActiveIndex(null); }} onKeyDown={handleKeyDown} placeholder={placeholder} autoComplete=\"off\"/>\n      <AnimatePresence mode=\"popLayout\" initial={false}>\n        {query ? <motion.button key=\"clear\" className={styles.clearButton} type=\"button\" aria-label=\"Clear search\" onClick={() => { setQuery(\"\"); setActiveIndex(null); inputRef.current?.focus(); }} initial={reduced ? false : { opacity: 0, scale: .6, filter: `blur(${motionTokens.blur.subtle}px)` }} animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }} exit={reduced ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, scale: .6, filter: `blur(${motionTokens.blur.subtle}px)`, transition: leave }} transition={reduced ? { duration: 0 } : { default: motionTokens.spring.snappy, opacity: { duration: motionTokens.duration.instant } }}><X width={15} height={15} aria-hidden=\"true\"/></motion.button> : null}\n      </AnimatePresence>\n      {onClose ? <button className={styles.closeButton} type=\"button\" aria-label=\"Esc, close command palette\" onClick={onClose}>Esc</button> : null}\n      <kbd className={styles.commandKey}>⌘ K</kbd>\n    </div>\n    <motion.div className={styles.resultsFrame} initial={false} animate={{ height: listHeight }} transition={reduced ? { duration: 0 } : motionTokens.spring.smooth}>\n      <motion.div ref={listRef} layoutScroll id={`${inputId}-results`} className={styles.results} role=\"listbox\" aria-label=\"Command results\" onPointerMove={onListPointerMove} onClick={nearest.onClick}>\n        <motion.span className={styles.highlight} style={{ y: highlightY, height: highlightHeight, opacity: highlightOpacity }} aria-hidden=\"true\"/>\n        {/* Results leave before the empty state arrives, so the frame makes one height change instead of two. */}\n        <AnimatePresence mode=\"wait\" initial={false}>\n          {filtered.length ? <motion.div key=\"results\" initial={reduced ? false : { opacity: 0 }} animate={{ opacity: 1 }} exit={reduced ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, transition: leave }} transition={enter}>\n            {/* Filtered-out rows pop out of the flow as they fade, so the rest glide up and the frame starts closing on the same keystroke. */}\n            <AnimatePresence mode=\"popLayout\" initial={false} custom={glide}>\n              {groupedItems.map(([group, entries]) => <motion.div layout={glide ? \"position\" : false} className={styles.group} role=\"group\" aria-label={group} key={group} variants={rowExit} initial={reduced ? false : { opacity: 0 }} animate={{ opacity: 1 }} exit=\"exit\" transition={reduced ? { duration: 0 } : { default: enter, layout: motionTokens.spring.smooth }}>\n                <span className={styles.groupHeading} aria-hidden=\"true\">{group}</span>\n                <AnimatePresence mode=\"popLayout\" initial={false} custom={glide}>{entries.map(({ item, index }) => <motion.button layout={glide ? \"position\" : false} key={item.id} id={`${inputId}-${item.id}`} className={`${styles.result} ${index === safeActiveIndex ? styles.activeResult : \"\"}`} type=\"button\" role=\"option\" tabIndex={-1} aria-selected={index === safeActiveIndex} onClick={() => choose(item)} data-index={index} variants={rowExit} initial={reduced ? false : { opacity: 0 }} animate={{ opacity: 1 }} exit=\"exit\" transition={reduced ? { duration: 0 } : { default: enter, layout: motionTokens.spring.smooth }}><span className={styles.itemIcon} aria-hidden=\"true\">{item.icon ?? <CommandIcon width={16} height={16}/>}</span><span className={styles.resultCopy}><strong>{item.label}</strong>{item.description && <small>{item.description}</small>}</span>{item.shortcut && <kbd className={styles.shortcut}>{item.shortcut}</kbd>}</motion.button>)}</AnimatePresence>\n              </motion.div>)}\n            </AnimatePresence>\n          </motion.div> : <motion.div key=\"empty\" className={styles.empty} initial={reduced ? false : { opacity: 0, y: 6, filter: `blur(${motionTokens.blur.subtle}px)` }} animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }} exit={reduced ? { opacity: 0, transition: { duration: 0 } } : { opacity: 0, y: -4, transition: leave }} transition={enter}><span><Search width={20} height={20} aria-hidden=\"true\"/></span><strong>No matching actions</strong><small>Try a different word or clear the search.</small></motion.div>}\n        </AnimatePresence>\n      </motion.div>\n    </motion.div>\n  </motion.div>;\n}\n\nexport default CommandPalette;\n"},{"path":"registry/components/command-palette/command-palette.module.css","type":"registry:component","target":"@components/silicon-ui/command-palette/command-palette.module.css","content":".palette {\n  width: 100%;\n  overflow: hidden;\n  border: 1px solid var(--border);\n  border-radius: var(--radius-container);\n  background: var(--surface);\n  box-shadow: var(--shadow-floating);\n  transform-origin: top center;\n}\n\n.searchRow {\n  position: relative;\n  display: flex;\n  min-height: 54px;\n  align-items: center;\n  gap: var(--space-group);\n  padding: var(--space-related) var(--space-inset);\n  border-bottom: 1px solid var(--border-subtle);\n  transition: background var(--duration-fast) var(--ease-standard);\n}\n\n.searchRow:focus-within { background: var(--surface-muted); }\n.searchIcon, .itemIcon { display: grid; flex: none; place-items: center; color: var(--text-muted); }\n.searchIcon { width: 22px; height: 22px; }\n.searchRow input { min-width: 0; flex: 1; border: 0; outline: 0; background: transparent; color: var(--foreground); font: inherit; font-size: var(--text-sm); }\n.searchRow input::placeholder { color: var(--text-secondary); }\n.searchRow input:focus-visible { outline: none; }\n\n.commandKey, .shortcut {\n  display: inline-flex;\n  align-items: center;\n  justify-content: center;\n  flex: none;\n  border: 1px solid var(--border);\n  border-radius: var(--radius-detail);\n  background: var(--surface-muted);\n  color: var(--text-secondary);\n  font-family: inherit;\n  font-size: var(--text-xs);\n  font-weight: var(--weight-medium);\n  line-height: 1;\n  font-variant-numeric: tabular-nums;\n}\n\n.commandKey { min-width: 38px; height: 24px; padding: 0 var(--space-related); gap: var(--space-hair); }\n.clearButton { display: grid; width: 24px; height: 24px; flex: none; place-items: center; border: 0; border-radius: var(--radius-detail); background: transparent; color: var(--text-muted); cursor: pointer; transition: color var(--duration-fast) var(--ease-standard), background-color var(--duration-fast) var(--ease-standard); }\n@media (hover: hover) and (pointer: fine) { .clearButton:hover, .closeButton:hover { background: var(--surface); color: var(--foreground); } }\n.clearButton:active, .closeButton:active { background: var(--surface); color: var(--foreground); }\n.closeButton { display: grid; min-width: 27px; height: 24px; flex: none; place-items: center; border: 1px solid var(--border-subtle); border-radius: var(--radius-detail); background: transparent; color: var(--text-secondary); padding: 0 var(--space-related); font: inherit; font-size: var(--text-xs); font-weight: var(--weight-medium); line-height: 1; cursor: pointer; transition: color var(--duration-fast) var(--ease-standard), background-color var(--duration-fast) var(--ease-standard); }\n\n/* The frame animates to the list height; the list keeps its own scroll. */\n.resultsFrame { overflow: hidden; }\n.results { position: relative; max-height: 342px; overflow: auto; padding: var(--space-related) var(--space-related); }\n.highlight { position: absolute; top: 0; right: var(--space-related); left: var(--space-related); border-radius: var(--radius-detail); background: var(--surface-muted); opacity: 0; pointer-events: none; }\n/* Groups are positioned so a row that pops out of the flow is placed against the same box it was measured in, even mid-glide. */\n.group { position: relative; }\n.group + .group { margin-top: var(--space-related); }\n.groupHeading { display: block; padding: var(--space-related) var(--space-related) var(--space-tight); color: var(--text-secondary); font-size: var(--text-xs); font-weight: var(--weight-medium); line-height: var(--leading-body); }\n\n/* One line per result: the title, then its description in muted text, so the list stays short and scannable. */\n.result { position: relative; display: flex; width: 100%; min-height: 34px; align-items: center; gap: var(--space-group); border: 0; border-radius: var(--radius-detail); padding: 0 var(--space-related); background: transparent; color: var(--foreground); text-align: left; cursor: pointer; }\n/* The active row is drawn by the shared highlight; the row itself only tints its icon and arrow. */\n.itemIcon { transition: color var(--duration-fast) var(--ease-standard); }\n.itemIcon { display: grid; width: 16px; height: 16px; flex: none; place-items: center; color: var(--text-muted); }\n.itemIcon svg { width: 16px; height: 16px; }\n.resultCopy { display: flex; min-width: 0; flex: 1; align-items: baseline; gap: var(--space-related); }\n.resultCopy strong, .resultCopy small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.resultCopy strong { flex: none; max-width: 100%; }\n.resultCopy small { min-width: 0; }\n.resultCopy strong { font-size: var(--text-sm); font-weight: var(--weight-medium); }\n.resultCopy small { color: var(--text-secondary); font-size: var(--text-xs); }\n.shortcut { min-width: 18px; height: 18px; padding: 0 var(--space-tight); border-color: transparent; border-radius: var(--radius-detail); font-size: var(--text-xs); }\n.activeResult .itemIcon { color: var(--foreground); }\n.empty { display: grid; justify-items: center; gap: var(--space-tight); padding: var(--space-section) var(--space-group) var(--space-block); text-align: center; }\n.empty > span { display: grid; width: 32px; height: 32px; place-items: center; margin-bottom: var(--space-tight); color: var(--text-muted); }\n.empty strong { font-size: var(--text-sm); font-weight: var(--weight-medium); }\n.empty small { color: var(--text-secondary); font-size: var(--text-xs); }\n.visuallyHidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }\n\n@media (max-width: 480px) {\n  .searchRow { gap: var(--space-related); padding: var(--space-related) var(--space-group); }\n  .results { padding: var(--space-related); }\n  .highlight { right: var(--space-related); left: var(--space-related); }\n  .result { gap: var(--space-related); }\n  .shortcut, .commandKey { display: none; }\n  }\n\n@media (max-width: 340px) {\n    .result { padding-inline: var(--space-related); }\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .searchRow, .itemIcon, .clearButton, .closeButton { transition: none; }\n}\n"},{"path":"lib/fluid-hover.tsx","type":"registry:lib","target":"@components/silicon-ui/lib/fluid-hover.tsx","content":"\"use client\";\n\n/**\n * Fluid hover: in a set of items (a menu, a list, tabs, a grid), the item nearest the pointer is lit, even while the\n * pointer is in a gap, the padding or past the last item, and one highlight springs between items. A click in a gap goes\n * to the lit item, so what is lit is what a click hits. A new pointer entry fades the highlight in where it lands instead\n * of sliding it over from the last item. The keyboard moves it without travel, and reduced motion keeps the fade but\n * drops the travel.\n *\n *   const list = useRef<HTMLUListElement>(null);\n *   const hover = useFluidHover(list, { items: \"[data-item]\" });\n *   <ul ref={list} className={styles.list} {...hover.handlers}>      // .list { position: relative }\n *     <FluidHoverHighlight hover={hover} className={styles.highlight} />\n *     …items…\n *   </ul>\n *\n * Adapted from Fluid Functionalism's use-fluid-hover and fluid-hover-highlight by Micka Touillaud (MIT),\n * https://github.com/mickadesign/fluid-functionalism. Items are found by a selector instead of registering themselves,\n * so a component adopts it without changing its items.\n */\nimport { useEffect, useEffectEvent, useRef, useState } from \"react\";\nimport type { FocusEvent, MouseEvent, PointerEvent, RefObject } from \"react\";\nimport { AnimatePresence, motion, useReducedMotion } from \"motion/react\";\nimport { motionTokens } from \"./motion-tokens\";\n\n/** An item's box in the container's own layout space (unaffected by transforms or scrolling). */\nexport interface FluidRect { top: number; left: number; width: number; height: number }\n\nexport interface FluidHoverState {\n  /** Where the highlight sits, or null when nothing is lit. */\n  rect: FluidRect | null;\n  /** The lit item. */\n  item: HTMLElement | null;\n  /** False when the highlight should jump (keyboard, a resize) rather than travel. */\n  glide: boolean;\n  /** Steps on each new pointer entry, so the highlight fades in where it lands. */\n  session: number;\n}\n\nexport interface FluidHoverOptions {\n  /** Selector for the items inside the container. */\n  items: string;\n  /** \"y\" for lists (default), \"x\" for a row of tabs, \"xy\" for grids. */\n  axis?: \"x\" | \"y\" | \"xy\";\n  /** Items the highlight skips (and a gap click never activates). Defaults to disabled or aria-disabled items. */\n  isItemDisabled?: (item: HTMLElement) => boolean;\n  /** \"skip\" (default) lights the nearest enabled item even over a disabled one; \"clear\" lights nothing over a disabled item (a calendar's unavailable days). */\n  disabled?: \"skip\" | \"clear\";\n  /** Route a click in a gap to the lit item. On by default; turn it off where empty space should stay inert. */\n  gapClick?: boolean;\n  /** Light the item that receives keyboard focus. On by default. */\n  followFocus?: boolean;\n}\n\nconst defaultDisabled = (item: HTMLElement) =>\n  item.matches(\":disabled, [aria-disabled='true'], [data-disabled]\");\n\n/** Controls that sit between items keep their own clicks. */\nconst CONTROL = \"input, textarea, select, button, a, summary, [contenteditable], [role='textbox'], [role='searchbox'], [role='button']\";\n\n/** The item's box relative to the container, summing offsets through positioned ancestors in between. */\nexport function rectOf(item: HTMLElement, container: HTMLElement): FluidRect {\n  let top = item.offsetTop, left = item.offsetLeft;\n  let parent = item.offsetParent as HTMLElement | null;\n  while (parent && parent !== container && container.contains(parent)) {\n    top += parent.offsetTop + parent.clientTop;\n    left += parent.offsetLeft + parent.clientLeft;\n    parent = parent.offsetParent as HTMLElement | null;\n  }\n  return { top, left, width: item.offsetWidth, height: item.offsetHeight };\n}\n\n/**\n * The item the pointer is inside, or else the one whose edge is nearest along the axis (both axes for a grid). Edges, not\n * centres, so a gap next to a wide item still lights the item the pointer is closer to.\n */\nexport function pickNearest(items: HTMLElement[], x: number, y: number, axis: \"x\" | \"y\" | \"xy\"): HTMLElement | null {\n  let nearest: HTMLElement | null = null, best = Infinity;\n  for (const item of items) {\n    const r = item.getBoundingClientRect();\n    if (!r.width && !r.height) continue;\n    if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) return item;\n    const dx = Math.max(r.left - x, 0, x - r.right), dy = Math.max(r.top - y, 0, y - r.bottom);\n    const distance = axis === \"x\" ? dx : axis === \"y\" ? dy : Math.hypot(dx, dy);\n    if (distance < best) { best = distance; nearest = item; }\n  }\n  return nearest;\n}\n\n/** Hands a gap click to the item as a real mouse click (detail, modifiers and coordinates kept), so the item reads it as a pointer press, not a keyboard one. */\nfunction forwardClick(item: HTMLElement, event: MouseEvent<HTMLElement>) {\n  const { detail, clientX, clientY, screenX, screenY, ctrlKey, shiftKey, altKey, metaKey, button, buttons } = event;\n  item.dispatchEvent(new globalThis.MouseEvent(\"click\", { bubbles: true, cancelable: true, composed: true, view: window, detail, clientX, clientY, screenX, screenY, ctrlKey, shiftKey, altKey, metaKey, button, buttons }));\n}\n\n/** Whether an event happened inside the element whose handler hears it, not in a portalled child (a submenu, a tooltip). */\nconst isOwn = (event: { currentTarget: EventTarget; target: EventTarget }) =>\n  !(event.currentTarget instanceof Node) || !(event.target instanceof Node) || event.currentTarget.contains(event.target);\n\nexport function useFluidHover<T extends HTMLElement>(container: RefObject<T | null>, options: FluidHoverOptions) {\n  const { items: selector, axis = \"y\", isItemDisabled = defaultDisabled, disabled = \"skip\", gapClick = true, followFocus = true } = options;\n  const [state, setState] = useState<FluidHoverState>({ rect: null, item: null, glide: false, session: 0 });\n  const current = useRef(state);\n  const pointer = useRef(false);\n  const entering = useRef(false);\n  const frame = useRef(0);\n\n  function commit(next: FluidHoverState) {\n    const prev = current.current;\n    if (prev.item === next.item && prev.session === next.session && sameRect(prev.rect, next.rect)) return;\n    current.current = next;\n    setState(next);\n  }\n\n  function light(item: HTMLElement | null, glide: boolean) {\n    const root = container.current;\n    if (!root || !item) return commit({ ...current.current, rect: null, item: null, glide });\n    let session = current.current.session;\n    if (entering.current) { entering.current = false; session += 1; }\n    commit({ rect: rectOf(item, root), item, glide: glide && session === current.current.session, session });\n  }\n\n  const enabledItems = () => {\n    const root = container.current;\n    return root ? [...root.querySelectorAll<HTMLElement>(selector)].filter(item => !isItemDisabled(item)) : [];\n  };\n\n  // The lit item can move under a still highlight (a resize, content above it changing): follow it without travel.\n  const follow = useEffectEvent(() => { const { item } = current.current; if (item?.isConnected) light(item, false); });\n  useEffect(() => {\n    const root = container.current;\n    if (!root || typeof ResizeObserver === \"undefined\") return;\n    const observer = new ResizeObserver(() => follow());\n    observer.observe(root);\n    return () => observer.disconnect();\n  }, [container]);\n  useEffect(() => () => cancelAnimationFrame(frame.current), []);\n\n  const handlers = {\n    onMouseEnter: () => { entering.current = true; },\n    onMouseMove: (event: MouseEvent<T>) => {\n      if (!isOwn(event)) return;\n      pointer.current = true;\n      const { clientX, clientY } = event;\n      cancelAnimationFrame(frame.current);\n      frame.current = requestAnimationFrame(() => {\n        const over = disabled === \"clear\" ? document.elementFromPoint(clientX, clientY)?.closest<HTMLElement>(selector) : null;\n        light(over && isItemDisabled(over) ? null : pickNearest(enabledItems(), clientX, clientY, axis), true);\n      });\n    },\n    onMouseLeave: () => { cancelAnimationFrame(frame.current); entering.current = false; light(null, false); },\n    onKeyDownCapture: () => { pointer.current = false; },\n    onFocus: (event: FocusEvent<T>) => {\n      if (!followFocus || pointer.current || !isOwn(event)) return;\n      const item = event.target instanceof HTMLElement ? event.target.closest<HTMLElement>(selector) : null;\n      if (item && container.current?.contains(item) && !isItemDisabled(item)) light(item, false);\n    },\n    onBlur: (event: FocusEvent<T>) => {\n      if (!pointer.current && !event.currentTarget.contains(event.relatedTarget as Node | null)) light(null, false);\n    },\n    onClick: (event: MouseEvent<T>) => {\n      if (!gapClick || !isOwn(event)) return;\n      const target = event.target as Element;\n      if (!target.isConnected || target.closest(selector) || target.closest(CONTROL)) return;\n      const { item } = current.current;\n      if (item?.isConnected && !isItemDisabled(item)) forwardClick(item, event);\n    },\n  };\n\n  /** Clears the highlight at once, such as when a menu opens again. */\n  const reset = () => { cancelAnimationFrame(frame.current); entering.current = true; light(null, false); };\n\n  return { ...state, handlers, reset, light };\n}\n\nexport interface NearestItemOptions extends Omit<FluidHoverOptions, \"followFocus\"> {\n  /** Called with the nearest enabled item as the mouse moves over the container. */\n  onPick: (item: HTMLElement) => void;\n}\n\n/**\n * Fluid hover's picking without its highlight, for a list that already keeps its own active item and highlight (a listbox\n * with aria-activedescendant, a roving list): the mouse picks the nearest enabled item, gaps and padding included, and a\n * click in a gap goes to that item. Spread the result on the container.\n */\n// A hook only so callbacks that touch refs can be passed during render; it keeps no state.\nexport function useNearestItem<T extends HTMLElement>({ items: selector, axis = \"y\", isItemDisabled = defaultDisabled, gapClick = true, onPick }: NearestItemOptions) {\n  const nearest = (event: MouseEvent<T>) => {\n    if (!isOwn(event)) return null;\n    const items = [...event.currentTarget.querySelectorAll<HTMLElement>(selector)].filter(item => !isItemDisabled(item));\n    return pickNearest(items, event.clientX, event.clientY, axis);\n  };\n  return {\n    onPointerMove: (event: PointerEvent<T>) => { if (event.pointerType !== \"mouse\") return; const item = nearest(event); if (item) onPick(item); },\n    onClick: (event: MouseEvent<T>) => {\n      if (!gapClick) return;\n      const target = event.target as Element;\n      if (!target.isConnected || target.closest(selector) || target.closest(CONTROL)) return;\n      const item = nearest(event);\n      if (item) forwardClick(item, event);\n    },\n  };\n}\n\nconst sameRect = (a: FluidRect | null, b: FluidRect | null) =>\n  a === b || (!!a && !!b && a.top === b.top && a.left === b.left && a.width === b.width && a.height === b.height);\n\nexport interface FluidHoverHighlightProps {\n  /** The state from useFluidHover (or any { rect, glide, session }). */\n  hover: Pick<FluidHoverState, \"rect\" | \"glide\" | \"session\">;\n  /** Radius, fill, z-index. The container must be position: relative; the highlight is placed at its top-left corner. */\n  className?: string;\n  /** Extra attributes for styling, such as data-tone. */\n  tone?: string;\n}\n\n/** The one highlight a fluid hover set renders: it springs between items on transforms, and fades in and out. */\nexport function FluidHoverHighlight({ hover, className, tone }: FluidHoverHighlightProps) {\n  const reduced = useReducedMotion() ?? false;\n  const { rect, glide, session } = hover;\n  const place = rect ? { x: rect.left, y: rect.top, width: rect.width, height: rect.height } : undefined;\n  return (\n    <AnimatePresence initial={false}>\n      {place ? (\n        <motion.span key={session} className={className} data-tone={tone} aria-hidden=\"true\"\n          style={{ position: \"absolute\", top: 0, left: 0, pointerEvents: \"none\" }}\n          initial={{ opacity: 0, ...place }}\n          animate={{ opacity: 1, ...place }}\n          exit={{ opacity: 0, transition: motionTokens.spring.fast.exit }}\n          transition={{ default: glide && !reduced ? motionTokens.spring.fast : { duration: 0 }, opacity: { duration: motionTokens.duration.fast } }} />\n      ) : null}\n    </AnimatePresence>\n  );\n}\n"}],"docs":"Docs and live preview: https://ui.teamofsilicons.com/command-palette","meta":{"tier":"free","kind":"block","docs":"https://ui.teamofsilicons.com/command-palette","markdown":"https://ui.teamofsilicons.com/command-palette.md","status":"stable"}}