Files
EpicNext-Cms/src/components/nav-dropdown.tsx
T
openhands 3827f3e686
Deploy / release (push) Skipped
Deploy / deploy (push) Successful in 2m4s
Migrate from framer-motion to motion/react
2026-07-28 18:49:25 +02:00

91 lines
2.1 KiB
TypeScript

"use client";
import { AnimatePresence, motion } from "motion/react";
import Image from "next/image";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { dropdownVariants } from "@/lib/motion";
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 onKeyDown(e: KeyboardEvent) {
if (e.key === "Escape") setOpen(false);
}
if (open) document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
}, [open]);
useEffect(() => {
function onOutsideClick(e: MouseEvent) {
if (ref.current && !ref.current.contains(e.target as Node)) {
setOpen(false);
}
}
if (open) {
document.addEventListener("mousedown", onOutsideClick);
}
return () => document.removeEventListener("mousedown", onOutsideClick);
}, [open]);
return (
<div ref={ref} className="relative">
<button
type="button"
onClick={() => setOpen((o) => !o)}
className="nav-item cursor-pointer"
aria-haspopup="true"
aria-expanded={open}
>
{icon ? (
<Image
src={icon}
alt=""
width={20}
height={20}
className="mr-1.5"
unoptimized
/>
) : null}
{label}
<motion.svg
className="ml-auto md:ml-1 w-3 h-3 shrink-0"
animate={{ rotate: open ? 180 : 0 }}
transition={{ duration: 0.2 }}
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M19 9l-7 7-7-7"
/>
</motion.svg>
</button>
<AnimatePresence>
{open && (
<motion.div
className="dropdown-menu md:absolute left-0 top-full mt-0.5 min-w-0 md:min-w-[200px] rounded-xl z-50 py-2"
role="menu"
variants={dropdownVariants}
initial="hidden"
animate="visible"
exit="exit"
>
{children}
</motion.div>
)}
</AnimatePresence>
</div>
);
}