58 lines
1.7 KiB
TypeScript
58 lines
1.7 KiB
TypeScript
"use client"
|
|
|
|
import { Input } from "@/components/ui/input"
|
|
import { validatePlayer } from "@/lib/hypixel/actions"
|
|
import { cn } from "@/lib/utils"
|
|
import { Search } from "lucide-react"
|
|
import { useRouter } from "next/navigation"
|
|
import { useState } from "react"
|
|
import { toast } from "sonner"
|
|
|
|
export function SearchBar({ navbar }: { navbar?: boolean }) {
|
|
const [input, setInput] = useState("")
|
|
const router = useRouter()
|
|
|
|
async function handleSearch(e: React.FormEvent) {
|
|
e.preventDefault()
|
|
|
|
const validatedPlayer = await validatePlayer(input.trim())
|
|
|
|
if (validatedPlayer.error === true) {
|
|
toast.error(validatedPlayer.message)
|
|
setInput("")
|
|
return
|
|
}
|
|
|
|
if (input.trim()) {
|
|
router.push(`/player/${encodeURIComponent(input.trim())}`)
|
|
}
|
|
if (navbar) {
|
|
setInput("")
|
|
}
|
|
}
|
|
|
|
const handleKeyDown = (e: React.KeyboardEvent) => {
|
|
if (e.key === "Enter") {
|
|
handleSearch(e)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<div className={cn("w-full max-w-4xl px-4", !navbar && "mt-8")}>
|
|
<form onSubmit={handleSearch}>
|
|
<div className="relative">
|
|
<Search className="absolute left-3 top-1/2 w-4 h-4 transform -translate-y-1/2 text-muted-foreground" />
|
|
<Input
|
|
type="text"
|
|
placeholder={!navbar ? "Search for a player..." : ""}
|
|
className="pl-10"
|
|
value={input}
|
|
onChange={(e) => setInput(e.target.value)}
|
|
onKeyDown={handleKeyDown}
|
|
/>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
)
|
|
}
|