"use client" import React, { FormEvent, useCallback, useEffect, useRef, useState } from "react" import { ChevronDownIcon, ChevronRightIcon } from "@heroicons/react/24/outline" // Assuming usage of Heroicons for icons import { flushSync } from "react-dom" import Link from "next/link" import { usePathname, useSearchParams, useRouter } from "next/navigation" import { formatDate, getResults } from "@/utils" type Props = { } const SearchBar = ({ }: Props) => { const searchParams = useSearchParams() const router = useRouter() const pathname = usePathname() const [query, setQuery] = useState(searchParams.get("q") ?? "") const inputRef = useRef() const [isLoading, setIsLoading] = useState(false) const [activeInput, setActiveInput] = useState(true) const [dirtyInput, setDirtyInput] = useState(false) const [results, setResults] = useState([]) const handleSearch = useCallback( async (event?: FormEvent) => { event?.preventDefault() setIsLoading(true) const newSearchParams = new URLSearchParams(searchParams) if (query) { newSearchParams.set("q", query) } else { newSearchParams.delete("q") } router.push(`${pathname}?${newSearchParams}`) // Perform search and update results state // Assume fetchResults is a function that fetches search results // const searchResults = await fetchResults(query); // Mock the search results const searchResults = await getResults({ query }) setResults(searchResults) setIsLoading(false) setActiveInput(false) }, [ query, setResults, setIsLoading, setActiveInput, searchParams, router, pathname ] ) const isActive = results.length > 0 || dirtyInput useEffect(() => { if (!dirtyInput && searchParams.get("q") && searchParams.get("q") !== "") { handleSearch() } }, []) return (
{isLoading || isActive ? ( Searching for ) : null} {activeInput ? (
{isActive ? ( {'"'} ) : ( "" )} { if (element) { inputRef.current = element } }} className={`flex-grow inline bg-transparent text-white placeholder-gray-400 outline-none ring-none ${ isActive ? `text-blue-300 p-0 underline underline-offset-4` : "w-full p-2" }`} placeholder={ isActive ? "Search for web3 news from the community" : undefined } value={query} size={query ? query.length : 1} style={ query ? { width: `calc(${query.length}ch+2px)` } : undefined } onChange={(e) => { if(!dirtyInput) { setDirtyInput(true); } setQuery(e.target.value) }} /> {isActive ? ( {'"'} ) : ( "" )}
) : ( { flushSync(() => { setActiveInput(true) }) inputRef.current?.focus() }} > {'"'} {query} {'"'} )} {isLoading ? ( // Shadcn Loading component placeholder ) : (
{/* Dropdown component should be here */}
All Sites
{/* Dropdown component should be here */}
All Times
)} {results.length > 0 && ( <>
{results.map((item) => ( {formatDate(item.timestamp)}

{item.title}

))} )}
) } // Placeholder components for Shadcn const LoadingComponent = () => { // Replace with actual Shadcn Loading component return
Loading...
} export default SearchBar