import { ReactNode , useState , useEffect , useCallback } from "react" ; import ContextMenu from "./ContextMenu" ; interface Props { renderContents ( ) : ReactNode ; children : ReactNode ; } export default function ContextMenuWraper ( { children , renderContents , ... passThroughProps } ) { const [ openPosition , setOpenPosition ] = useState < { x : number ; y : number ; } | null > ( null ) ; const closeMenu = useCallback ( ( ) => { setOpenPosition ( null ) ; } , [ ] ) ; const handleGlobalClick = useCallback ( ( e ) => { if ( e . button !== 2 ) { closeMenu ( ) ; } } , [ closeMenu ] ) ; const handleRightClick = useCallback ( ( e ) => { const { pageX , pageY } = e ; setOpenPosition ( { x : pageX , y : pageY } ) ; e . preventDefault ( ) ; e . stopPropagation ( ) ; } , [ ] ) ; useEffect ( ( ) => { if ( openPosition == null ) { return ; } document . addEventListener ( "click" , handleGlobalClick ) ; document . body . addEventListener ( "contextmenu" , closeMenu ) ; return ( ) => { document . removeEventListener ( "click" , handleGlobalClick ) ; document . body . removeEventListener ( "contextmenu" , closeMenu ) ; } ; } , [ openPosition , closeMenu , handleGlobalClick ] ) ; return ( < div onContextMenu = { handleRightClick } style = { { width : "100%" , height : "100%" } } { ... passThroughProps } > < ContextMenu selected = { openPosition != null } offsetTop = { openPosition ?. y ?? 0 } offsetLeft = { openPosition ?. x ?? 0 } > { renderContents ( ) } < /ContextMenu> { children } < /div>); }