"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = create;

var _react = _interopRequireWildcard(require("react"));

var _reactDom = require("react-dom");

var _propTypes = _interopRequireDefault(require("prop-types"));

var _classnames = _interopRequireDefault(require("classnames"));

var _overlay = _interopRequireDefault(require("../../overlay"));

var _util = require("../../util");

var _configProvider = _interopRequireDefault(require("../../config-provider"));

var _menu = _interopRequireDefault(require("./menu"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(source, true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(source).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var bindCtx = _util.func.bindCtx;
var getContextProps = _configProvider["default"].getContextProps;

var Menu = _configProvider["default"].config(_menu["default"]);

var menuInstance;

var ContextMenu =
/*#__PURE__*/
function (_Component) {
  _inherits(ContextMenu, _Component);

  function ContextMenu(props) {
    var _this;

    _classCallCheck(this, ContextMenu);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(ContextMenu).call(this, props));
    _this.state = {
      visible: true
    };
    bindCtx(_assertThisInitialized(_this), ['handleOverlayClose', 'handleOverlayOpen', 'handleItemClick', 'getOverlay']);
    return _this;
  }

  _createClass(ContextMenu, [{
    key: "getOverlay",
    value: function getOverlay(ref) {
      this.overlay = ref;
    }
  }, {
    key: "close",
    value: function close() {
      this.setState({
        visible: false
      });
      menuInstance = null;
    }
  }, {
    key: "handleOverlayClose",
    value: function handleOverlayClose(triggerType, e) {
      var clickedPopupMenu = triggerType === 'docClick' && this.popupNodes.some(function (node) {
        return node.contains(e.target);
      });

      if (!clickedPopupMenu) {
        this.close();
        var overlayProps = this.props.overlayProps;

        if (overlayProps && overlayProps.onRequestClose) {
          for (var _len = arguments.length, others = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
            others[_key - 2] = arguments[_key];
          }

          overlayProps.onRequestClose.apply(overlayProps, [triggerType, e].concat(others));
        }
      }
    }
  }, {
    key: "handleOverlayOpen",
    value: function handleOverlayOpen() {
      this.popupNodes = this.overlay.getInstance().getContent().getInstance().popupNodes;
      var overlayProps = this.props.overlayProps;

      if (overlayProps && overlayProps.onOpen) {
        overlayProps.onOpen();
      }
    }
  }, {
    key: "handleItemClick",
    value: function handleItemClick() {
      var _this$props;

      this.close();
      this.props.onItemClick && (_this$props = this.props).onItemClick.apply(_this$props, arguments);
    }
  }, {
    key: "render",
    value: function render() {
      var _cx, _cx2;

      var _this$props2 = this.props,
          className = _this$props2.className,
          popupClassName = _this$props2.popupClassName,
          target = _this$props2.target,
          align = _this$props2.align,
          offset = _this$props2.offset,
          afterClose = _this$props2.afterClose,
          _this$props2$overlayP = _this$props2.overlayProps,
          overlayProps = _this$props2$overlayP === void 0 ? {} : _this$props2$overlayP,
          others = _objectWithoutProperties(_this$props2, ["className", "popupClassName", "target", "align", "offset", "afterClose", "overlayProps"]);

      var contextProps = getContextProps(this.props);
      var prefix = contextProps.prefix;
      var visible = this.state.visible;

      var newOverlayProps = _objectSpread({}, contextProps, {}, overlayProps, {
        target: target,
        align: align,
        offset: offset,
        afterClose: afterClose,
        visible: visible,
        onRequestClose: this.handleOverlayClose,
        onOpen: this.handleOverlayOpen,
        ref: this.getOverlay
      });

      var menuProps = _objectSpread({}, contextProps, {
        triggerType: 'hover'
      }, others, {
        className: (0, _classnames["default"])((_cx = {}, _defineProperty(_cx, "".concat(prefix, "context"), true), _defineProperty(_cx, className, !!className), _cx)),
        popupClassName: (0, _classnames["default"])((_cx2 = {}, _defineProperty(_cx2, "".concat(prefix, "context"), true), _defineProperty(_cx2, popupClassName, !!popupClassName), _cx2)),
        onItemClick: this.handleItemClick
      });

      newOverlayProps.rtl = false;
      return _react["default"].createElement(_overlay["default"], newOverlayProps, _react["default"].createElement(Menu, menuProps));
    }
  }]);

  return ContextMenu;
}(_react.Component);
/**
 * 创建上下文菜单
 * @exportName create
 * @param {Object} props 属性对象
 */


_defineProperty(ContextMenu, "propTypes", {
  className: _propTypes["default"].string,
  popupClassName: _propTypes["default"].string,
  target: _propTypes["default"].any,
  align: _propTypes["default"].string,
  offset: _propTypes["default"].array,
  overlayProps: _propTypes["default"].object,
  afterClose: _propTypes["default"].func,
  mode: _propTypes["default"].oneOf(['inline', 'popup']),
  onOpen: _propTypes["default"].func,
  onItemClick: _propTypes["default"].func
});

_defineProperty(ContextMenu, "defaultProps", {
  prefix: 'next-',
  align: 'tl tl',
  mode: 'popup'
});

function create(props) {
  if (menuInstance) {
    menuInstance.destroy();
  }
  /* eslint-disable no-unused-vars */


  var afterClose = props.afterClose,
      others = _objectWithoutProperties(props, ["afterClose"]);
  /* eslint-enable no-unused-vars */


  var div = document.createElement('div');
  document.body.appendChild(div);

  var closeChain = function closeChain() {
    (0, _reactDom.unmountComponentAtNode)(div);
    document.body.removeChild(div);
    afterClose && afterClose();
  };

  var newContext = _configProvider["default"].getContext();

  var menu;
  (0, _reactDom.render)(_react["default"].createElement(_configProvider["default"], newContext, _react["default"].createElement(ContextMenu, _extends({
    ref: function ref(_ref) {
      menu = _ref;
    },
    afterClose: closeChain
  }, others))), div);
  menuInstance = {
    destroy: function destroy() {
      if (menu) {
        menu.close();
      }
    }
  };
  return menuInstance;
}