import React from "react"; import PropTypes from "prop-types"; import ContextMenu from "./ContextMenu"; export default class ContextMenuWraper extends React.Component { constructor(props) { super(props); this.state = { selected: false, offsetTop: null, offsetLeft: null }; this._handleRightClick = this._handleRightClick.bind(this); this._handleGlobalClick = this._handleGlobalClick.bind(this); } componentWillUnmount() { document.removeEventListener("click", this._handleGlobalClick); } _handleGlobalClick() { this.setState({ selected: false, offsetTop: null, offsetLeft: null }); document.removeEventListener("click", this._handleGlobalClick); } _handleRightClick(e) { const { pageX, pageY } = e; this.setState({ selected: true, // TODO: We could do an initial render to see if the menu fits here // and do a second render if it does not. offsetTop: pageY, offsetLeft: pageX }); // This used to be a "click" handler, but Firefox would trigger a "click" // event on the mouseup of the click that triggered `_handleRightClick` in the // first place. // // If there are multiple right-clicks before there is a global click, // the browser will dedupe this binding for us, since the bound function // is referentially identical each time. document.addEventListener("mousedown", this._handleGlobalClick); e.preventDefault(); e.stopPropagation(); } render() { const { children, renderContents, ...passThroughProps } = this.props; return (
{renderContents()} {children}
); } } ContextMenuWraper.propTypes = { children: PropTypes.any.isRequired, renderContents: PropTypes.func.isRequired };