import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/esm/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
// @ts-nocheck
import * as React from 'react';
import { Provider, create } from 'mini-store';
import omit from '../rc-util/omit';
import SubPopupMenu, { getActiveKey } from './SubPopupMenu';
import { noop } from './util';
import { getMotion } from './utils/legacyUtil';

var Menu = /*#__PURE__*/function (_React$Component) {
  _inherits(Menu, _React$Component);

  var _super = _createSuper(Menu);

  function Menu(props) {
    var _this;

    _classCallCheck(this, Menu);

    _this = _super.call(this, props);

    _this.onSelect = function (selectInfo) {
      var _assertThisInitialize = _assertThisInitialized(_this),
          props = _assertThisInitialize.props;

      if (props.selectable) {
        // root menu
        var _this$store$getState = _this.store.getState(),
            _selectedKeys = _this$store$getState.selectedKeys;

        var selectedKey = selectInfo.key;

        if (props.multiple) {
          _selectedKeys = _selectedKeys.concat([selectedKey]);
        } else {
          _selectedKeys = [selectedKey];
        }

        if (!('selectedKeys' in props)) {
          _this.store.setState({
            selectedKeys: _selectedKeys
          });
        }

        props.onSelect(_objectSpread(_objectSpread({}, selectInfo), {}, {
          selectedKeys: _selectedKeys
        }));
      }
    };

    _this.onClick = function (e) {
      var mode = _this.getRealMenuMode();

      var _assertThisInitialize2 = _assertThisInitialized(_this),
          store = _assertThisInitialize2.store,
          onOpenChange = _assertThisInitialize2.props.onOpenChange;

      if (mode !== 'inline' && !('openKeys' in _this.props)) {
        // closing vertical popup submenu after click it
        store.setState({
          openKeys: []
        });
        onOpenChange([]);
      }

      _this.props.onClick(e);
    }; // onKeyDown needs to be exposed as a instance method
    // e.g., in rc-select, we need to navigate menu item while
    // current active item is rc-select input box rather than the menu itself


    _this.onKeyDown = function (e, callback) {
      _this.innerMenu.getWrappedInstance().onKeyDown(e, callback);
    };

    _this.onOpenChange = function (event) {
      var _assertThisInitialize3 = _assertThisInitialized(_this),
          props = _assertThisInitialize3.props;

      var openKeys = _this.store.getState().openKeys.concat();

      var changed = false;

      var processSingle = function processSingle(e) {
        var oneChanged = false;

        if (e.open) {
          oneChanged = openKeys.indexOf(e.key) === -1;

          if (oneChanged) {
            openKeys.push(e.key);
          }
        } else {
          var index = openKeys.indexOf(e.key);
          oneChanged = index !== -1;

          if (oneChanged) {
            openKeys.splice(index, 1);
          }
        }

        changed = changed || oneChanged;
      };

      if (Array.isArray(event)) {
        // batch change call
        event.forEach(processSingle);
      } else {
        processSingle(event);
      }

      if (changed) {
        if (!('openKeys' in _this.props)) {
          _this.store.setState({
            openKeys: openKeys
          });
        }

        props.onOpenChange(openKeys);
      }
    };

    _this.onDeselect = function (selectInfo) {
      var _assertThisInitialize4 = _assertThisInitialized(_this),
          props = _assertThisInitialize4.props;

      if (props.selectable) {
        var _selectedKeys2 = _this.store.getState().selectedKeys.concat();

        var selectedKey = selectInfo.key;

        var index = _selectedKeys2.indexOf(selectedKey);

        if (index !== -1) {
          _selectedKeys2.splice(index, 1);
        }

        if (!('selectedKeys' in props)) {
          _this.store.setState({
            selectedKeys: _selectedKeys2
          });
        }

        props.onDeselect(_objectSpread(_objectSpread({}, selectInfo), {}, {
          selectedKeys: _selectedKeys2
        }));
      }
    }; // Restore vertical mode when menu is collapsed responsively when mounted
    // https://github.com/ant-design/ant-design/issues/13104
    // TODO: not a perfect solution,
    // looking a new way to avoid setting switchingModeFromInline in this situation


    _this.onMouseEnter = function (e) {
      _this.restoreModeVerticalFromInline();

      var onMouseEnter = _this.props.onMouseEnter;

      if (onMouseEnter) {
        onMouseEnter(e);
      }
    };

    _this.onTransitionEnd = function (e) {
      // when inlineCollapsed menu width animation finished
      // https://github.com/ant-design/ant-design/issues/12864
      var widthCollapsed = e.propertyName === 'width' && e.target === e.currentTarget; // Fix SVGElement e.target.className.indexOf is not a function
      // https://github.com/ant-design/ant-design/issues/15699

      var className = e.target.className; // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal,
      // unless during an animation.

      var classNameValue = Object.prototype.toString.call(className) === '[object SVGAnimatedString]' ? className.animVal : className; // Fix for <Menu style={{ width: '100%' }} />,
      // the width transition won't trigger when menu is collapsed
      // https://github.com/ant-design/ant-design-pro/issues/2783

      var iconScaled = e.propertyName === 'font-size' && classNameValue.indexOf('anticon') >= 0;

      if (widthCollapsed || iconScaled) {
        _this.restoreModeVerticalFromInline();
      }
    };

    _this.setInnerMenu = function (node) {
      _this.innerMenu = node;
    };

    _this.isRootMenu = true;
    var selectedKeys = props.defaultSelectedKeys;
    var openKeys = props.defaultOpenKeys;

    if ('selectedKeys' in props) {
      selectedKeys = props.selectedKeys || [];
    }

    if ('openKeys' in props) {
      openKeys = props.openKeys || [];
    }

    _this.store = create({
      selectedKeys: selectedKeys,
      openKeys: openKeys,
      activeKey: {
        '0-menu-': getActiveKey(props, props.activeKey)
      }
    });
    _this.state = {
      switchingModeFromInline: false,
      prevProps: props,
      inlineOpenKeys: [],
      store: _this.store
    };
    return _this;
  }

  _createClass(Menu, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.updateMiniStore();
      this.updateMenuDisplay();
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      var _this$props = this.props,
          siderCollapsed = _this$props.siderCollapsed,
          inlineCollapsed = _this$props.inlineCollapsed,
          onOpenChange = _this$props.onOpenChange;

      if (!prevProps.inlineCollapsed && inlineCollapsed || !prevProps.siderCollapsed && siderCollapsed) {
        onOpenChange([]);
      }

      this.updateMiniStore();
      this.updateMenuDisplay();
    }
  }, {
    key: "updateMenuDisplay",
    value: function updateMenuDisplay() {
      var collapsedWidth = this.props.collapsedWidth,
          store = this.store,
          prevOpenKeys = this.prevOpenKeys; // https://github.com/ant-design/ant-design/issues/8587

      var hideMenu = this.getInlineCollapsed() && (collapsedWidth === 0 || collapsedWidth === '0' || collapsedWidth === '0px');

      if (hideMenu) {
        this.prevOpenKeys = store.getState().openKeys.concat();
        this.store.setState({
          openKeys: []
        });
      } else if (prevOpenKeys) {
        this.store.setState({
          openKeys: prevOpenKeys
        });
        this.prevOpenKeys = null;
      }
    }
  }, {
    key: "getRealMenuMode",
    value: function getRealMenuMode() {
      var mode = this.props.mode;
      var switchingModeFromInline = this.state.switchingModeFromInline;
      var inlineCollapsed = this.getInlineCollapsed();

      if (switchingModeFromInline && inlineCollapsed) {
        return 'inline';
      }

      return inlineCollapsed ? 'vertical' : mode;
    }
  }, {
    key: "getInlineCollapsed",
    value: function getInlineCollapsed() {
      var _this$props2 = this.props,
          inlineCollapsed = _this$props2.inlineCollapsed,
          siderCollapsed = _this$props2.siderCollapsed;

      if (siderCollapsed !== undefined) {
        return siderCollapsed;
      }

      return inlineCollapsed;
    }
  }, {
    key: "restoreModeVerticalFromInline",
    value: function restoreModeVerticalFromInline() {
      var switchingModeFromInline = this.state.switchingModeFromInline;

      if (switchingModeFromInline) {
        this.setState({
          switchingModeFromInline: false
        });
      }
    }
  }, {
    key: "updateMiniStore",
    value: function updateMiniStore() {
      if ('selectedKeys' in this.props) {
        this.store.setState({
          selectedKeys: this.props.selectedKeys || []
        });
      }

      if ('openKeys' in this.props) {
        this.store.setState({
          openKeys: this.props.openKeys || []
        });
      }
    }
  }, {
    key: "render",
    value: function render() {
      var props = _objectSpread({}, omit(this.props, ['collapsedWidth', 'siderCollapsed', 'defaultMotions']));

      var mode = this.getRealMenuMode();
      props.className += " ".concat(props.prefixCls, "-root");

      if (props.direction === 'rtl') {
        props.className += " ".concat(props.prefixCls, "-rtl");
      }

      props = _objectSpread(_objectSpread({}, props), {}, {
        mode: mode,
        onClick: this.onClick,
        onOpenChange: this.onOpenChange,
        onDeselect: this.onDeselect,
        onSelect: this.onSelect,
        onMouseEnter: this.onMouseEnter,
        onTransitionEnd: this.onTransitionEnd,
        parentMenu: this,
        motion: getMotion(this.props, this.state, mode)
      });
      delete props.openAnimation;
      delete props.openTransitionName;
      return /*#__PURE__*/React.createElement(Provider, {
        store: this.store
      }, /*#__PURE__*/React.createElement(SubPopupMenu, Object.assign({}, props, {
        ref: this.setInnerMenu
      }), this.props.children));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(nextProps, prevState) {
      var prevProps = prevState.prevProps,
          store = prevState.store;
      var prevStoreState = store.getState();
      var newStoreState = {};
      var newState = {
        prevProps: nextProps
      };

      if (prevProps.mode === 'inline' && nextProps.mode !== 'inline') {
        newState.switchingModeFromInline = true;
      }

      if ('openKeys' in nextProps) {
        newStoreState.openKeys = nextProps.openKeys || [];
      } else {
        // [Legacy] Old code will return after `openKeys` changed.
        // Not sure the reason, we should keep this logic still.
        if (nextProps.inlineCollapsed && !prevProps.inlineCollapsed || nextProps.siderCollapsed && !prevProps.siderCollapsed) {
          newState.switchingModeFromInline = true;
          newState.inlineOpenKeys = prevStoreState.openKeys;
          newStoreState.openKeys = [];
        }

        if (!nextProps.inlineCollapsed && prevProps.inlineCollapsed || !nextProps.siderCollapsed && prevProps.siderCollapsed) {
          newStoreState.openKeys = prevState.inlineOpenKeys;
          newState.inlineOpenKeys = [];
        }
      }

      if (Object.keys(newStoreState).length) {
        store.setState(newStoreState);
      }

      return newState;
    }
  }]);

  return Menu;
}(React.Component);

Menu.defaultProps = {
  selectable: true,
  onClick: noop,
  onSelect: noop,
  onOpenChange: noop,
  onDeselect: noop,
  defaultSelectedKeys: [],
  defaultOpenKeys: [],
  subMenuOpenDelay: 0.1,
  subMenuCloseDelay: 0.1,
  triggerSubMenuAction: 'hover',
  prefixCls: 'rc-menu',
  className: '',
  mode: 'vertical',
  style: {},
  builtinPlacements: {},
  overflowedIndicator: /*#__PURE__*/React.createElement("span", null, "\xB7\xB7\xB7")
};
export default Menu;