'use client' import React, { createContext, useContext, useEffect } from 'react' import { createPortal } from 'react-dom' import type { MenuAnchor } from './types' const MenuCtx = createContext<{ onClose?: () => void }>({}) type MenuProps = { ref: React.RefObject children: React.ReactNode anchor: MenuAnchor onClose?: () => void } export default function Menu({ ref, children, anchor, onClose }: MenuProps) { useEffect(() => { ref.current?.querySelector('[role=menuitem]')?.focus() }, [ref]) useEffect(() => { function handleKey(e: KeyboardEvent) { if (e.key === 'Escape') onClose?.() } window.addEventListener('keydown', handleKey) return () => window.removeEventListener('keydown', handleKey) }, [onClose]) return createPortal(
{children}
, document.body ) } export function MenuButton({ icon, text, hotKey, onClick, className = '', }: { icon: React.ReactNode text: string hotKey?: string onClick: () => void className?: string }) { const { onClose } = useContext(MenuCtx) useEffect(() => { if (!hotKey) return function handleKey(e: KeyboardEvent) { const tag = (e.target as HTMLElement).tagName if (tag === 'INPUT' || tag === 'TEXTAREA') return if (e.key.toLowerCase() === hotKey!.toLowerCase()) { e.preventDefault() onClick() onClose?.() } } window.addEventListener('keydown', handleKey) return () => window.removeEventListener('keydown', handleKey) }, [hotKey, onClick, onClose]) return ( ) }