el.xwx.moe/components/SearchBar.tsx

44 lines
1.4 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"
className="inline-flex w-fit absolute left-2 pointer-events-none rounded-md p-1 text-primary"
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-11-27 15:38:38 -06:00
className="border border-neutral-content bg-base-200 focus:border-primary py-2 rounded-md pl-10 pr-2 w-44 sm:w-60 md:focus:w-80 duration-100 outline-none"
2023-05-15 21:13:59 -05:00
/>
</div>
2023-05-08 09:35:39 -05:00
);
}