{
  "name": "cai-site-search",
  "type": "registry:ui",
  "description": "CAI site search: Cmd/Ctrl+K command dialog over a site index with lazy loading, ranked and grouped results, highlighting and full keyboard support",
  "files": [
    {
      "path": "components/ui/cai-site-search.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { createPortal } from \"react-dom\"\nimport { useRouter } from \"next/navigation\"\n\nimport { cn } from \"@/lib/utils\"\n\n/**\n * CAI site search: one command-style dialog over a site's pages and articles.\n *\n * - Opens from a trigger (icon or field), Cmd/Ctrl+K, or \"/\" outside inputs.\n * - Loads its index lazily from `indexUrl` on first open (or takes `items`).\n * - Ranks by title, then tags, then description; groups results by `group`.\n * - Combobox pattern: arrow keys move, Enter opens, Esc closes, focus returns\n *   to the trigger.\n *\n * Index shape (JSON array, or { items: [...] }):\n *   { title, href, description?, group?, tags?, keywords? }\n */\n\nexport type CaiSearchItem = {\n  title: string\n  href: string\n  description?: string\n  /** Result group heading, e.g. \"Pages\", \"Articles\". */\n  group?: string\n  tags?: string[]\n  /** Extra hidden terms that should match (synonyms, French labels...). */\n  keywords?: string[]\n}\n\nexport type CaiSiteSearchLabels = {\n  trigger: string\n  placeholder: string\n  empty: string\n  loading: string\n  error: string\n  hint: string\n}\n\nconst DEFAULT_LABELS: CaiSiteSearchLabels = {\n  trigger: \"Search\",\n  placeholder: \"Search pages, articles and guides\",\n  empty: \"No results. Try another word.\",\n  loading: \"Loading…\",\n  error: \"Search is unavailable right now.\",\n  hint: \"Type to search\",\n}\n\nconst normalize = (value: string) =>\n  value\n    .toLowerCase()\n    .normalize(\"NFD\")\n    .replace(/[̀-ͯ]/g, \"\")\n\n/** Scores one item against query tokens; 0 means \"not a match\". */\nexport function scoreSearchItem(item: CaiSearchItem, tokens: string[]): number {\n  if (tokens.length === 0) return 0\n  const title = normalize(item.title)\n  const tags = normalize((item.tags ?? []).join(\" \"))\n  const body = normalize([item.description ?? \"\", ...(item.keywords ?? []), item.href].join(\" \"))\n  let score = 0\n  for (const token of tokens) {\n    let best = 0\n    if (title.startsWith(token)) best = 12\n    else if (new RegExp(`\\\\b${escapeRegExp(token)}`).test(title)) best = 9\n    else if (title.includes(token)) best = 6\n    else if (tags.includes(token)) best = 4\n    else if (body.includes(token)) best = 2\n    if (best === 0) return 0 // every token must match somewhere\n    score += best\n  }\n  return score\n}\n\nfunction escapeRegExp(value: string) {\n  return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\")\n}\n\nexport function searchItems(items: CaiSearchItem[], query: string, limit = 24): CaiSearchItem[] {\n  const tokens = normalize(query).split(/\\s+/).filter(Boolean)\n  return items\n    .map((item, index) => ({ item, index, score: scoreSearchItem(item, tokens) }))\n    .filter((entry) => entry.score > 0)\n    .sort((a, b) => b.score - a.score || a.index - b.index)\n    .slice(0, limit)\n    .map((entry) => entry.item)\n}\n\nfunction Highlight({ text, query }: { text: string; query: string }) {\n  const tokens = normalize(query).split(/\\s+/).filter(Boolean)\n  if (tokens.length === 0) return <>{text}</>\n  // Fold per UTF-16 unit so indices line up with the original text.\n  const folded = Array.from({ length: text.length }, (_, i) => normalize(text[i]).charAt(0) || text[i]).join(\"\")\n  const marks = new Array<boolean>(text.length).fill(false)\n  for (const token of tokens) {\n    let from = 0\n    while (token && (from = folded.indexOf(token, from)) !== -1) {\n      for (let i = from; i < from + token.length; i++) marks[i] = true\n      from += token.length\n    }\n  }\n  const parts: React.ReactNode[] = []\n  let start = 0\n  for (let i = 1; i <= text.length; i++) {\n    if (i === text.length || marks[i] !== marks[start]) {\n      const chunk = text.slice(start, i)\n      parts.push(\n        marks[start] ? (\n          <mark key={start} className=\"bg-transparent text-[#0f7b4e] underline decoration-[#0f7b4e]/40 underline-offset-2 dark:text-[#50856f]\">\n            {chunk}\n          </mark>\n        ) : (\n          chunk\n        ),\n      )\n      start = i\n    }\n  }\n  return <>{parts}</>\n}\n\nfunction SearchIcon({ className }: { className?: string }) {\n  return (\n    <svg aria-hidden viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" className={cn(\"h-3.5 w-3.5\", className)}>\n      <circle cx=\"7\" cy=\"7\" r=\"4.75\" />\n      <path d=\"m10.5 10.5 3.5 3.5\" strokeLinecap=\"square\" />\n    </svg>\n  )\n}\n\nexport function CaiSiteSearch({\n  indexUrl,\n  items: providedItems,\n  trigger = \"icon\",\n  labels: labelOverrides,\n  shortcut = true,\n  className,\n}: {\n  /** JSON endpoint returning CaiSearchItem[] (or { items }). Fetched on first open. */\n  indexUrl?: string\n  /** Static index; used instead of indexUrl when given. */\n  items?: CaiSearchItem[]\n  trigger?: \"icon\" | \"field\"\n  labels?: Partial<CaiSiteSearchLabels>\n  /** Cmd/Ctrl+K and \"/\" open the dialog. Mount one instance with this on per page. */\n  shortcut?: boolean\n  className?: string\n}) {\n  const labels = { ...DEFAULT_LABELS, ...labelOverrides }\n  const router = useRouter()\n  const [open, setOpen] = React.useState(false)\n  const [query, setQuery] = React.useState(\"\")\n  const [active, setActive] = React.useState(0)\n  const [items, setItems] = React.useState<CaiSearchItem[] | null>(providedItems ?? null)\n  const [status, setStatus] = React.useState<\"idle\" | \"loading\" | \"error\">(\"idle\")\n  const triggerRef = React.useRef<HTMLButtonElement>(null)\n  const inputRef = React.useRef<HTMLInputElement>(null)\n  const listId = React.useId()\n  const [isMac, setIsMac] = React.useState(false)\n\n  React.useEffect(() => setIsMac(/Mac|iPhone|iPad/.test(navigator.platform)), [])\n  React.useEffect(() => {\n    if (providedItems) setItems(providedItems)\n  }, [providedItems])\n\n  const close = React.useCallback(() => {\n    setOpen(false)\n    setQuery(\"\")\n    setActive(0)\n    requestAnimationFrame(() => triggerRef.current?.focus())\n  }, [])\n\n  // Lazy index load on first open.\n  React.useEffect(() => {\n    if (!open || items || !indexUrl || status === \"loading\") return\n    setStatus(\"loading\")\n    fetch(indexUrl)\n      .then((response) => (response.ok ? response.json() : Promise.reject(new Error(String(response.status)))))\n      .then((data: CaiSearchItem[] | { items: CaiSearchItem[] }) => {\n        setItems(Array.isArray(data) ? data : data.items)\n        setStatus(\"idle\")\n      })\n      .catch(() => setStatus(\"error\"))\n  }, [open, items, indexUrl, status])\n\n  // Global shortcuts.\n  React.useEffect(() => {\n    if (!shortcut) return\n    const onKey = (event: KeyboardEvent) => {\n      const target = event.target as HTMLElement | null\n      const typing = !!target && (target.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName))\n      if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === \"k\") {\n        event.preventDefault()\n        setOpen((value) => !value)\n      } else if (event.key === \"/\" && !typing && !event.metaKey && !event.ctrlKey && !event.altKey) {\n        event.preventDefault()\n        setOpen(true)\n      }\n    }\n    window.addEventListener(\"keydown\", onKey)\n    return () => window.removeEventListener(\"keydown\", onKey)\n  }, [shortcut])\n\n  // Lock page scroll and focus the input while open.\n  React.useEffect(() => {\n    if (!open) return\n    const previous = document.body.style.overflow\n    document.body.style.overflow = \"hidden\"\n    requestAnimationFrame(() => inputRef.current?.focus())\n    return () => {\n      document.body.style.overflow = previous\n    }\n  }, [open])\n\n  const results = React.useMemo(() => (items && query.trim() ? searchItems(items, query) : []), [items, query])\n  React.useEffect(() => setActive(0), [query])\n\n  const go = (item: CaiSearchItem) => {\n    close()\n    if (/^https?:\\/\\//.test(item.href)) window.location.assign(item.href)\n    else router.push(item.href)\n  }\n\n  const onInputKey = (event: React.KeyboardEvent<HTMLInputElement>) => {\n    if (event.key === \"ArrowDown\") {\n      event.preventDefault()\n      setActive((i) => Math.min(results.length - 1, i + 1))\n    } else if (event.key === \"ArrowUp\") {\n      event.preventDefault()\n      setActive((i) => Math.max(0, i - 1))\n    } else if (event.key === \"Enter\" && results[active]) {\n      event.preventDefault()\n      go(results[active])\n    } else if (event.key === \"Escape\") {\n      event.preventDefault()\n      close()\n    }\n  }\n\n  React.useEffect(() => {\n    document.getElementById(`${listId}-${active}`)?.scrollIntoView({ block: \"nearest\" })\n  }, [active, listId])\n\n  // Group while keeping rank order of first appearance.\n  const groups: Array<{ name: string; entries: Array<{ item: CaiSearchItem; index: number }> }> = []\n  results.forEach((item, index) => {\n    const name = item.group ?? \"\"\n    let group = groups.find((g) => g.name === name)\n    if (!group) groups.push((group = { name, entries: [] }))\n    group.entries.push({ item, index })\n  })\n\n  const shortcutLabel = isMac ? \"⌘K\" : \"Ctrl K\"\n\n  return (\n    <>\n      {trigger === \"icon\" ? (\n        <button\n          ref={triggerRef}\n          type=\"button\"\n          onClick={() => setOpen(true)}\n          aria-label={labels.trigger}\n          aria-haspopup=\"dialog\"\n          data-slot=\"cai-site-search-trigger\"\n          className={cn(\"border border-foreground/20 p-2 text-foreground transition hover:bg-foreground hover:text-background\", className)}\n        >\n          <SearchIcon />\n        </button>\n      ) : (\n        <button\n          ref={triggerRef}\n          type=\"button\"\n          onClick={() => setOpen(true)}\n          aria-haspopup=\"dialog\"\n          data-slot=\"cai-site-search-trigger\"\n          className={cn(\n            \"group flex w-full items-center gap-3 rounded-[2px] border border-foreground/15 bg-background px-3.5 py-2.5 text-left text-sm text-muted-foreground transition-colors hover:border-foreground/40\",\n            className,\n          )}\n        >\n          <SearchIcon className=\"shrink-0\" />\n          <span className=\"flex-1 truncate\">{labels.placeholder}</span>\n          {shortcut ? <kbd className=\"hidden shrink-0 border border-foreground/15 px-1.5 py-0.5 font-mono text-[10px] sm:inline\">{shortcutLabel}</kbd> : null}\n        </button>\n      )}\n\n      {open && typeof document !== \"undefined\"\n        ? createPortal(\n        // Portal to <body>: ancestors with transform/backdrop-filter (e.g. a\n        // blurred sticky header) would otherwise trap the fixed overlay.\n        <div data-slot=\"cai-site-search\" className=\"fixed inset-0 z-[100] flex items-start justify-center px-3 pt-[12vh] sm:px-6\">\n          <div aria-hidden className=\"absolute inset-0 bg-[#161717]/60 backdrop-blur-sm\" onClick={close} />\n          <div\n            role=\"dialog\"\n            aria-modal=\"true\"\n            aria-label={labels.trigger}\n            className=\"relative flex max-h-[72vh] w-full max-w-2xl flex-col overflow-hidden rounded-[4px] border border-foreground/15 bg-background text-foreground shadow-2xl\"\n          >\n            <div className=\"flex items-center gap-3 border-b border-foreground/10 px-4 transition-colors focus-within:border-[#0f7b4e]/60\">\n              <SearchIcon className=\"h-4 w-4 shrink-0 text-muted-foreground\" />\n              <input\n                ref={inputRef}\n                value={query}\n                onChange={(event) => setQuery(event.target.value)}\n                onKeyDown={onInputKey}\n                placeholder={labels.placeholder}\n                role=\"combobox\"\n                aria-expanded={results.length > 0}\n                aria-controls={listId}\n                aria-activedescendant={results[active] ? `${listId}-${active}` : undefined}\n                aria-autocomplete=\"list\"\n                autoComplete=\"off\"\n                spellCheck={false}\n                // Inline so unlayered global :focus-visible rules cannot draw a second box;\n                // the row's emerald bottom border is the focus indicator.\n                style={{ outline: \"none\" }}\n                className=\"h-14 flex-1 bg-transparent text-base outline-none placeholder:text-muted-foreground\"\n              />\n              <button type=\"button\" onClick={close} className=\"border border-foreground/15 px-1.5 py-0.5 font-mono text-[10px] text-muted-foreground hover:text-foreground\">\n                Esc\n              </button>\n            </div>\n\n            <div id={listId} role=\"listbox\" aria-label={labels.trigger} className=\"flex-1 overflow-y-auto overscroll-contain py-2\">\n              {status === \"loading\" && !items ? <p className=\"px-4 py-6 text-sm text-muted-foreground\">{labels.loading}</p> : null}\n              {status === \"error\" ? <p className=\"px-4 py-6 text-sm text-muted-foreground\">{labels.error}</p> : null}\n              {items && !query.trim() ? <p className=\"px-4 py-6 text-sm text-muted-foreground\">{labels.hint}</p> : null}\n              {items && query.trim() && results.length === 0 ? <p className=\"px-4 py-6 text-sm text-muted-foreground\">{labels.empty}</p> : null}\n              {groups.map((group) => (\n                <div key={group.name || \"results\"} role=\"group\" aria-label={group.name || undefined} className=\"pb-2\">\n                  {group.name ? (\n                    <p className=\"px-4 pb-1 pt-3 text-[10px] font-semibold uppercase tracking-[0.24em] text-muted-foreground\">{group.name}</p>\n                  ) : null}\n                  {group.entries.map(({ item, index }) => (\n                    <div\n                      key={`${item.href}-${index}`}\n                      id={`${listId}-${index}`}\n                      role=\"option\"\n                      aria-selected={index === active}\n                      onMouseMove={() => setActive(index)}\n                      onClick={() => go(item)}\n                      className={cn(\n                        \"mx-2 flex cursor-pointer items-start gap-3 rounded-[2px] border-l-2 px-3 py-2.5\",\n                        index === active ? \"border-[#0f7b4e] bg-foreground/[0.06]\" : \"border-transparent\",\n                      )}\n                    >\n                      <div className=\"min-w-0 flex-1\">\n                        <p className=\"truncate text-sm font-medium\">\n                          <Highlight text={item.title} query={query} />\n                        </p>\n                        {item.description ? (\n                          <p className=\"mt-0.5 line-clamp-1 text-xs text-muted-foreground\">\n                            <Highlight text={item.description} query={query} />\n                          </p>\n                        ) : null}\n                      </div>\n                      <span className=\"hidden shrink-0 pt-0.5 font-mono text-[10px] text-muted-foreground/70 sm:block\">{item.href.replace(/^https?:\\/\\/[^/]+/, \"\")}</span>\n                    </div>\n                  ))}\n                </div>\n              ))}\n            </div>\n\n            <div className=\"hidden items-center gap-4 border-t border-foreground/10 px-4 py-2 font-mono text-[10px] text-muted-foreground sm:flex\">\n              <span>↑↓ to move</span>\n              <span>↵ to open</span>\n              <span className=\"ml-auto\">{shortcutLabel}</span>\n            </div>\n          </div>\n        </div>,\n            document.body,\n          )\n        : null}\n    </>\n  )\n}\n",
      "type": "registry:ui"
    }
  ]
}