el.xwx.moe/components/SearchBar.tsx

64 lines
2.0 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-30 05:13:42 -06:00
type Props = {
placeholder?: string;
};
export default function SearchBar({ placeholder }: Props) {
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-11-30 05:13:42 -06:00
className="inline-flex w-fit absolute left-1 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"
2023-11-30 05:13:42 -06:00
placeholder={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-11-30 05:13:42 -06:00
onKeyDown={(e) => {
if (e.key === "Enter") {
if (router.pathname.startsWith("/public")) {
if (!searchQuery) {
return router.push("/public/collections/" + router.query.id);
}
return router.push(
"/public/collections/" +
router.query.id +
"?q=" +
encodeURIComponent(searchQuery || "")
);
} else {
return router.push(
"/search?q=" + encodeURIComponent(searchQuery)
);
}
}
}}
className="border border-neutral-content bg-base-200 focus:border-primary py-1 rounded-md pl-9 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
);
}