"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard")["default"];

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault")["default"];

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

var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));

var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));

var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck"));

var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass"));

var _assertThisInitialized2 = _interopRequireDefault(require("@babel/runtime/helpers/assertThisInitialized"));

var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));

var _createSuper2 = _interopRequireDefault(require("@babel/runtime/helpers/createSuper"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _objectSpread3 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

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

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

var _noop = _interopRequireDefault(require("lodash/noop"));

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

var _miniStore = require("mini-store");

var _trigger = _interopRequireDefault(require("../trigger"));

var _KeyCode = _interopRequireDefault(require("../../_util/KeyCode"));

var _SubPopupMenu = _interopRequireDefault(require("./SubPopupMenu"));

var _placements = _interopRequireDefault(require("./placements"));

var _animate = _interopRequireDefault(require("../../animate"));

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

var guid = 0;
var popupPlacementMap = {
  horizontal: 'bottomLeft',
  vertical: 'rightTop',
  'vertical-left': 'rightTop',
  'vertical-right': 'leftTop'
};

var updateDefaultActiveFirst = function updateDefaultActiveFirst(store, eventKey, defaultActiveFirst) {
  var menuId = (0, _util.getMenuIdFromSubMenuEventKey)(eventKey);
  var state = store.getState();
  store.setState({
    defaultActiveFirst: (0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, state.defaultActiveFirst), {}, (0, _defineProperty2["default"])({}, menuId, defaultActiveFirst))
  });
};

var SubMenu = /*#__PURE__*/function (_Component) {
  (0, _inherits2["default"])(SubMenu, _Component);

  var _super = (0, _createSuper2["default"])(SubMenu);

  function SubMenu(_props) {
    var _this;

    (0, _classCallCheck2["default"])(this, SubMenu);
    _this = _super.call(this, _props);
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onDestroy", function (key) {
      _this.props.onDestroy(key);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onKeyDown", function (e) {
      var keyCode = e.keyCode;
      var menu = _this.menuInstance;
      var _this$props = _this.props,
          isOpen = _this$props.isOpen,
          store = _this$props.store;

      if (keyCode === _KeyCode["default"].ENTER) {
        _this.onTitleClick(e);

        updateDefaultActiveFirst(store, _this.props.eventKey, true);
        return true;
      }

      if (keyCode === _KeyCode["default"].RIGHT) {
        if (isOpen) {
          menu.onKeyDown(e);
        } else {
          _this.triggerOpenChange(true); // need to update current menu's defaultActiveFirst value


          updateDefaultActiveFirst(store, _this.props.eventKey, true);
        }

        return true;
      }

      if (keyCode === _KeyCode["default"].LEFT) {
        var handled;

        if (isOpen) {
          handled = menu.onKeyDown(e);
        } else {
          return undefined;
        }

        if (!handled) {
          _this.triggerOpenChange(false);

          handled = true;
        }

        return handled;
      }

      if (isOpen && (keyCode === _KeyCode["default"].UP || keyCode === _KeyCode["default"].DOWN)) {
        return menu.onKeyDown(e);
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onOpenChange", function (e) {
      _this.props.onOpenChange(e);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onPopupVisibleChange", function (visible) {
      _this.triggerOpenChange(visible, visible ? 'mouseenter' : 'mouseleave');
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onMouseEnter", function (e) {
      var _this$props2 = _this.props,
          key = _this$props2.eventKey,
          onMouseEnter = _this$props2.onMouseEnter,
          store = _this$props2.store;
      updateDefaultActiveFirst(store, _this.props.eventKey, false);
      onMouseEnter({
        key: key,
        domEvent: e
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onMouseLeave", function (e) {
      var _this$props3 = _this.props,
          parentMenu = _this$props3.parentMenu,
          eventKey = _this$props3.eventKey,
          onMouseLeave = _this$props3.onMouseLeave;
      parentMenu.subMenuInstance = (0, _assertThisInitialized2["default"])(_this);
      onMouseLeave({
        key: eventKey,
        domEvent: e
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTitleMouseEnter", function (domEvent) {
      var _this$props4 = _this.props,
          key = _this$props4.eventKey,
          onItemHover = _this$props4.onItemHover,
          onTitleMouseEnter = _this$props4.onTitleMouseEnter;
      onItemHover({
        key: key,
        hover: true
      });
      onTitleMouseEnter({
        key: key,
        domEvent: domEvent
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTitleMouseLeave", function (e) {
      var _this$props5 = _this.props,
          parentMenu = _this$props5.parentMenu,
          eventKey = _this$props5.eventKey,
          onItemHover = _this$props5.onItemHover,
          onTitleMouseLeave = _this$props5.onTitleMouseLeave;
      parentMenu.subMenuInstance = (0, _assertThisInitialized2["default"])(_this);
      onItemHover({
        key: eventKey,
        hover: false
      });
      onTitleMouseLeave({
        key: eventKey,
        domEvent: e
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onTitleClick", function (e) {
      var _assertThisInitialize = (0, _assertThisInitialized2["default"])(_this),
          props = _assertThisInitialize.props;

      props.onTitleClick({
        key: props.eventKey,
        domEvent: e
      });

      if (props.triggerSubMenuAction === 'hover') {
        return;
      }

      _this.triggerOpenChange(!props.isOpen, 'click');

      updateDefaultActiveFirst(props.store, _this.props.eventKey, false);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onSubMenuClick", function (info) {
      // in the case of overflowed submenu
      // onClick is not copied over
      if (typeof _this.props.onClick === 'function') {
        _this.props.onClick(_this.addKeyPath(info));
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onSelect", function (info) {
      _this.props.onSelect(info);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "onDeselect", function (info) {
      _this.props.onDeselect(info);
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getPrefixCls", function () {
      return "".concat(_this.props.rootPrefixCls, "-submenu");
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getActiveClassName", function () {
      return "".concat(_this.getPrefixCls(), "-active");
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getDisabledClassName", function () {
      return "".concat(_this.getPrefixCls(), "-disabled");
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getSelectedClassName", function () {
      return "".concat(_this.getPrefixCls(), "-selected");
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "getOpenClassName", function () {
      return "".concat(_this.props.rootPrefixCls, "-submenu-open");
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "saveMenuInstance", function (c) {
      // children menu instance
      _this.menuInstance = c;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "addKeyPath", function (info) {
      return (0, _objectSpread3["default"])((0, _objectSpread3["default"])({}, info), {}, {
        keyPath: (info.keyPath || []).concat(_this.props.eventKey)
      });
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "triggerOpenChange", function (open, type) {
      var key = _this.props.eventKey;

      var openChange = function openChange() {
        _this.onOpenChange({
          key: key,
          item: (0, _assertThisInitialized2["default"])(_this),
          trigger: type,
          open: open
        });
      };

      if (type === 'mouseenter') {
        // make sure mouseenter happen after other menu item's mouseleave
        _this.mouseenterTimeout = setTimeout(function () {
          openChange();
        }, 0);
      } else {
        openChange();
      }
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "isChildrenSelected", function () {
      var ret = {
        find: false
      };
      (0, _util.loopMenuItemRecursively)(_this.props.children, _this.props.selectedKeys, ret);
      return ret.find;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "isOpen", function () {
      return _this.props.openKeys.indexOf(_this.props.eventKey) !== -1;
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "adjustWidth", function () {
      /* istanbul ignore if */
      if (!_this.subMenuTitle || !_this.menuInstance) {
        return;
      }

      var popupMenu = (0, _reactDom.findDOMNode)(_this.menuInstance);

      if (popupMenu.offsetWidth >= _this.subMenuTitle.offsetWidth) {
        return;
      }
      /* istanbul ignore next */


      popupMenu.style.minWidth = "".concat(_this.subMenuTitle.offsetWidth, "px");
    });
    (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "saveSubMenuTitle", function (subMenuTitle) {
      _this.subMenuTitle = subMenuTitle;
    });
    var _store = _props.store;
    var _eventKey = _props.eventKey;

    var defaultActiveFirst = _store.getState().defaultActiveFirst;

    _this.isRootMenu = false;
    var value = false;

    if (defaultActiveFirst) {
      value = defaultActiveFirst[_eventKey];
    }

    updateDefaultActiveFirst(_store, _eventKey, value);
    return _this;
  }

  (0, _createClass2["default"])(SubMenu, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.componentDidUpdate();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate() {
      var _this2 = this;

      var _this$props6 = this.props,
          mode = _this$props6.mode,
          parentMenu = _this$props6.parentMenu,
          manualRef = _this$props6.manualRef; // invoke customized ref to expose component to mixin

      if (manualRef) {
        manualRef(this);
      }

      if (mode !== 'horizontal' || !parentMenu.isRootMenu || !this.props.isOpen) {
        return;
      }

      this.minWidthTimeout = setTimeout(function () {
        return _this2.adjustWidth();
      }, 0);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      var _this$props7 = this.props,
          onDestroy = _this$props7.onDestroy,
          eventKey = _this$props7.eventKey;

      if (onDestroy) {
        onDestroy(eventKey);
      }
      /* istanbul ignore if */


      if (this.minWidthTimeout) {
        clearTimeout(this.minWidthTimeout);
      }
      /* istanbul ignore if */


      if (this.mouseenterTimeout) {
        clearTimeout(this.mouseenterTimeout);
      }
    }
  }, {
    key: "renderChildren",
    value: function renderChildren(children) {
      var props = this.props;
      var baseProps = {
        mode: props.mode === 'horizontal' ? 'vertical' : props.mode,
        hidden: !this.props.isOpen,
        level: props.level + 1,
        inlineIndent: props.inlineIndent,
        focusable: false,
        onClick: this.onSubMenuClick,
        onSelect: this.onSelect,
        onDeselect: this.onDeselect,
        onDestroy: this.onDestroy,
        selectedKeys: props.selectedKeys,
        eventKey: "".concat(props.eventKey, "-menu-"),
        openKeys: props.openKeys,
        openTransitionName: props.openTransitionName,
        openAnimation: props.openAnimation,
        onOpenChange: this.onOpenChange,
        subMenuOpenDelay: props.subMenuOpenDelay,
        parentMenu: this,
        subMenuCloseDelay: props.subMenuCloseDelay,
        forceSubMenuRender: props.forceSubMenuRender,
        triggerSubMenuAction: props.triggerSubMenuAction,
        builtinPlacements: props.builtinPlacements,
        defaultActiveFirst: props.store.getState().defaultActiveFirst[(0, _util.getMenuIdFromSubMenuEventKey)(props.eventKey)],
        multiple: props.multiple,
        prefixCls: props.rootPrefixCls,
        id: this._menuId,
        manualRef: this.saveMenuInstance,
        itemIcon: props.itemIcon,
        expandIcon: props.expandIcon
      };
      var haveRendered = this.haveRendered;
      this.haveRendered = true;
      this.haveOpened = this.haveOpened || !baseProps.hidden || baseProps.forceSubMenuRender; // never rendered not planning to, don't render

      if (!this.haveOpened) {
        return /*#__PURE__*/_react["default"].createElement("div", null);
      } // don't show transition on first rendering (no animation for opened menu)
      // show appear transition if it's hidden (not sure why)
      // show appear transition if it's not inline mode


      var transitionAppear = haveRendered || baseProps.hidden || !baseProps.mode === 'inline';
      baseProps.className = " ".concat(baseProps.prefixCls, "-sub");
      var animProps = {};

      if (baseProps.openTransitionName) {
        animProps.transitionName = baseProps.openTransitionName;
      } else if ((0, _typeof2["default"])(baseProps.openAnimation) === 'object') {
        animProps.animation = (0, _objectSpread3["default"])({}, baseProps.openAnimation);

        if (!transitionAppear) {
          delete animProps.animation.appear;
        }
      }

      return /*#__PURE__*/_react["default"].createElement(_animate["default"], (0, _extends2["default"])({}, animProps, {
        hiddenProp: "hidden",
        component: "",
        transitionAppear: transitionAppear
      }), /*#__PURE__*/_react["default"].createElement(_SubPopupMenu["default"], (0, _extends2["default"])({}, baseProps, {
        id: this._menuId
      }), children));
    }
  }, {
    key: "render",
    value: function render() {
      var _classNames;

      var props = (0, _objectSpread3["default"])({}, this.props);
      var isOpen = props.isOpen;
      var prefixCls = this.getPrefixCls();
      var isInlineMode = props.mode === 'inline';
      var className = (0, _classnames["default"])(prefixCls, "".concat(prefixCls, "-").concat(props.mode), (_classNames = {}, (0, _defineProperty2["default"])(_classNames, props.className, !!props.className), (0, _defineProperty2["default"])(_classNames, this.getOpenClassName(), isOpen), (0, _defineProperty2["default"])(_classNames, this.getActiveClassName(), props.active || isOpen && !isInlineMode), (0, _defineProperty2["default"])(_classNames, this.getDisabledClassName(), props.disabled), (0, _defineProperty2["default"])(_classNames, this.getSelectedClassName(), this.isChildrenSelected()), _classNames));

      if (!this._menuId) {
        if (props.eventKey) {
          this._menuId = "".concat(props.eventKey, "$Menu");
        } else {
          this._menuId = "$__$".concat(++guid, "$Menu");
        }
      }

      var mouseEvents = {};
      var titleClickEvents = {};
      var titleMouseEvents = {};

      if (!props.disabled) {
        mouseEvents = {
          onMouseLeave: this.onMouseLeave,
          onMouseEnter: this.onMouseEnter
        }; // only works in title, not outer li

        titleClickEvents = {
          onClick: this.onTitleClick
        };
        titleMouseEvents = {
          onMouseEnter: this.onTitleMouseEnter,
          onMouseLeave: this.onTitleMouseLeave
        };
      }

      var style = {};

      if (isInlineMode) {
        style.paddingLeft = props.inlineIndent * props.level;
      }

      var ariaOwns = {}; // only set aria-owns when menu is open
      // otherwise it would be an invalid aria-owns value
      // since corresponding node cannot be found

      if (this.props.isOpen) {
        ariaOwns = {
          'aria-owns': this._menuId
        };
      } // expand custom icon should NOT be displayed in menu with horizontal mode.


      var icon = null;

      if (props.mode !== 'horizontal') {
        icon = this.props.expandIcon; // ReactNode

        if (typeof this.props.expandIcon === 'function') {
          icon = /*#__PURE__*/(0, _react.createElement)(this.props.expandIcon, (0, _objectSpread3["default"])({}, this.props));
        }
      }

      var title = /*#__PURE__*/_react["default"].createElement("div", (0, _extends2["default"])({
        ref: this.saveSubMenuTitle,
        style: style,
        className: "".concat(prefixCls, "-title")
      }, titleMouseEvents, titleClickEvents, {
        "aria-expanded": isOpen
      }, ariaOwns, {
        "aria-haspopup": "true",
        title: typeof props.title === 'string' ? props.title : undefined
      }), props.title, icon || /*#__PURE__*/_react["default"].createElement("i", {
        className: "".concat(prefixCls, "-arrow")
      }));

      var children = this.renderChildren(props.children);
      var getPopupContainer = props.parentMenu.isRootMenu ? props.parentMenu.props.getPopupContainer : function (triggerNode) {
        return triggerNode.parentNode;
      };
      var popupPlacement = popupPlacementMap[props.mode];
      var popupAlign = props.popupOffset ? {
        offset: props.popupOffset
      } : {};
      var popupClassName = props.mode === 'inline' ? '' : props.popupClassName;
      var disabled = props.disabled,
          triggerSubMenuAction = props.triggerSubMenuAction,
          subMenuOpenDelay = props.subMenuOpenDelay,
          forceSubMenuRender = props.forceSubMenuRender,
          subMenuCloseDelay = props.subMenuCloseDelay,
          builtinPlacements = props.builtinPlacements;

      _util.menuAllProps.forEach(function (key) {
        return delete props[key];
      }); // Set onClick to null, to ignore propagated onClick event


      delete props.onClick;
      return /*#__PURE__*/_react["default"].createElement("li", (0, _extends2["default"])({}, props, mouseEvents, {
        className: className,
        role: "menuitem"
      }), isInlineMode && title, isInlineMode && children, !isInlineMode && /*#__PURE__*/_react["default"].createElement(_trigger["default"], {
        prefixCls: prefixCls,
        popupClassName: "".concat(prefixCls, "-popup ").concat(popupClassName),
        getPopupContainer: getPopupContainer,
        builtinPlacements: (0, _extends2["default"])({}, _placements["default"], builtinPlacements),
        popupPlacement: popupPlacement,
        popupVisible: isOpen,
        popupAlign: popupAlign,
        popup: children,
        action: disabled ? [] : [triggerSubMenuAction],
        mouseEnterDelay: subMenuOpenDelay,
        mouseLeaveDelay: subMenuCloseDelay,
        onPopupVisibleChange: this.onPopupVisibleChange,
        forceRender: forceSubMenuRender
      }, title));
    }
  }]);
  return SubMenu;
}(_react.Component);

exports.SubMenu = SubMenu;
(0, _defineProperty2["default"])(SubMenu, "defaultProps", {
  onMouseEnter: _noop["default"],
  onMouseLeave: _noop["default"],
  onTitleMouseEnter: _noop["default"],
  onTitleMouseLeave: _noop["default"],
  onTitleClick: _noop["default"],
  manualRef: _noop["default"],
  mode: 'vertical',
  title: ''
});
var connected = (0, _miniStore.connect)(function (_ref, _ref2) {
  var openKeys = _ref.openKeys,
      activeKey = _ref.activeKey,
      selectedKeys = _ref.selectedKeys;
  var eventKey = _ref2.eventKey,
      subMenuKey = _ref2.subMenuKey;
  return {
    isOpen: openKeys.indexOf(eventKey) > -1,
    active: activeKey[subMenuKey] === eventKey,
    selectedKeys: selectedKeys
  };
})(SubMenu);
connected.isSubMenu = true;
var _default = connected;
exports["default"] = _default;
//# sourceMappingURL=SubMenu.js.map
