"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; 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); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.saveRef = saveRef;
exports.getActiveKey = getActiveKey;
exports.default = void 0;

var _vue = _interopRequireWildcard(require("vue"));

var _vueTypes = _interopRequireDefault(require("../_util/vue-types"));

var _store = require("../_util/store");

var _BaseMixin = _interopRequireDefault(require("../_util/BaseMixin"));

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

var _classNames = _interopRequireDefault(require("../_util/classNames"));

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

var _DOMWrap = _interopRequireDefault(require("./DOMWrap"));

var _vnode = require("../_util/vnode");

var _propsUtil = require("../_util/props-util");

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { 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 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(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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; }

function allDisabled(arr) {
  if (!arr.length) {
    return true;
  }

  return arr.every(function (c) {
    return !!c.disabled;
  });
}

function updateActiveKey(store, menuId, activeKey) {
  var state = store.getState();
  store.setState({
    activeKey: _objectSpread(_objectSpread({}, state.activeKey), {}, _defineProperty({}, menuId, activeKey))
  });
}

function getEventKey(props) {
  // when eventKey not available ,it's menu and return menu id '0-menu-'
  return props.eventKey || '0-menu-';
}

function saveRef(key, c) {
  if (c) {
    var index = this.instanceArrayKeyIndexMap[key];
    this.instanceArray[index] = c;
  }
}

function getActiveKey(props, originalActiveKey) {
  var activeKey = originalActiveKey;
  var eventKey = props.eventKey,
      defaultActiveFirst = props.defaultActiveFirst,
      children = props.children;

  if (activeKey !== undefined && activeKey !== null) {
    var found;
    (0, _util.loopMenuItem)(children, function (c, i) {
      var propsData = (0, _propsUtil.getPropsData)(c);

      if (c && !propsData.disabled && activeKey === (0, _util.getKeyFromChildrenIndex)(c, eventKey, i)) {
        found = true;
      }
    });

    if (found) {
      return activeKey;
    }
  }

  activeKey = null;

  if (defaultActiveFirst) {
    (0, _util.loopMenuItem)(children, function (c, i) {
      var propsData = (0, _propsUtil.getPropsData)(c);
      var noActiveKey = activeKey === null || activeKey === undefined;

      if (noActiveKey && c && !propsData.disabled) {
        activeKey = (0, _util.getKeyFromChildrenIndex)(c, eventKey, i);
      }
    });
    return activeKey;
  }

  return activeKey;
}

var SubPopupMenu = {
  name: 'SubPopupMenu',
  inheritAttrs: false,
  props: (0, _propsUtil.initDefaultProps)({
    // onSelect: PropTypes.func,
    // onClick: PropTypes.func,
    // onDeselect: PropTypes.func,
    // onOpenChange: PropTypes.func,
    // onDestroy: PropTypes.func,
    prefixCls: _vueTypes.default.string,
    openTransitionName: _vueTypes.default.string,
    openAnimation: _vueTypes.default.oneOfType([_vueTypes.default.string, _vueTypes.default.object]),
    openKeys: _vueTypes.default.arrayOf(_vueTypes.default.oneOfType([_vueTypes.default.string, _vueTypes.default.number])),
    visible: _vueTypes.default.bool,
    eventKey: _vueTypes.default.string,
    store: _vueTypes.default.object,
    // adding in refactor
    focusable: _vueTypes.default.bool,
    multiple: _vueTypes.default.bool,
    defaultActiveFirst: _vueTypes.default.bool,
    activeKey: _vueTypes.default.oneOfType([_vueTypes.default.string, _vueTypes.default.number]),
    selectedKeys: _vueTypes.default.arrayOf(_vueTypes.default.oneOfType([_vueTypes.default.string, _vueTypes.default.number])),
    defaultSelectedKeys: _vueTypes.default.arrayOf(_vueTypes.default.oneOfType([_vueTypes.default.string, _vueTypes.default.number])),
    defaultOpenKeys: _vueTypes.default.arrayOf(_vueTypes.default.oneOfType([_vueTypes.default.string, _vueTypes.default.number])),
    level: _vueTypes.default.number,
    mode: _vueTypes.default.oneOf(['horizontal', 'vertical', 'vertical-left', 'vertical-right', 'inline']),
    triggerSubMenuAction: _vueTypes.default.oneOf(['click', 'hover']),
    inlineIndent: _vueTypes.default.oneOfType([_vueTypes.default.number, _vueTypes.default.string]),
    manualRef: _vueTypes.default.func,
    itemIcon: _vueTypes.default.any,
    expandIcon: _vueTypes.default.any,
    overflowedIndicator: _vueTypes.default.any,
    children: _vueTypes.default.any.def([])
  }, {
    prefixCls: 'rc-menu',
    mode: 'vertical',
    level: 1,
    inlineIndent: 24,
    visible: true,
    focusable: true,
    manualRef: _util.noop
  }),
  mixins: [_BaseMixin.default],
  setup: function setup() {
    return {
      parentMenu: (0, _vue.inject)('parentMenu', undefined)
    };
  },
  created: function created() {
    var props = (0, _propsUtil.getOptionProps)(this);
    this.prevProps = _objectSpread({}, props);
    props.store.setState({
      activeKey: _objectSpread(_objectSpread({}, props.store.getState().activeKey), {}, _defineProperty({}, props.eventKey, getActiveKey(props, props.activeKey)))
    });
    this.instanceArray = [];
  },
  mounted: function mounted() {
    // invoke customized ref to expose component to mixin
    if (this.manualRef) {
      this.manualRef(this);
    }
  },
  updated: function updated() {
    var props = (0, _propsUtil.getOptionProps)(this);
    var prevProps = this.prevProps;
    var originalActiveKey = 'activeKey' in props ? props.activeKey : props.store.getState().activeKey[getEventKey(props)];
    var activeKey = getActiveKey(props, originalActiveKey);

    if (activeKey !== originalActiveKey) {
      updateActiveKey(props.store, getEventKey(props), activeKey);
    } else if ('activeKey' in prevProps) {
      // If prev activeKey is not same as current activeKey,
      // we should set it.
      var prevActiveKey = getActiveKey(prevProps, prevProps.activeKey);

      if (activeKey !== prevActiveKey) {
        updateActiveKey(props.store, getEventKey(props), activeKey);
      }
    }

    this.prevProps = _objectSpread({}, props);
  },
  methods: {
    // all keyboard events callbacks run from here at first
    onKeyDown: function onKeyDown(e, callback) {
      var keyCode = e.keyCode;
      var handled;
      this.getFlatInstanceArray().forEach(function (obj) {
        if (obj && obj.active && obj.onKeyDown) {
          handled = obj.onKeyDown(e);
        }
      });

      if (handled) {
        return 1;
      }

      var activeItem = null;

      if (keyCode === _KeyCode.default.UP || keyCode === _KeyCode.default.DOWN) {
        activeItem = this.step(keyCode === _KeyCode.default.UP ? -1 : 1);
      }

      if (activeItem) {
        e.preventDefault();
        updateActiveKey(this.$props.store, getEventKey(this.$props), activeItem.eventKey);

        if (typeof callback === 'function') {
          callback(activeItem);
        }

        return 1;
      }

      return undefined;
    },
    onItemHover: function onItemHover(e) {
      var key = e.key,
          hover = e.hover;
      updateActiveKey(this.$props.store, getEventKey(this.$props), hover ? key : null);
    },
    onDeselect: function onDeselect(selectInfo) {
      this.__emit('deselect', selectInfo);
    },
    onSelect: function onSelect(selectInfo) {
      this.__emit('select', selectInfo);
    },
    onClick: function onClick(e) {
      this.__emit('click', e);
    },
    onOpenChange: function onOpenChange(e) {
      this.__emit('openChange', e);
    },
    onDestroy: function onDestroy(key) {
      this.__emit('destroy', key);
    },
    getFlatInstanceArray: function getFlatInstanceArray() {
      return this.instanceArray;
    },
    getOpenTransitionName: function getOpenTransitionName() {
      return this.$props.openTransitionName;
    },
    step: function step(direction) {
      var children = this.getFlatInstanceArray();
      var activeKey = this.$props.store.getState().activeKey[getEventKey(this.$props)];
      var len = children.length;

      if (!len) {
        return null;
      }

      if (direction < 0) {
        children = children.concat().reverse();
      } // find current activeIndex


      var activeIndex = -1;
      children.every(function (c, ci) {
        if (c && c.eventKey === activeKey) {
          activeIndex = ci;
          return false;
        }

        return true;
      });

      if (!this.defaultActiveFirst && activeIndex !== -1 && allDisabled(children.slice(activeIndex, len - 1))) {
        return undefined;
      }

      var start = (activeIndex + 1) % len;
      var i = start;

      do {
        var child = children[i];

        if (!child || child.disabled) {
          i = (i + 1) % len;
        } else {
          return child;
        }
      } while (i !== start);

      return null;
    },
    getIcon: function getIcon(instance, name) {
      return (0, _propsUtil.getComponent)(instance, name);
    },
    renderCommonMenuItem: function renderCommonMenuItem(child, i, extraProps) {
      var _this = this;

      if (child.type === _vue.Comment) {
        return child;
      }

      var state = this.$props.store.getState();
      var props = this.$props;
      var key = (0, _util.getKeyFromChildrenIndex)(child, props.eventKey, i);
      var childProps = child.props || {}; // child.props 包含事件

      var isActive = key === state.activeKey[getEventKey(this.$props)];

      if (!childProps.disabled) {
        // manualRef的执行顺序不能保证，使用key映射ref在this.instanceArray中的位置
        this.instanceArrayKeyIndexMap[key] = Object.keys(this.instanceArrayKeyIndexMap).length;
      }

      var newChildProps = _objectSpread(_objectSpread({
        mode: childProps.mode || props.mode,
        level: props.level,
        inlineIndent: props.inlineIndent,
        renderMenuItem: this.renderMenuItem,
        rootPrefixCls: props.prefixCls,
        index: i,
        // customized ref function, need to be invoked manually in child's componentDidMount
        manualRef: childProps.disabled ? _util.noop : saveRef.bind(this, key),
        eventKey: key,
        active: !childProps.disabled && isActive,
        multiple: props.multiple,
        openTransitionName: this.getOpenTransitionName(),
        openAnimation: props.openAnimation,
        subMenuOpenDelay: props.subMenuOpenDelay,
        subMenuCloseDelay: props.subMenuCloseDelay,
        forceSubMenuRender: props.forceSubMenuRender,
        builtinPlacements: props.builtinPlacements,
        itemIcon: this.getIcon(child, 'itemIcon') || this.getIcon(this, 'itemIcon'),
        expandIcon: this.getIcon(child, 'expandIcon') || this.getIcon(this, 'expandIcon')
      }, extraProps), {}, {
        onClick: function onClick(e) {
          (childProps.onClick || _util.noop)(e);

          _this.onClick(e);
        },
        onItemHover: this.onItemHover,
        onOpenChange: this.onOpenChange,
        onDeselect: this.onDeselect,
        // destroy: this.onDestroy,
        onSelect: this.onSelect
      }); // ref: https://github.com/ant-design/ant-design/issues/13943


      if (props.mode === 'inline' || (0, _util.isMobileDevice)()) {
        newChildProps.triggerSubMenuAction = 'click';
      }

      return (0, _vnode.cloneElement)(child, newChildProps);
    },
    renderMenuItem: function renderMenuItem(c, i, subMenuKey) {
      if (!c) {
        return null;
      }

      var state = this.$props.store.getState();
      var extraProps = {
        openKeys: state.openKeys,
        selectedKeys: state.selectedKeys,
        triggerSubMenuAction: this.triggerSubMenuAction,
        isRootMenu: false,
        subMenuKey: subMenuKey
      };
      return this.renderCommonMenuItem(c, i, extraProps);
    }
  },
  render: function render() {
    var _this2 = this;

    var props = _objectSpread({}, this.$props);

    var _splitAttrs = (0, _propsUtil.splitAttrs)(this.$attrs),
        onEvents = _splitAttrs.onEvents,
        extraAttrs = _splitAttrs.extraAttrs;

    var eventKey = props.eventKey,
        prefixCls = props.prefixCls,
        visible = props.visible,
        level = props.level,
        mode = props.mode,
        theme = props.theme;
    this.instanceArray = [];
    this.instanceArrayKeyIndexMap = {};
    var className = (0, _classNames.default)(extraAttrs.class, props.prefixCls, "".concat(props.prefixCls, "-").concat(props.mode));

    _util.menuAllProps.forEach(function (key) {
      return delete props[key];
    }); // Otherwise, the propagated click event will trigger another onClick


    delete onEvents.onClick;

    var domWrapProps = _objectSpread(_objectSpread({}, props), {}, {
      tag: 'ul',
      // hiddenClassName: `${prefixCls}-hidden`,
      visible: visible,
      prefixCls: prefixCls,
      level: level,
      mode: mode,
      theme: theme,
      overflowedIndicator: (0, _propsUtil.getComponent)(this, 'overflowedIndicator'),
      role: props.role || 'menu',
      class: className,
      style: extraAttrs.style
    }, onEvents);

    if (extraAttrs.id !== undefined) {
      domWrapProps.id = extraAttrs.id;
    }

    if (props.focusable) {
      domWrapProps.tabindex = '0';
      domWrapProps.onKeydown = this.onKeyDown;
    }

    delete domWrapProps.children;
    return (// ESLint is not smart enough to know that the type of `children` was checked.

      /* eslint-disable */
      _vue.createVNode(_DOMWrap.default, domWrapProps, {
        default: function _default() {
          return [props.children.map(function (c, i) {
            return _this2.renderMenuItem(c, i, eventKey || '0-menu-');
          })];
        }
      })
      /*eslint -enable */

    );
  }
};

var _default2 = (0, _store.connect)()(SubPopupMenu);

exports.default = _default2;