import config from "@/config/config.json"; import { humanize, plainify, slugify } from "@/lib/utils/textConverter"; import Fuse from "fuse.js"; import React, { useEffect, useRef, useState } from "react"; import { FaRegFolder, FaRegUserCircle, FaSearch, } from "react-icons/fa/index.js"; const { summary_length, blog_folder } = config.settings; export type SearchItem = { slug: string; data: any; content: any; }; interface Props { searchList: SearchItem[]; } interface SearchResult { item: SearchItem; refIndex: number; } const Search = ({ searchList }: Props) => { const inputRef = useRef(null); const [inputVal, setInputVal] = useState(""); const [searchResults, setSearchResults] = useState([]); const handleChange = (e: React.FormEvent) => { setInputVal(e.currentTarget.value); }; const fuse = new Fuse(searchList, { keys: ["data.title", "data.categories", "data.tags"], includeMatches: true, minMatchCharLength: 3, threshold: 0.5, }); useEffect(() => { const searchUrl = new URLSearchParams(window.location.search); const searchStr = searchUrl.get("q"); if (searchStr) setInputVal(searchStr); setTimeout(function () { inputRef.current!.selectionStart = inputRef.current!.selectionEnd = searchStr?.length || 0; }, 50); }, []); useEffect(() => { let inputResult = inputVal.length > 2 ? fuse.search(inputVal) : []; setSearchResults(inputResult); if (inputVal.length > 0) { const searchParams = new URLSearchParams(window.location.search); searchParams.set("q", inputVal); const newRelativePathQuery = window.location.pathname + "?" + searchParams.toString(); history.pushState(null, "", newRelativePathQuery); } else { history.pushState(null, "", window.location.pathname); } }, [inputVal]); return (
{/* {inputVal.length > 1 && (
Found {searchResults?.length} {searchResults?.length && searchResults?.length === 1 ? " result" : " results"}{" "} for '{inputVal}'
)} */}
{searchResults?.length < 1 ? (
no-search-found

{inputVal.length < 1 ? "Search Post Here" : "No Search Found!"}

{inputVal.length < 1 ? "Search for posts by title, category, or tag." : "We couldn't find what you searched for. Try searching again."}

) : ( searchResults?.map(({ item }, index) => (
{item.data.image && ( {item.data.title} )}

{item.data.title}

{plainify(item.content?.slice(0, Number(summary_length)))}

read more
)) )}
); }; export default Search;