'use client'; import { useEffect, useRef } from 'react'; interface DropdownItem { label: string; href: string; } interface DropdownMenuProps { items: DropdownItem[]; onClose: () => void; } export function DropdownMenu({ items, onClose }: DropdownMenuProps) { const menuRef = useRef(null); // Handle keyboard navigation within dropdown useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { if (!menuRef.current) return; const focusableElements = menuRef.current.querySelectorAll('a'); const currentIndex = Array.from(focusableElements).findIndex( (el) => el === document.activeElement, ); switch (event.key) { case 'ArrowDown': event.preventDefault(); const nextIndex = currentIndex < focusableElements.length - 1 ? currentIndex + 1 : 0; focusableElements[nextIndex]?.focus(); break; case 'ArrowUp': event.preventDefault(); const prevIndex = currentIndex > 0 ? currentIndex - 1 : focusableElements.length - 1; focusableElements[prevIndex]?.focus(); break; case 'Escape': event.preventDefault(); onClose(); break; case 'Tab': if (event.shiftKey && currentIndex === 0) { onClose(); } else if (!event.shiftKey && currentIndex === focusableElements.length - 1) { onClose(); } break; } }; document.addEventListener('keydown', handleKeyDown); return () => document.removeEventListener('keydown', handleKeyDown); }, [onClose]); return (
{items.map((item, index) => ( {item.label} ))}
); }