import { useEffect, useRef, useState } from "preact/hooks"; import useDebouncedCallback from "@lib/hooks/useDebouncedCallback.ts"; import { IconSearch } from "@components/icons.tsx"; import { useEventListener } from "@lib/hooks/useEventListener.ts"; export const RedirectSearchHandler = () => { useEventListener("keydown", (e: KeyboardEvent) => { if (e?.target?.nodeName == "INPUT") return; if ( e.key === "?" && window.location.search === "" ) { window.location.href += "?q="; } }); return <>; }; const SearchComponent = ( { q, type }: { q: string; type?: string }, ) => { const [searchQuery, setSearchQuery] = useState(q); const [data, setData] = useState([]); const [isLoading, setIsLoading] = useState(false); const inputRef = useRef(null); if ("history" in globalThis) { const u = new URL(window.location.href); if (u.searchParams.get("q") !== searchQuery) { u.searchParams.set("q", searchQuery); window.history.replaceState({}, "", u); } } const fetchData = async (query: string) => { try { setIsLoading(true); const fetchUrl = new URL(window.location.href); fetchUrl.pathname = "/api/resources"; if (searchQuery) { fetchUrl.searchParams.set("q", encodeURIComponent(searchQuery)); } else { return; } if (type) { fetchUrl.searchParams.set("type", type); } const response = await fetch(fetchUrl); const jsonData = await response.json(); setData(jsonData); setIsLoading(false); } catch (error) { console.error("Error fetching data:", error); setIsLoading(false); } }; useEffect(() => { if (inputRef.current && searchQuery?.length === 0) { inputRef.current?.focus(); } }, [inputRef.current, searchQuery]); const debouncedFetchData = useDebouncedCallback(fetchData, 500); // Debounce the fetchData function with a delay of 500ms const handleInputChange = (event: Event) => { const target = event.target as HTMLInputElement; setSearchQuery(target.value); debouncedFetchData(target.value); // Call the debounced fetch function with the updated search query }; return (
{isLoading ?
Loading...
: (
{data.map((d) => (
{JSON.stringify(d.document, null, 2)}
))}
)}
); }; export default SearchComponent;