"use client"; import { useCallback, useEffect, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog"; import { cn } from "@/lib/utils"; type SearchResult = { title: string; href: string; snippet: string; }; function subscribeToKeyboard(callback: () => void) { const handler = (e: KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && e.key === "k") { e.preventDefault(); callback(); } }; document.addEventListener("keydown", handler); return () => document.removeEventListener("keydown", handler); } export function Search() { const router = useRouter(); const [open, setOpen] = useState(false); const [query, setQuery] = useState(""); const [results, setResults] = useState([]); const [resolvedQuery, setResolvedQuery] = useState(""); const [activeIndex, setActiveIndex] = useState(0); const inputRef = useRef(null); const listRef = useRef(null); const abortRef = useRef(null); useEffect( () => subscribeToKeyboard(() => setOpen((previous) => !previous)), [], ); const navigate = useCallback( (href: string) => { setOpen(false); setQuery(""); setResults([]); router.push(href); }, [router], ); const openDialog = useCallback(() => { setOpen(true); setTimeout(() => inputRef.current?.focus(), 0); }, []); const handleOpenChange = useCallback((next: boolean) => { setOpen(next); if (next) { setTimeout(() => inputRef.current?.focus(), 0); } else { setQuery(""); setResults([]); } }, []); // Debounced search — genuinely async with abort; useEffect is appropriate here useEffect(() => { const q = query.trim(); if (!q) { return; } abortRef.current?.abort(); const controller = new AbortController(); abortRef.current = controller; const timeout = setTimeout(async () => { try { const res = await fetch(`/api/search?q=${encodeURIComponent(q)}`, { signal: controller.signal, }); if (res.ok) { const data = await res.json(); setResults(data.results); setActiveIndex(0); } else { setResults([]); } } catch { if (!controller.signal.aborted) { setResults([]); } } finally { if (!controller.signal.aborted) { setResolvedQuery(q); } } }, 150); return () => { clearTimeout(timeout); controller.abort(); }; }, [query]); function scrollActiveIntoView() { requestAnimationFrame(() => { const active = listRef.current?.querySelector("[data-active='true']"); active?.scrollIntoView({ block: "nearest" }); }); } function handleKeyDown(e: React.KeyboardEvent) { // Ignore keys that confirm an IME composition (e.g. Enter selecting a candidate). if (e.nativeEvent.isComposing || e.keyCode === 229) { return; } if (e.key === "ArrowDown") { e.preventDefault(); if (results.length > 0) { setActiveIndex((i) => Math.min(i + 1, results.length - 1)); scrollActiveIntoView(); } } else if (e.key === "ArrowUp") { e.preventDefault(); if (results.length > 0) { setActiveIndex((i) => Math.max(i - 1, 0)); scrollActiveIntoView(); } } else if (e.key === "Enter" && results[activeIndex]) { e.preventDefault(); navigate(results[activeIndex].href); } } const normalizedQuery = query.trim(); const hasQuery = normalizedQuery.length > 0; const loading = hasQuery && resolvedQuery !== normalizedQuery; return ( <> Search documentation
{ setQuery(e.target.value); setResolvedQuery(""); }} onKeyDown={handleKeyDown} placeholder="Search docs..." aria-label="Search docs" className="flex-1 bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground" /> {query && ( )}
{loading && hasQuery ? (
) : hasQuery && results.length === 0 ? (

No results found.

) : !hasQuery ? (

Type to search documentation...

) : ( results.map((item, i) => ( )) )}
); }