el.xwx.moe/components/SearchBar.tsx

44 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-05-08 09:35:39 -05:00
import { faMagnifyingGlass } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
2023-06-05 11:18:54 -05:00
import { useState } from "react";
2023-05-08 09:35:39 -05:00
import { useRouter } from "next/router";
import { toast } from "react-hot-toast";
2023-05-08 09:35:39 -05:00
2023-11-16 02:22:16 -06:00
export default function SearchBar() {
2023-05-08 09:35:39 -05:00
const router = useRouter();
2023-11-16 02:22:16 -06:00
const routeQuery = router.query.q;
2023-05-08 09:35:39 -05:00
2023-06-05 11:18:54 -05:00
const [searchQuery, setSearchQuery] = useState(
routeQuery ? decodeURIComponent(routeQuery as string) : ""
);
2023-05-08 09:35:39 -05:00
return (
2023-11-16 02:22:16 -06:00
<div className="flex items-center relative group">
2023-05-15 21:13:59 -05:00
<label
htmlFor="search-box"
2023-08-30 23:17:27 -05:00
className="inline-flex w-fit absolute left-2 pointer-events-none rounded-md p-1 text-sky-500 dark:text-sky-500"
2023-05-08 09:35:39 -05:00
>
2023-05-15 21:13:59 -05:00
<FontAwesomeIcon icon={faMagnifyingGlass} className="w-5 h-5" />
</label>
2023-05-08 09:35:39 -05:00
2023-05-15 21:13:59 -05:00
<input
id="search-box"
type="text"
placeholder="Search for Links"
2023-06-05 11:18:54 -05:00
value={searchQuery}
2023-05-15 21:13:59 -05:00
onChange={(e) => {
2023-06-07 14:34:50 -05:00
e.target.value.includes("%") &&
toast.error("The search query should not contain '%'.");
2023-06-05 11:18:54 -05:00
setSearchQuery(e.target.value.replace("%", ""));
2023-05-15 21:13:59 -05:00
}}
2023-06-05 11:18:54 -05:00
onKeyDown={(e) =>
e.key === "Enter" &&
router.push("/search?q=" + encodeURIComponent(searchQuery))
2023-06-05 11:18:54 -05:00
}
2023-08-30 23:00:57 -05:00
className="border border-sky-100 bg-gray-50 dark:border-neutral-700 focus:border-sky-300 dark:focus:border-sky-600 rounded-md pl-10 py-2 pr-2 w-44 sm:w-60 dark:hover:border-neutral-600 md:focus:w-80 hover:border-sky-300 duration-100 outline-none dark:bg-neutral-800"
2023-05-15 21:13:59 -05:00
/>
</div>
2023-05-08 09:35:39 -05:00
);
}