54 lines
1.8 KiB
TypeScript
54 lines
1.8 KiB
TypeScript
"use client";
|
|
|
|
import { useState, useRef, useEffect, type ReactNode } from "react";
|
|
|
|
interface NavDropdownProps {
|
|
label: string;
|
|
icon?: string;
|
|
children: ReactNode;
|
|
}
|
|
|
|
export function NavDropdown({ label, icon, children }: NavDropdownProps) {
|
|
const [open, setOpen] = useState(false);
|
|
const ref = useRef<HTMLDivElement>(null);
|
|
|
|
useEffect(() => {
|
|
function handleClick(e: MouseEvent) {
|
|
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
|
|
}
|
|
function handleKey(e: KeyboardEvent) {
|
|
if (e.key === "Escape") setOpen(false);
|
|
}
|
|
if (open) {
|
|
document.addEventListener("mousedown", handleClick);
|
|
document.addEventListener("keydown", handleKey);
|
|
}
|
|
return () => {
|
|
document.removeEventListener("mousedown", handleClick);
|
|
document.removeEventListener("keydown", handleKey);
|
|
};
|
|
}, [open]);
|
|
|
|
return (
|
|
<div ref={ref} className="relative group md:flex">
|
|
<button
|
|
type="button"
|
|
onClick={() => setOpen(!open)}
|
|
onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") setOpen(!open); }}
|
|
className="nav-item cursor-pointer"
|
|
aria-expanded={open}
|
|
aria-haspopup="true"
|
|
>
|
|
{icon ? <img src={icon} alt="" className="w-5 h-5 mr-1.5" /> : null}
|
|
{label}
|
|
<svg className={`ml-auto md:ml-1 w-3 h-3 transition-transform duration-200 ${open ? "rotate-180" : ""}`} fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" /></svg>
|
|
</button>
|
|
{open && (
|
|
<div className="dropdown-menu md:absolute left-0 top-full mt-0.5 min-w-[200px] rounded-xl z-50 py-2" role="menu" onClick={() => setOpen(false)}>
|
|
{children}
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|