'use client'; import { useState, useEffect, useRef, useCallback } from 'react'; import { useRouter } from 'next/navigation'; import Image from 'next/image'; import api from '@/services/api'; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- interface UserSuggestion { id: string; username: string; displayName: string; avatarUrl: string | null; } interface RepoSuggestion { id: string; fullName: string; description: string | null; stars: number; } interface SuggestionsResponse { users: UserSuggestion[]; repos: RepoSuggestion[]; } type SuggestionItem = | { kind: 'recent'; query: string } | { kind: 'user'; user: UserSuggestion } | { kind: 'repo'; repo: RepoSuggestion } | { kind: 'search'; query: string }; interface SearchBarProps { placeholder?: string; className?: string; autoFocus?: boolean; } // --------------------------------------------------------------------------- // Constants // --------------------------------------------------------------------------- const RECENT_SEARCHES_KEY = 'gitgram:recentSearches'; const MAX_RECENT = 5; const DEBOUNCE_MS = 200; // --------------------------------------------------------------------------- // Local-storage helpers (immutable read/write) // --------------------------------------------------------------------------- function getRecentSearches(): string[] { if (typeof window === 'undefined') return []; try { const raw = localStorage.getItem(RECENT_SEARCHES_KEY); return raw ? (JSON.parse(raw) as string[]) : []; } catch { return []; } } function saveRecentSearch(query: string): void { if (typeof window === 'undefined') return; const trimmed = query.trim(); if (!trimmed) return; const prev = getRecentSearches().filter((q) => q !== trimmed); const next = [trimmed, ...prev].slice(0, MAX_RECENT); localStorage.setItem(RECENT_SEARCHES_KEY, JSON.stringify(next)); } // --------------------------------------------------------------------------- // Component // --------------------------------------------------------------------------- export default function SearchBar({ placeholder = 'Search...', className = '', autoFocus = false }: SearchBarProps) { const router = useRouter(); const [query, setQuery] = useState(''); const [isOpen, setIsOpen] = useState(false); const [isFocused, setIsFocused] = useState(false); const [suggestions, setSuggestions] = useState(null); const [activeIndex, setActiveIndex] = useState(-1); const inputRef = useRef(null); const containerRef = useRef(null); const debounceTimer = useRef | null>(null); const abortControllerRef = useRef(null); // --------------------------------------------------------------------------- // Derived list of items shown in the dropdown // --------------------------------------------------------------------------- const buildItems = useCallback((): SuggestionItem[] => { const items: SuggestionItem[] = []; if (!query.trim()) { // Show recent searches when input is empty getRecentSearches().forEach((q) => items.push({ kind: 'recent', query: q })); } else { // Quick user results (suggestions?.users ?? []).slice(0, 3).forEach((user) => items.push({ kind: 'user', user }) ); // Quick repo results (suggestions?.repos ?? []).slice(0, 3).forEach((repo) => items.push({ kind: 'repo', repo }) ); // "Search for '…'" always last items.push({ kind: 'search', query: query.trim() }); } return items; }, [query, suggestions]); const items = buildItems(); // --------------------------------------------------------------------------- // Fetch suggestions (debounced) // --------------------------------------------------------------------------- useEffect(() => { if (debounceTimer.current) clearTimeout(debounceTimer.current); if (abortControllerRef.current) abortControllerRef.current.abort(); if (!query.trim()) { setSuggestions(null); return; } debounceTimer.current = setTimeout(async () => { const controller = new AbortController(); abortControllerRef.current = controller; try { const response = await api.get('/search/suggestions', { params: { q: query.trim() }, signal: controller.signal, }); setSuggestions(response.data); } catch (err: unknown) { // Silently ignore aborted requests if (err instanceof Error && err.name !== 'CanceledError' && err.name !== 'AbortError') { setSuggestions(null); } } }, DEBOUNCE_MS); return () => { if (debounceTimer.current) clearTimeout(debounceTimer.current); }; }, [query]); // Reset active index whenever items change useEffect(() => { setActiveIndex(-1); }, [items.length, query]); // --------------------------------------------------------------------------- // Click-outside to close // --------------------------------------------------------------------------- useEffect(() => { function handlePointerDown(e: PointerEvent) { if (containerRef.current && !containerRef.current.contains(e.target as Node)) { setIsOpen(false); } } document.addEventListener('pointerdown', handlePointerDown); return () => document.removeEventListener('pointerdown', handlePointerDown); }, []); // --------------------------------------------------------------------------- // Navigation helpers // --------------------------------------------------------------------------- function navigateToSearch(q: string) { if (!q.trim()) return; saveRecentSearch(q); router.push(`/search?q=${encodeURIComponent(q.trim())}`); setIsOpen(false); setQuery(''); } function activateItem(item: SuggestionItem) { switch (item.kind) { case 'recent': case 'search': navigateToSearch(item.query); break; case 'user': saveRecentSearch(item.user.username); router.push(`/${item.user.username}`); setIsOpen(false); setQuery(''); break; case 'repo': saveRecentSearch(item.repo.fullName); router.push(`/${item.repo.fullName}`); setIsOpen(false); setQuery(''); break; } } // --------------------------------------------------------------------------- // Event handlers // --------------------------------------------------------------------------- function handleKeyDown(e: React.KeyboardEvent) { if (!isOpen) return; switch (e.key) { case 'ArrowDown': e.preventDefault(); setActiveIndex((prev) => Math.min(prev + 1, items.length - 1)); break; case 'ArrowUp': e.preventDefault(); setActiveIndex((prev) => Math.max(prev - 1, -1)); break; case 'Enter': e.preventDefault(); if (activeIndex >= 0 && activeIndex < items.length) { activateItem(items[activeIndex]); } else { navigateToSearch(query); } break; case 'Escape': setIsOpen(false); inputRef.current?.blur(); break; } } function handleChange(e: React.ChangeEvent) { setQuery(e.target.value); setIsOpen(true); } function handleFocus() { setIsFocused(true); setIsOpen(true); } function handleBlur() { setIsFocused(false); } function handleClear() { setQuery(''); setSuggestions(null); inputRef.current?.focus(); } // --------------------------------------------------------------------------- // Render helpers // --------------------------------------------------------------------------- function formatStars(n: number): string { if (n >= 1000) return `${(n / 1000).toFixed(1)}k`; return String(n); } const showDropdown = isOpen && (items.length > 0); return (
{/* Input row */}
{/* Search icon */} = 0 ? `suggestion-${activeIndex}` : undefined} autoFocus={autoFocus} value={query} onChange={handleChange} onFocus={handleFocus} onBlur={handleBlur} onKeyDown={handleKeyDown} placeholder={placeholder} className="w-full pl-9 pr-8 py-2 rounded-lg border border-gray-200 dark:border-gray-600 bg-gray-50 dark:bg-gray-700 text-sm text-gray-900 dark:text-gray-100 placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent transition" /> {/* Clear button */} {query && ( )}
{/* Dropdown */} {showDropdown && (
    {/* Section label: recent searches */} {!query.trim() && items.length > 0 && (
  • Recent searches
  • )} {/* Section labels for query results */} {query.trim() && suggestions?.users && suggestions.users.length > 0 && (
  • Users
  • )} {items.map((item, idx) => { const isActive = idx === activeIndex; const baseClasses = `flex items-center gap-3 px-3 py-2 cursor-pointer text-sm transition-colors ${ isActive ? 'bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300' : 'hover:bg-gray-50 dark:hover:bg-gray-700 text-gray-800 dark:text-gray-200' }`; // Insert repos section label before first repo item const prevItem = items[idx - 1]; const isFirstRepo = item.kind === 'repo' && prevItem?.kind !== 'repo'; const isFirstUser = item.kind === 'user' && prevItem?.kind !== 'user'; return ( <> {isFirstUser && query.trim() && ( null /* label already rendered above */ )} {isFirstRepo && (
  • Repositories
  • )}
  • { // Use pointerdown so we fire before the input blur e.preventDefault(); activateItem(item); }} > {item.kind === 'recent' && ( <> {item.query} )} {item.kind === 'user' && ( <> {item.user.avatarUrl ? ( {item.user.username} ) : ( {item.user.username[0]?.toUpperCase() ?? '?'} )} {item.user.username} {item.user.displayName && item.user.displayName !== item.user.username && ( {item.user.displayName} )} )} {item.kind === 'repo' && ( <> {item.repo.fullName} {formatStars(item.repo.stars)} )} {item.kind === 'search' && ( <> Search for{' '} “{item.query}” )}
  • ); })}
)}
); }