import { useState, useRef, useEffect } from "react"; import { Search } from "lucide-react"; // ---------------------- // Main Component // ---------------------- const HeaderSearch = () => { // ---------------------- // State & Refs // ---------------------- // Desktop-only state/refs (mobile search is always open) const [isOpen, setIsOpen] = useState(false); const inputRef = useRef(null); // ---------------------- // Auto-focus desktop input when search opens // ---------------------- useEffect(() => { if (isOpen && inputRef.current) inputRef.current.focus(); }, [isOpen]); // ---------------------- // Close desktop search on outside click // ---------------------- useEffect(() => { const handleClickOutside = (e: MouseEvent) => { if (!inputRef.current) return; const form = inputRef.current.closest("form"); if (form && !form.contains(e.target as Node)) setIsOpen(false); }; document.addEventListener("mousedown", handleClickOutside); return () => document.removeEventListener("mousedown", handleClickOutside); }, []); // ---------------------- // Keyboard Shortcut: Cmd/Ctrl + K opens search // ---------------------- useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { const isMac = /Mac|iPod|iPhone|iPad/.test(navigator.platform); const isShortcut = (isMac && e.metaKey && e.key === "k") || (!isMac && e.ctrlKey && e.key === "k"); if (isShortcut) { e.preventDefault(); setIsOpen(true); } }; window.addEventListener("keydown", handleKeyDown); return () => window.removeEventListener("keydown", handleKeyDown); }, []); // ---------------------- // Render Component // ---------------------- return (
{/* ========================================================= MOBILE SEARCH BAR - Always open - Full width - Visible only on small screens ( {/* ========================================================= DESKTOP SEARCH BAR - Toggleable open/close - Hidden on mobile ( {/* INPUT FIELD: - Fades and expands in when open - Invisible and width=0 when closed WIDTH TUNING: - Adjust "w-[200px]" in the parent for the expanded width. - You can also tweak transition speed via `duration-300`. */} {/* SEARCH ICON BUTTON: - Acts as toggle when closed - Submits form when open ANIMATION TIPS: - Add slight rotation or color transition: e.g. `transition-transform duration-200 hover:scale-110` */}
); }; // ---------------------- // Export Component // ---------------------- export default HeaderSearch;