{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"expandable-search-bar","type":"registry:component","title":"Expandable Search Bar","description":"A search icon that springs open into a full field with a suggestions dropdown: recent searches, live filtering, arrow-key navigation, / and Cmd+K to open, Escape to collapse. A real ARIA combobox, no dependencies.","dependencies":[],"registryDependencies":[],"files":[{"path":"components/viberdy/expandable-search-bar.tsx","content":"\"use client\";\n\nimport { Fragment, useEffect, useId, useRef, useState } from \"react\";\nimport type { KeyboardEvent as ReactKeyboardEvent } from \"react\";\n\ntype Tone = \"dark\" | \"light\";\ntype Item = { label: string; kind: \"recent\" | \"suggestion\" | \"query\" };\n\nconst NO_ITEMS: string[] = [];\n\n// Damped spring (stiffness 320, damping 28, mass 1) sampled into a CSS linear() easing.\nfunction springEasing(): string {\n  const w0 = Math.sqrt(320);\n  const z = 28 / (2 * w0);\n  const wd = w0 * Math.sqrt(1 - z * z);\n  const pts: string[] = [];\n  const n = 40;\n  for (let i = 0; i <= n; i++) {\n    const t = (i / n) * 0.6;\n    const v = 1 - Math.exp(-z * w0 * t) * (Math.cos(wd * t) + ((z * w0) / wd) * Math.sin(wd * t));\n    pts.push((i === n ? 1 : v).toFixed(3));\n  }\n  return \"linear(\" + pts.join(\", \") + \")\";\n}\n\nconst CSS = [\n  \".esb-w{transition:width 520ms cubic-bezier(.3,1.25,.5,1)}\",\n  \"@supports (transition-timing-function:linear(0,1)){.esb-w{transition-timing-function:\" + springEasing() + \"}}\",\n  '.esb-w[data-open=\"false\"]{transition-duration:340ms;transition-timing-function:cubic-bezier(.3,.7,.2,1)}',\n  \".esb-pill{box-shadow:inset 0 0 0 1px color-mix(in srgb,currentColor 16%,transparent);transition:box-shadow 200ms ease,background-color 200ms ease}\",\n  \".esb-pill:hover{box-shadow:inset 0 0 0 1px color-mix(in srgb,currentColor 28%,transparent)}\",\n  \".esb-pill:focus-within{box-shadow:inset 0 0 0 1px color-mix(in srgb,currentColor 48%,transparent),0 0 0 4px color-mix(in srgb,currentColor 11%,transparent)}\",\n  \".esb-in{opacity:0;transition:opacity 120ms ease}\",\n  '.esb-w[data-open=\"true\"] .esb-in{opacity:1;transition:opacity 220ms ease 130ms}',\n  \".esb-pop{transform-origin:top left;animation:esb-pop 220ms cubic-bezier(.2,.8,.2,1) both}\",\n  \".esb-row{animation:esb-row 240ms cubic-bezier(.2,.8,.2,1) both;animation-delay:calc(var(--i,0)*24ms + 40ms)}\",\n  \"@keyframes esb-pop{from{opacity:0;transform:translateY(-6px) scale(.97)}to{opacity:1;transform:none}}\",\n  \"@keyframes esb-row{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none}}\",\n  \"@keyframes esb-fade{from{opacity:0}to{opacity:1}}\",\n  \"@media (prefers-reduced-motion:reduce){.esb-w,.esb-w[data-open]{transition:none}.esb-in,.esb-w[data-open=true] .esb-in{transition:none}.esb-pop,.esb-row{animation-name:esb-fade;animation-duration:140ms;animation-delay:0s}}\",\n].join(\"\\n\");\n\nconst TONES: Record<Tone, { bg: string; fg: string; shadow: string }> = {\n  dark: {\n    bg: \"#0c0d10\",\n    fg: \"#eceef2\",\n    shadow: \"inset 0 0 0 1px rgba(255,255,255,0.09), 0 24px 48px -12px rgba(0,0,0,0.6), 0 2px 6px rgba(0,0,0,0.4)\",\n  },\n  light: {\n    bg: \"#ffffff\",\n    fg: \"#16181d\",\n    shadow: \"inset 0 0 0 1px rgba(0,0,0,0.08), 0 20px 40px -12px rgba(15,20,30,0.22), 0 2px 6px rgba(15,20,30,0.08)\",\n  },\n};\n\nconst MIX = (pct: number) => \"color-mix(in srgb, currentColor \" + pct + \"%, transparent)\";\n\nfunction Icon({ d, size = 16, className }: { d: string; size?: number; className?: string }) {\n  return (\n    <svg\n      aria-hidden\n      width={size}\n      height={size}\n      viewBox=\"0 0 24 24\"\n      fill=\"none\"\n      stroke=\"currentColor\"\n      strokeWidth={2}\n      strokeLinecap=\"round\"\n      strokeLinejoin=\"round\"\n      className={className}\n    >\n      <path d={d} />\n    </svg>\n  );\n}\nconst SEARCH = \"M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16ZM21 21l-4.3-4.3\";\nconst CLOSE = \"M18 6 6 18M6 6l12 12\";\nconst ENTER = \"M20 5v6a3 3 0 0 1-3 3H5M9 10l-4 4 4 4\";\nconst CLOCK =\"M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18ZM12 7v5l3 2\";\n\nfunction Match({ text, q }: { text: string; q: string }) {\n  const i = q ? text.toLowerCase().indexOf(q) : -1;\n  if (i < 0) return <>{text}</>;\n  return (\n    <>\n      {text.slice(0, i)}\n      <span style={{ color: \"currentColor\" }} className=\"font-medium\">\n        {text.slice(i, i + q.length)}\n      </span>\n      {text.slice(i + q.length)}\n    </>\n  );\n}\n\nexport function ExpandableSearchBar({\n  placeholder = \"Search...\",\n  width = 240,\n  suggestions = NO_ITEMS,\n  recent = NO_ITEMS,\n  onSearch,\n  onQueryChange,\n  defaultOpen = false,\n  shortcut = false,\n  panel = \"dark\",\n  className = \"\",\n}: {\n  placeholder?: string;\n  width?: number;\n  /** Suggestions filtered as you type; shown under the field. */\n  suggestions?: string[];\n  /** Recent searches shown first while the field is empty (submitted searches are added). */\n  recent?: string[];\n  onSearch?: (query: string) => void;\n  onQueryChange?: (query: string) => void;\n  defaultOpen?: boolean;\n  /** Press / or Cmd/Ctrl+K anywhere on the page to open and focus the field. */\n  shortcut?: boolean;\n  /** Surface of the suggestions panel. The field itself inherits currentColor. */\n  panel?: Tone;\n  className?: string;\n}) {\n  const [open, setOpen] = useState(defaultOpen);\n  const [query, setQuery] = useState(\"\");\n  const [recents, setRecents] = useState<string[]>(recent);\n  const [listOpen, setListOpen] = useState(defaultOpen);\n  const [active, setActive] = useState(-1);\n  const uid = useId().replace(/[^a-zA-Z0-9]/g, \"\");\n  const listId = \"esb\" + uid + \"list\";\n  const rootRef = useRef<HTMLDivElement>(null);\n  const fieldRef = useRef<HTMLDivElement>(null);\n  const inputRef = useRef<HTMLInputElement>(null);\n  const triggerRef = useRef<HTMLButtonElement>(null);\n  const wantFocus = useRef(false);\n  const refocusTrigger = useRef(false);\n\n  useEffect(() => {\n    fieldRef.current?.toggleAttribute(\"inert\", !open);\n    if (open && wantFocus.current) {\n      wantFocus.current = false;\n      inputRef.current?.focus({ preventScroll: true });\n    }\n    if (!open && refocusTrigger.current) {\n      refocusTrigger.current = false;\n      triggerRef.current?.focus({ preventScroll: true });\n    }\n  }, [open]);\n\n  useEffect(() => {\n    if (!shortcut) return;\n    const onKey = (e: KeyboardEvent) => {\n      const t = e.target as HTMLElement | null;\n      const typing = !!t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName));\n      const mod = (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"k\";\n      const slash = e.key === \"/\" && !e.metaKey && !e.ctrlKey && !e.altKey && !typing;\n      if (!mod && !slash) return;\n      e.preventDefault();\n      setListOpen(true);\n      if (fieldRef.current && !fieldRef.current.hasAttribute(\"inert\")) {\n        inputRef.current?.focus({ preventScroll: true });\n        inputRef.current?.select();\n        return;\n      }\n      wantFocus.current = true;\n      setOpen(true);\n    };\n    window.addEventListener(\"keydown\", onKey);\n    return () => window.removeEventListener(\"keydown\", onKey);\n  }, [shortcut]);\n\n  const q = query.trim().toLowerCase();\n  const items: Item[] = [];\n  if (!q) {\n    for (const r of recents.slice(0, 3)) items.push({ label: r, kind: \"recent\" });\n    for (const s of suggestions) {\n      if (items.length >= 5) break;\n      if (!recents.includes(s)) items.push({ label: s, kind: \"suggestion\" });\n    }\n  } else {\n    const seen = new Set<string>();\n    for (const r of recents) {\n      if (r.toLowerCase().includes(q) && !seen.has(r)) {\n        seen.add(r);\n        items.push({ label: r, kind: \"recent\" });\n      }\n    }\n    for (const s of suggestions) {\n      if (s.toLowerCase().includes(q) && !seen.has(s)) {\n        seen.add(s);\n        items.push({ label: s, kind: \"suggestion\" });\n      }\n    }\n    items.splice(5);\n    items.push({ label: query.trim(), kind: \"query\" });\n  }\n  const shown = open && listOpen && items.length > 0;\n  const act = active < items.length ? active : -1;\n  const tone = TONES[panel] ?? TONES.dark;\n\n  function commit(label: string) {\n    const v = label.trim();\n    if (!v) return;\n    setQuery(v);\n    setRecents((r) => [v, ...r.filter((x) => x !== v)].slice(0, 5));\n    setListOpen(false);\n    setActive(-1);\n    onSearch?.(v);\n  }\n\n  function collapse(refocus: boolean) {\n    setOpen(false);\n    setQuery(\"\");\n    setListOpen(false);\n    setActive(-1);\n    refocusTrigger.current = refocus;\n    onQueryChange?.(\"\");\n  }\n\n  function onKeyDown(e: ReactKeyboardEvent<HTMLInputElement>) {\n    if (e.nativeEvent.isComposing) return;\n    if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n      e.preventDefault();\n      if (!shown) {\n        setListOpen(true);\n        return;\n      }\n      const n = items.length;\n      setActive(e.key === \"ArrowDown\" ? (act + 1) % n : act <= 0 ? n - 1 : act - 1);\n    } else if (e.key === \"Enter\") {\n      e.preventDefault();\n      const it = act >= 0 ? items[act] : undefined;\n      commit(it ? it.label : query);\n    } else if (e.key === \"Escape\") {\n      e.preventDefault();\n      collapse(true);\n    }\n  }\n\n  const headerStyle = { color: MIX(48) };\n  let lastKind = \"\";\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"search\"\n      data-open={open}\n      className={\"esb-w relative h-11 shrink-0 \" + className}\n      style={{ width: open ? width : 44 }}\n      onBlur={(e) => {\n        if (!rootRef.current?.contains(e.relatedTarget as Node | null)) setListOpen(false);\n      }}\n    >\n      <style>{CSS}</style>\n      <div className=\"esb-pill absolute inset-0 overflow-hidden rounded-full\" style={{ background: MIX(5) }}>\n        {open ? (\n          <span aria-hidden className=\"pointer-events-none absolute left-[14px] top-1/2 -mt-2 opacity-70\">\n            <Icon d={SEARCH} />\n          </span>\n        ) : (\n          <button\n            ref={triggerRef}\n            type=\"button\"\n            title=\"Search\"\n            aria-label=\"Open search\"\n            aria-expanded={false}\n            aria-keyshortcuts={shortcut ? \"/ Control+K Meta+K\" : undefined}\n            onClick={() => {\n              wantFocus.current = true;\n              setListOpen(true);\n              setOpen(true);\n            }}\n            className=\"group absolute inset-0 flex cursor-pointer items-center rounded-full bg-transparent pl-[14px] text-inherit focus-visible:!rounded-full focus-visible:!outline-2 focus-visible:!outline-offset-2 focus-visible:!outline-current\"\n          >\n            <Icon\n              d={SEARCH}\n              className=\"opacity-70 transition-[opacity,transform] duration-200 group-hover:opacity-100 group-active:scale-90\"\n            />\n          </button>\n        )}\n        <div ref={fieldRef} className=\"esb-in absolute inset-y-0 flex items-center\" style={{ left: 40, width: Math.max(0, width - 40) }}>\n          <input\n            ref={inputRef}\n            type=\"text\"\n            role=\"combobox\"\n            aria-label={placeholder}\n            aria-expanded={shown}\n            aria-controls={listId}\n            aria-autocomplete=\"list\"\n            aria-activedescendant={shown && act >= 0 ? \"esb\" + uid + \"o\" + act : undefined}\n            enterKeyHint=\"search\"\n            autoComplete=\"off\"\n            spellCheck={false}\n            placeholder={placeholder}\n            value={query}\n            onChange={(e) => {\n              setQuery(e.target.value);\n              setListOpen(true);\n              setActive(-1);\n              onQueryChange?.(e.target.value);\n            }}\n            onFocus={() => setListOpen(true)}\n            onKeyDown={onKeyDown}\n            style={{ color: \"inherit\" }}\n            className=\"h-full min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-current placeholder:opacity-50 focus-visible:!outline-none [@media(pointer:coarse)]:text-[16px]\"\n          />\n          <button\n            type=\"button\"\n            aria-label={query ? \"Clear search\" : \"Close search\"}\n            onClick={() => {\n              if (query) {\n                setQuery(\"\");\n                setActive(-1);\n                onQueryChange?.(\"\");\n                inputRef.current?.focus({ preventScroll: true });\n              } else collapse(true);\n            }}\n            className=\"mr-[6px] flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full bg-transparent text-inherit opacity-60 transition-[opacity,background-color] duration-150 hover:opacity-100 focus-visible:!rounded-full focus-visible:!opacity-100 focus-visible:!outline-2 focus-visible:!outline-offset-0 focus-visible:!outline-current [@media(pointer:coarse)]:size-10\"\n            onMouseEnter={(e) => (e.currentTarget.style.background = MIX(12))}\n            onMouseLeave={(e) => (e.currentTarget.style.background = \"\")}\n          >\n            <Icon d={CLOSE} size={14} />\n          </button>\n        </div>\n      </div>\n\n      {shown ? (\n        <div\n          className=\"esb-pop absolute left-0 top-full z-20 mt-2 w-full min-w-[240px] max-w-[calc(100vw-2rem)] overflow-hidden rounded-2xl\"\n          style={{ background: tone.bg, color: tone.fg, boxShadow: tone.shadow }}\n        >\n          <ul id={listId} role=\"listbox\" aria-label=\"Search suggestions\" className=\"m-0 list-none p-1.5\">\n            {items.map((it, i) => {\n              const head = !q && it.kind !== lastKind && it.kind !== \"query\";\n              lastKind = it.kind;\n              return (\n                <Fragment key={it.kind + it.label}>\n                  {head ? (\n                    <div\n                      aria-hidden\n                      className=\"esb-row px-2.5 pb-1 pt-2 text-[11px] font-medium uppercase tracking-[0.14em]\"\n                      style={{ ...headerStyle, [\"--i\" as string]: i }}\n                    >\n                      {it.kind === \"recent\" ? \"Recent\" : \"Suggested\"}\n                    </div>\n                  ) : null}\n                  <div\n                    role=\"option\"\n                    id={\"esb\" + uid + \"o\" + i}\n                    aria-selected={act === i}\n                    onMouseDown={(e) => e.preventDefault()}\n                    onMouseMove={() => {\n                      if (act !== i) setActive(i);\n                    }}\n                    onClick={() => commit(it.label)}\n                    className=\"esb-row flex h-9 cursor-pointer items-center gap-2.5 rounded-[10px] px-2.5 text-[13.5px] transition-colors duration-100\"\n                    style={{ background: act === i ? MIX(9) : undefined, [\"--i\" as string]: i }}\n                  >\n                    <Icon d={it.kind === \"recent\" ? CLOCK : SEARCH} size={14} className=\"shrink-0 opacity-50\" />\n                    <span className=\"min-w-0 flex-1 truncate\" style={{ color: MIX(it.kind === \"query\" ? 70 : 62) }}>\n                      {it.kind === \"query\" ? (\n                        <>\n                          Search for <span style={{ color: \"currentColor\" }}>“{it.label}”</span>\n                        </>\n                      ) : (\n                        <Match text={it.label} q={q} />\n                      )}\n                    </span>\n                    {act === i ? (\n                      <kbd\n                        aria-hidden\n                        className=\"shrink-0 rounded-[5px] px-1.5 font-sans text-[11px] leading-[18px] opacity-70 [@media(pointer:coarse)]:hidden\"\n                        style={{ boxShadow: \"inset 0 0 0 1px \" + MIX(20) }}\n                      >\n                        <Icon d={ENTER} size={11} className=\"inline\" />\n                      </kbd>\n                    ) : null}\n                  </div>\n                </Fragment>\n              );\n            })}\n          </ul>\n          <div\n            aria-hidden\n            className=\"flex items-center gap-4 px-3.5 py-2 text-[11px] [@media(pointer:coarse)]:hidden\"\n            style={{ color: MIX(46), boxShadow: \"inset 0 1px 0 \" + MIX(8) }}\n          >\n            <span className=\"inline-flex items-center gap-1.5\">\n              <Icon d=\"M12 19V5M5 12l7-7 7 7\" size={11} />\n              <Icon d=\"M12 5v14M19 12l-7 7-7-7\" size={11} />\n              navigate\n            </span>\n            <span className=\"inline-flex items-center gap-1.5\">\n              <Icon d={ENTER} size={11} />\n              select\n            </span>\n            <span>esc close</span>\n          </div>\n        </div>\n      ) : null}\n      <span role=\"status\" className=\"sr-only\">\n        {shown ? items.length + (items.length === 1 ? \" suggestion\" : \" suggestions\") + \" available\" : \"\"}\n      </span>\n    </div>\n  );\n}\n","type":"registry:component","target":"components/viberdy/expandable-search-bar.tsx"}],"meta":{"tier":"free","tags":["search","input","expand","combobox","autocomplete","command","keyboard"],"href":"https://viberdy.dev/library/expandable-search-bar","aiPrompt":"Create a single-file React + Tailwind component named ExpandableSearchBar (a \"use client\" file, React only: no framer-motion, no icon library; draw the icons as inline SVG, 24px viewBox, stroke 2, round caps).\n\nProps (all optional): placeholder \"Search...\"; width 240 (expanded px); suggestions string[] (default empty); recent string[] (default empty); onSearch(query); onQueryChange(query); defaultOpen false; shortcut false (when true: \"/\" outside inputs, or Cmd/Ctrl+K anywhere, opens and focuses the field); panel \"dark\" | \"light\" (default \"dark\", the suggestions panel surface); className on the root.\n\nRoot: div role=\"search\", relative, h-11 (44px), width 44px collapsed and `width` open, transitioning width only. Opening: 520ms, a damped spring (stiffness 320, damping 28, mass 1) sampled to 40 points and written as a CSS linear() easing (fallback cubic-bezier(.3,1.25,.5,1)); closing: 340ms cubic-bezier(.3,.7,.2,1). Reduced motion: no transition. Inside, one absolute pill (inset 0, rounded-full, overflow hidden, background currentColor 5% via color-mix) whose 1px ring is an inset box-shadow, never a border: currentColor 16% at rest, 28% hover, 48% plus a 4px 11% halo on :focus-within. The component inherits text colour (currentColor), so it works on light and dark pages.\n\nCollapsed: a full-size button (aria-label \"Open search\", aria-expanded false, aria-keyshortcuts when shortcut) with the 16px search icon at left 14px (opacity .7, 1 on hover, scale .9 pressed). Open: the icon is a plain span in the same place. A field wrapper (absolute, left 40px, fixed width = width - 40, so nothing reflows while the pill grows) holds an input and a 32px round button, and fades in (opacity 220ms after a 130ms delay; instant out). It is `inert` (toggleAttribute in an effect) while collapsed. Input: type text, role combobox, aria-label = placeholder, aria-expanded, aria-controls the listbox, aria-autocomplete list, aria-activedescendant, enterKeyHint search, autoComplete off, text-sm (16px on coarse pointers), transparent, no outline (the pill shows focus), placeholder at 50% opacity. Right button: X icon, label \"Clear search\" while there is text (clears, keeps focus) else \"Close search\" (collapses); hover background currentColor 12%; 40px on coarse pointers; focus ring currentColor outline 2px.\n\nSuggestions panel (only when open, list visible and there are rows): absolute under the pill, mt 8px, width 100% with min-width 240px, rounded-2xl, p 6px. Dark: #0c0d10 text #eceef2 ring rgba(255,255,255,.09) shadow 0 24px 48px -12px rgba(0,0,0,.6); light: #fff text #16181d ring rgba(0,0,0,.08) soft shadow. Enter animation 220ms cubic-bezier(.2,.8,.2,1) from opacity 0, translateY(-6px), scale .97 (origin top left); rows stagger in 24ms apart. Rows: a div role=\"listbox\" list of option divs (36px high, rounded 10px, 13.5px text, 14px icon at 50% opacity: clock for recent, magnifier otherwise). Empty query: headers \"Recent\" (up to 3) then \"Suggested\" (to 5 rows total), 11px uppercase tracking .14em at 48%. With a query: recents and suggestions that contain it (case-insensitive, max 5), matched text at full colour (medium weight) and the rest at 62%, then a final row \"Search for “query”\". Active row background currentColor 9% and a small \"↵\" kbd. A footer \"↑↓ navigate · ↵ select · esc close\" (11px, 46%, hidden on coarse pointers) sits under a 1px inset top line. A polite sr-only status announces \"N suggestions available\".\n\nBehaviour: focus or typing opens the list; ArrowDown/ArrowUp move the active row (wrapping; ArrowDown opens a closed list); Enter picks the active row or submits the typed text (ignore during IME composition); picking sets the text, adds it to the front of the session recents (max 5), closes the list and calls onSearch. Escape clears, collapses and returns focus to the icon button. Blur out of the root closes the list but keeps the field open. Rows use mousedown preventDefault so the input keeps focus; hover moves the active row. Opening (click or shortcut) focuses the input with preventScroll. Collapsing clears the query. defaultOpen starts open with the list visible without focusing.\nFocus rings must be important utilities (outline-2, outline-current) because host stylesheets may set :focus-visible globally. Styles for the animations live in one static <style> string rendered beside the elements (never inside the button).","license":"https://viberdy.dev/license"}}