Files
craft2prints/src/components/NavDropdown.tsx
T

85 lines
2.7 KiB
TypeScript

'use client';
import Link from 'next/link';
import { useEffect, useRef, useState } from 'react';
type NavLink = { href: string; label: string };
type NavSection = { title: string; links: NavLink[] };
export default function NavDropdown({
label,
links,
sections,
}: {
label: string;
links?: NavLink[];
sections?: NavSection[];
}) {
const [open, setOpen] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const onClickOutside = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
};
document.addEventListener('mousedown', onClickOutside);
return () => document.removeEventListener('mousedown', onClickOutside);
}, []);
return (
<div ref={ref} className="relative">
<button
onClick={() => setOpen((o) => !o)}
aria-expanded={open}
className="tag-label flex items-center gap-1 hover:text-ink"
>
{label}
<span className={`inline-block transition-transform ${open ? 'rotate-180' : ''}`}></span>
</button>
{open && (
<div className="absolute left-0 top-full mt-2 w-52 border border-line bg-paper shadow-sm">
{sections ? (
sections.every((s) => s.links.length === 0) ? (
<p className="px-4 py-3 text-sm text-muted">Coming soon.</p>
) : (
<div className="divide-y divide-line">
{sections
.filter((s) => s.links.length > 0)
.map((section) => (
<div key={section.title} className="py-1">
<p className="px-4 pt-2 text-xs font-medium uppercase tracking-wide text-muted">{section.title}</p>
{section.links.map((link) => (
<Link
key={link.href + link.label}
href={link.href}
onClick={() => setOpen(false)}
className="block px-4 py-2.5 text-sm hover:bg-surface"
>
{link.label}
</Link>
))}
</div>
))}
</div>
)
) : links && links.length > 0 ? (
links.map((link) => (
<Link
key={link.href + link.label}
href={link.href}
onClick={() => setOpen(false)}
className="block px-4 py-3 text-sm hover:bg-surface"
>
{link.label}
</Link>
))
) : (
<p className="px-4 py-3 text-sm text-muted">Coming soon.</p>
)}
</div>
)}
</div>
);
}