Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 21x 13x 13x 13x 13x 8x 8x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 8x 8x 8x 8x 39x 39x 39x 39x 11x 11x 11x 11x 39x 39x 39x 39x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 11x 11x 39x 39x 39x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 39x 39x 39x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 39x 39x 39x 1x 1x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 39x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 3x 3x 3x 3x 39x 39x 39x 39x | "use client";
import { useState, useEffect, useRef } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import styles from "./SearchBar.module.css";
import { clientLogger } from "@/lib/logging/clientLogger";
import { eventTracking } from "@/lib/event-tracking";
import { Icon } from "@/components/ui/icons";
import { Button } from "@/components/ui";
import { SearchBarProps } from "@/types/shop";
import { useFunnelSteps } from "@/hooks/useFunnelTracking";
export function SearchBar({ onSearch, placeholder = "Search products..." }: SearchBarProps) {
const router = useRouter();
const searchParams = useSearchParams();
const [query, setQuery] = useState(searchParams.get("query") || "");
const [suggestions, setSuggestions] = useState<string[]>([]);
const [showSuggestions, setShowSuggestions] = useState(false);
const [loading, setLoading] = useState(false);
const [selectedIndex, setSelectedIndex] = useState(-1);
const suggestionsRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const { trackStep } = useFunnelSteps();
// Fetch suggestions as user types
useEffect(() => {
if (query.length < 2) {
setSuggestions([]);
setSelectedIndex(-1);
return;
}
const fetchSuggestions = async () => {
try {
setLoading(true);
const response = await fetch(
`/api/products/search/suggestions?query=${encodeURIComponent(query)}&limit=10`
);
const data = await response.json();
if (data.success) {
setSuggestions(data.data);
setShowSuggestions(true);
setSelectedIndex(-1); // Reset selection when suggestions change
}
} catch (error) {
clientLogger.error("Failed to fetch suggestions", error instanceof Error ? error : new Error(String(error)));
} finally {
setLoading(false);
}
};
const debounceTimer = setTimeout(fetchSuggestions, 300);
return () => clearTimeout(debounceTimer);
}, [query]);
// Close suggestions when clicking outside
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (
suggestionsRef.current &&
!suggestionsRef.current.contains(event.target as Node) &&
inputRef.current &&
!inputRef.current.contains(event.target as Node)
) {
setShowSuggestions(false);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
// Keyboard shortcut: "/" to focus search
useEffect(() => {
function handleKeyPress(event: KeyboardEvent) {
// Only trigger if not already focused on an input/textarea
if (
event.key === "/" &&
document.activeElement?.tagName !== "INPUT" &&
document.activeElement?.tagName !== "TEXTAREA"
) {
event.preventDefault();
inputRef.current?.focus();
}
// ESC to clear search and close suggestions
if (event.key === "Escape" && inputRef.current === document.activeElement) {
setQuery("");
setShowSuggestions(false);
inputRef.current?.blur();
}
}
document.addEventListener("keydown", handleKeyPress);
return () => document.removeEventListener("keydown", handleKeyPress);
}, []);
const handleSearch = (searchQuery: string) => {
if (!searchQuery.trim()) {
return;
}
const params = new URLSearchParams();
params.append("query", searchQuery);
// Preserve other filters
const categories = searchParams.get("categories");
const minPrice = searchParams.get("minPrice");
const maxPrice = searchParams.get("maxPrice");
const sortBy = searchParams.get("sortBy");
if (categories) params.append("categories", categories);
if (minPrice) params.append("minPrice", minPrice);
if (maxPrice) params.append("maxPrice", maxPrice);
if (sortBy) params.append("sortBy", sortBy);
router.push(`/shop?${params.toString()}`);
setShowSuggestions(false);
onSearch?.(searchQuery);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const searchQuery = selectedIndex >= 0 && suggestions[selectedIndex] ? suggestions[selectedIndex] : query;
// Track search event (legacy)
eventTracking.search(searchQuery, 0);
// Track search for product discovery funnel
trackStep('productDiscovery', 'search', {
search_query: searchQuery});
if (selectedIndex >= 0 && suggestions[selectedIndex]) {
handleSearch(suggestions[selectedIndex]);
} else {
handleSearch(query);
}
};
const handleSuggestionClick = (suggestion: string) => {
setQuery(suggestion);
handleSearch(suggestion);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
if (!showSuggestions || suggestions.length === 0) return;
switch (e.key) {
case "ArrowDown":
e.preventDefault();
setSelectedIndex((prev) => (prev < suggestions.length - 1 ? prev + 1 : prev));
break;
case "ArrowUp":
e.preventDefault();
setSelectedIndex((prev) => (prev > 0 ? prev - 1 : -1));
break;
case "Escape":
setShowSuggestions(false);
setSelectedIndex(-1);
break;
case "Enter":
if (selectedIndex >= 0) {
e.preventDefault();
handleSuggestionClick(suggestions[selectedIndex]);
}
break;
}
};
return (
<div className={styles.searchContainer}>
<form onSubmit={handleSubmit} className={styles.searchForm} role="search">
<input
ref={inputRef}
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
onFocus={() => suggestions.length > 0 && setShowSuggestions(true)}
onKeyDown={handleKeyDown}
placeholder={placeholder}
className={styles.searchInput}
autoComplete="off"
aria-label="Search products"
aria-autocomplete="list"
aria-controls={showSuggestions && suggestions.length > 0 ? "search-suggestions" : undefined}
aria-activedescendant={selectedIndex >= 0 ? `suggestion-${selectedIndex}` : undefined}
role="combobox"
aria-expanded={showSuggestions && suggestions.length > 0}
/>
<Button type="submit" variant="ghost" size="sm" className={styles.searchButton} aria-label="Search">
<Icon name="search" size={20} />
</Button>
</form>
{/* Suggestions Dropdown */}
{showSuggestions && suggestions.length > 0 && (
<div
ref={suggestionsRef}
id="search-suggestions"
role="listbox"
className={styles.suggestions}
aria-label="Search suggestions"
>
{loading && <div className={styles.loadingText} role="status">Loading...</div>}
{!loading && (
<>
{suggestions.map((suggestion, index) => (
<Button
key={index}
id={`suggestion-${index}`}
onClick={() => handleSuggestionClick(suggestion)}
variant="ghost"
size="sm"
className={`${styles.suggestionItem} ${index === selectedIndex ? styles.suggestionSelected : ""}`}
type="button"
role="option"
aria-selected={index === selectedIndex}
onMouseEnter={() => setSelectedIndex(index)}
>
<Icon name="search" size={16} aria-hidden="true" />
<span>{suggestion}</span>
</Button>
))}
</>
)}
</div>
)}
</div>
);
}
|