{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"expanding-search","type":"registry:component","title":"Expanding search","description":"Opens from a circle into a search field, and closes faster than it opens.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/expanding-search.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useEffect, useId, useRef, useState } from \"react\";\nimport { flushSync } from \"react-dom\";\nimport { AnimatePresence, motion } from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\n// Matches the h-10 height, so the collapsed state is a true circle.\nconst COLLAPSED = 40;\n// Width animates rather than a layout transform on purpose: Motion's layout\n// animation scales the box and has to counter-scale border-radius every\n// frame, while a real width keeps rounded-full exact at every step. The\n// field only grows into space the wrapper already reserves, so nothing\n// around it reflows.\nconst EXPAND = { type: \"spring\", visualDuration: 0.28, bounce: 0 } as const;\n// Closing is the system tidying up, so it gets out of the way faster.\nconst COLLAPSE = { type: \"spring\", visualDuration: 0.2, bounce: 0 } as const;\nconst INSTANT = { duration: 0 } as const;\nconst ICON_SWAP = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\nconst EASE_OUT = [0.23, 1, 0.32, 1] as const;\n// Held back until the width has mostly settled, so the text never appears\n// squeezed inside a half-open pill.\nconst PLACEHOLDER_IN = { duration: 0.15, delay: 0.16, ease: EASE_OUT };\nconst PLACEHOLDER_OUT = { duration: 0.08, ease: EASE_OUT };\n\nfunction isEditable(target: EventTarget | null) {\n  if (!(target instanceof HTMLElement)) return false;\n  return (\n    target.isContentEditable ||\n    target.tagName === \"INPUT\" ||\n    target.tagName === \"TEXTAREA\" ||\n    target.tagName === \"SELECT\"\n  );\n}\n\nexport function ExpandingSearch({\n  label = \"Search\",\n  placeholder = \"Search\",\n  width = 280,\n  shortcut = \"/\",\n  onSearch,\n  onOpenChange,\n  className,\n}: {\n  label?: string;\n  placeholder?: string;\n  width?: number;\n  shortcut?: string | null;\n  onSearch?: (query: string) => void;\n  onOpenChange?: (open: boolean) => void;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const id = useId();\n  const [open, setOpen] = useState(false);\n  const [query, setQuery] = useState(\"\");\n  const rootRef = useRef<HTMLFormElement>(null);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const triggerRef = useRef<HTMLButtonElement>(null);\n\n  // Opening a search is occasional rather than constant, so the shortcut\n  // morphs just like a click does; the animation shows where the field came\n  // from.\n  const change = (next: boolean) => {\n    // The target has to be visible before focus can move to it. Focusing in\n    // the same event also lets mobile browsers raise the keyboard.\n    flushSync(() => {\n      setOpen(next);\n      if (!next) setQuery(\"\");\n    });\n    onOpenChange?.(next);\n  };\n\n  const expand = () => {\n    change(true);\n    inputRef.current?.focus();\n  };\n\n  useEffect(() => {\n    if (!shortcut) return;\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key !== shortcut || open || e.defaultPrevented) return;\n      if (e.metaKey || e.ctrlKey || e.altKey || isEditable(e.target)) return;\n      // Inert copies, like the index preview, stay quiet.\n      if (rootRef.current?.closest(\"[inert]\")) return;\n      e.preventDefault();\n      expand();\n    };\n    document.addEventListener(\"keydown\", onKey);\n    return () => document.removeEventListener(\"keydown\", onKey);\n  });\n\n  const widthTransition = reduceMotion ? INSTANT : open ? EXPAND : COLLAPSE;\n  const hiddenIcon = reduceMotion\n    ? { opacity: 0 }\n    : { scale: 0.25, opacity: 0, filter: \"blur(4px)\" };\n\n  return (\n    <div className={cn(\"flex justify-end\", className)} style={{ width }}>\n      <motion.form\n        ref={rootRef}\n        role=\"search\"\n        initial={false}\n        animate={{ width: open ? width : COLLAPSED }}\n        transition={widthTransition}\n        onSubmit={(e) => {\n          e.preventDefault();\n          onSearch?.(query);\n        }}\n        onBlur={(e) => {\n          if (!open || query !== \"\") return;\n          if (rootRef.current?.contains(e.relatedTarget as Node | null)) return;\n          change(false);\n        }}\n        className={cn(\n          \"relative h-10 shrink-0 overflow-hidden rounded-full bg-muted text-foreground shadow-raised transition-[scale] duration-150 ease-out motion-reduce:transition-none\",\n          \"has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-foreground\",\n          \"[&:has(>[data-trigger]:active)]:scale-[0.96]\",\n        )}\n      >\n        {/* Pinned to the left edge, so it rides the growing edge across\n            instead of needing an animation of its own. */}\n        <svg\n          viewBox=\"0 0 16 16\"\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth={1.5}\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n          aria-hidden\n          className={cn(\n            \"pointer-events-none absolute top-3 left-3 size-4 transition-[color] duration-150 ease-out\",\n            open && \"text-muted-foreground\",\n          )}\n        >\n          <circle cx=\"7\" cy=\"7\" r=\"4.25\" />\n          <path d=\"m10.25 10.25 3 3\" />\n        </svg>\n\n        <button\n          ref={triggerRef}\n          type=\"button\"\n          data-trigger\n          aria-label={label}\n          aria-expanded={open}\n          aria-controls={id}\n          aria-keyshortcuts={shortcut ?? undefined}\n          onClick={expand}\n          className={cn(\n            \"absolute inset-0 rounded-full outline-hidden\",\n            open && \"invisible\",\n          )}\n        />\n\n        <label htmlFor={id} className=\"sr-only\">\n          {label}\n        </label>\n        {/* Full width from the start, so typed text never reflows while the\n            pill is still opening around it. */}\n        <input\n          ref={inputRef}\n          id={id}\n          type=\"search\"\n          autoComplete=\"off\"\n          spellCheck={false}\n          value={query}\n          onChange={(e) => setQuery(e.target.value)}\n          onKeyDown={(e) => {\n            if (e.key !== \"Escape\") return;\n            e.preventDefault();\n            change(false);\n            triggerRef.current?.focus();\n          }}\n          style={{ width }}\n          className={cn(\n            \"absolute inset-y-0 left-0 bg-transparent pr-10 pl-9 text-sm outline-hidden [&::-webkit-search-cancel-button]:appearance-none\",\n            !open && \"invisible\",\n          )}\n        />\n        <motion.span\n          aria-hidden\n          initial={false}\n          animate={{ opacity: open && query === \"\" ? 1 : 0 }}\n          // Typing hides it instantly, like a native placeholder, so the first\n          // letter never lands underneath it. Only opening and closing fade.\n          transition={\n            query !== \"\"\n              ? INSTANT\n              : open\n                ? PLACEHOLDER_IN\n                : PLACEHOLDER_OUT\n          }\n          className=\"pointer-events-none absolute top-1/2 left-9 -translate-y-1/2 text-sm whitespace-nowrap text-muted-foreground\"\n        >\n          {placeholder}\n        </motion.span>\n\n        <AnimatePresence initial={false}>\n          {open && query !== \"\" && (\n            <motion.button\n              key=\"clear\"\n              type=\"button\"\n              aria-label=\"Clear search\"\n              initial={hiddenIcon}\n              animate={{ scale: 1, opacity: 1, filter: \"blur(0px)\" }}\n              exit={hiddenIcon}\n              transition={ICON_SWAP}\n              onClick={() => {\n                setQuery(\"\");\n                inputRef.current?.focus();\n              }}\n              className=\"absolute top-1.5 right-1.5 flex size-7 items-center justify-center rounded-full text-muted-foreground outline-hidden transition-[color] duration-150 ease-out hover:text-foreground focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-foreground active:scale-[0.96]\"\n            >\n              <svg\n                viewBox=\"0 0 16 16\"\n                fill=\"none\"\n                stroke=\"currentColor\"\n                strokeWidth={1.5}\n                strokeLinecap=\"round\"\n                aria-hidden\n                className=\"size-3.5\"\n              >\n                <path d=\"m4.5 4.5 7 7M11.5 4.5l-7 7\" />\n              </svg>\n            </motion.button>\n          )}\n        </AnimatePresence>\n      </motion.form>\n    </div>\n  );\n}\n\nexport default function ExpandingSearchDemo() {\n  const [open, setOpen] = useState(false);\n\n  return (\n    <div className=\"flex flex-col items-center gap-4\">\n      <div className=\"relative flex items-center\">\n        {/* Sits under the pill and fades as it opens, so the header keeps\n            its size and nothing moves. */}\n        <span\n          aria-hidden={open}\n          className={cn(\n            \"pointer-events-none absolute left-1 text-sm font-medium text-foreground transition-[opacity] duration-150 ease-out\",\n            open && \"opacity-0\",\n          )}\n        >\n          Projects\n        </span>\n        <ExpandingSearch placeholder=\"Search projects\" onOpenChange={setOpen} />\n      </div>\n      <p className=\"text-xs text-muted-foreground\">\n        Press{\" \"}\n        <kbd className=\"rounded border border-border px-1 font-mono\">/</kbd> to\n        search\n      </p>\n    </div>\n  );\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/expanding-search"}