"use client"; /* eslint-disable @next/next/no-img-element */ import { useEffect, useRef, useState, type FormEvent } from "react"; import { useRouter } from "next/navigation"; import Icon from "@/components/Icon"; import { FoxMark } from "@/components/Logo"; import type { SearchTab } from "@/lib/types"; import { cn } from "@/lib/utils"; export default function SearchBar({ initial = "", tab = "all", compact = false, autoFocus = false, className, }: { initial?: string; /** A new query stays on the tab the user is already looking at. */ tab?: SearchTab; compact?: boolean; autoFocus?: boolean; className?: string; }) { const router = useRouter(); const [value, setValue] = useState(initial); const inputRef = useRef(null); useEffect(() => { setValue(initial); }, [initial]); useEffect(() => { if (autoFocus) inputRef.current?.focus(); }, [autoFocus]); useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.key !== "/" || e.metaKey || e.ctrlKey || e.altKey) return; const el = document.activeElement as HTMLElement | null; if ( el && (el.tagName === "INPUT" || el.tagName === "TEXTAREA" || el.tagName === "SELECT" || el.isContentEditable) ) { return; } e.preventDefault(); inputRef.current?.focus(); inputRef.current?.select(); }; window.addEventListener("keydown", onKey); return () => window.removeEventListener("keydown", onKey); }, []); const runSearch = (targetTab: SearchTab = tab) => { const q = value.replace(/\s+/g, " ").trim(); if (!q) return; inputRef.current?.blur(); router.push(`/search?q=${encodeURIComponent(q)}&tab=${targetTab}`); }; const submit = (e: FormEvent) => { e.preventDefault(); runSearch(tab); }; return (
{!compact && ( )} setValue(e.target.value)} placeholder={compact ? "Search Fox or type a query…" : "Ask anything, find anything..."} aria-label="Search query" dir="auto" type="search" enterKeyHint="search" autoComplete="off" autoCapitalize="off" spellCheck={false} maxLength={200} className={cn( "w-full min-w-0 flex-1 appearance-none bg-transparent text-slate-900 placeholder:text-slate-400 focus:outline-none dark:text-[#e8eaed] dark:placeholder:text-[#7f8694] [&::-webkit-search-cancel-button]:hidden", compact ? "text-[15px]" : "text-[15px] sm:text-base", )} /> {value && ( )} {compact ? (
) : ( )} ); }