From 33bab9c489d74e1b53109d5f1e8f3586cfcb9433 Mon Sep 17 00:00:00 2001 From: Sat Naing Date: Thu, 29 Sep 2022 11:29:37 +0630 Subject: [PATCH] Update search functionality - dynamic url update, auto focus --- src/components/Search.tsx | 30 +++++++++++++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/src/components/Search.tsx b/src/components/Search.tsx index 1b152f6..7c73a61 100644 --- a/src/components/Search.tsx +++ b/src/components/Search.tsx @@ -1,6 +1,6 @@ // import type React from "react"; import Fuse from "fuse.js"; -import { useEffect, useState } from "react"; +import { useEffect, useRef, useState } from "react"; import Card from "@components/Card"; import slugify from "@utils/slugify"; import type { Frontmatter } from "src/types"; @@ -22,6 +22,7 @@ interface SearchResult { } export default function SearchBar({ searchList }: Props) { + const inputRef = useRef(null); const [inputVal, setInputVal] = useState(""); const [searchResults, setSearchResults] = useState( null @@ -38,8 +39,33 @@ export default function SearchBar({ searchList }: Props) { threshold: 0.5, }); + useEffect(() => { + // if URL has search query, + // insert that search query in input field + const searchUrl = new URLSearchParams(window.location.search); + const searchStr = searchUrl.get("q"); + if (searchStr) setInputVal(searchStr); + + // put focus cursor at the end of the string + setTimeout(function () { + inputRef.current!.selectionStart = inputRef.current!.selectionEnd = + searchStr?.length || 0; + }, 50); + }, []); + useEffect(() => { setSearchResults(fuse!.search!(inputVal!)); + + // Update search string in URL + 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 ( @@ -62,6 +88,8 @@ export default function SearchBar({ searchList }: Props) { defaultValue={inputVal} onChange={handleChange} autoComplete="off" + autoFocus + ref={inputRef} />