Skip to content

Commit

Permalink
Update search functionality - dynamic url update, auto focus
Browse files Browse the repository at this point in the history
  • Loading branch information
satnaing committed Sep 29, 2022
1 parent 18e920d commit 33bab9c
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion src/components/Search.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -22,6 +22,7 @@ interface SearchResult {
}

export default function SearchBar({ searchList }: Props) {
const inputRef = useRef<HTMLInputElement>(null);
const [inputVal, setInputVal] = useState("");
const [searchResults, setSearchResults] = useState<SearchResult[] | null>(
null
Expand All @@ -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 (
Expand All @@ -62,6 +88,8 @@ export default function SearchBar({ searchList }: Props) {
defaultValue={inputVal}
onChange={handleChange}
autoComplete="off"
autoFocus
ref={inputRef}
/>
</label>

Expand Down

0 comments on commit 33bab9c

Please sign in to comment.