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

import React, { Children } from 'react';
import { findDOMNode } from 'react-dom';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { func, dom, events } from '../util';
import Menu from '../menu';
import Overlay from '../overlay';
import Loading from '../loading';
import zhCN from '../locale/zh-cn';
import DataStore from './data-store';
import VirtualList from '../virtual-list';
import { isSingle, filter, isNull, valueToSelectKey } from './util';
var Popup = Overlay.Popup;
var MenuItem = Menu.Item,
    MenuGroup = Menu.Group;
var noop = func.noop,
    makeChain = func.makeChain;

function preventDefault(e) {
  e.preventDefault();
}

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

  function Base(_props2) {
    var _this;

    _classCallCheck(this, Base);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(Base).call(this, _props2));

    _defineProperty(_assertThisInitialized(_this), "syncWidth", function () {
      var width = dom.getStyle(_this.selectDOM, 'width');

      if (width && _this.width !== width) {
        _this.width = width;

        if (_this.popupRef && _this.props.autoWidth) {
          // overy 的 node 节点可能没有挂载完成，所以这里需要异步
          setTimeout(function () {
            if (_this.popupRef && _this.popupRef.getInstance().overlay) {
              dom.setStyle(_this.popupRef.getInstance().overlay.getInstance().getContentNode(), 'width', _this.width); // 更新下Menu的宽度

              _this.forceUpdate();
            }
          }, 0);
        }
      }
    });

    _defineProperty(_assertThisInitialized(_this), "handleResize", function () {
      clearTimeout(_this.resizeTimeout);

      if (_this.state.visible) {
        _this.resizeTimeout = setTimeout(function () {
          _this.syncWidth();
        }, 200);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "setDataSource", function (props) {
      var dataSource = props.dataSource,
          children = props.children; // children is higher priority then dataSource

      if (Children.count(children)) {
        return _this.dataStore.updateByDS(children, true);
      } else if (Array.isArray(dataSource)) {
        return _this.dataStore.updateByDS(dataSource, false);
      }

      return [];
    });

    _defineProperty(_assertThisInitialized(_this), "setVisible", function (visible, type) {
      if (_this.props.disabled || _this.state.visible === visible) {
        return;
      }

      if (!('visible' in _this.props)) {
        _this.setState({
          visible: visible
        });
      }

      if (!_this.props.visible && visible) {
        // 当面板由收起到展开时，面板显示完整的数据（无过滤效果）
        _this.setState({
          dataSource: _this.dataStore.getOriginDS()
        }); // 更新菜单数据


        _this.dataStore.updateByKey('');
      }

      _this.props.onVisibleChange(visible, type);
    });

    _defineProperty(_assertThisInitialized(_this), "setFirstHightLightKeyForMenu", function () {
      // 设置高亮 item key
      if (_this.dataStore.getMenuDS().length && _this.dataStore.getEnableDS().length) {
        _this.setState({
          highlightKey: "".concat(_this.dataStore.getEnableDS()[0].value)
        });
      }
    });

    _defineProperty(_assertThisInitialized(_this), "handleChange", function (value) {
      var _this$props;

      // 非受控模式清空内部数据
      if (!('value' in _this.props)) {
        _this.setState({
          value: value
        });
      }

      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }

      (_this$props = _this.props).onChange.apply(_this$props, [value].concat(args));
    });

    _defineProperty(_assertThisInitialized(_this), "handleMenuBodyClick", function (e) {
      _this.focusInput(e);
    });

    _defineProperty(_assertThisInitialized(_this), "toggleHighlightItem", function (dir) {
      if (!_this.state.visible) {
        _this.setVisible(true, 'enter');

        return;
      }

      var maxCount = _this.dataStore.getEnableDS().length; // When there is no enabled item


      if (!maxCount) {
        return false;
      }

      var highlightKey = _this.state.highlightKey;
      var highlightIndex = -1; // find previous highlight index

      highlightKey !== null && _this.dataStore.getEnableDS().some(function (item, index) {
        if ("".concat(item.value) === highlightKey) {
          highlightIndex = index;
        }

        return highlightIndex > -1;
      }); // toggle highlight index

      highlightIndex += dir;

      if (highlightIndex < 0) {
        highlightIndex = maxCount - 1;
      }

      if (highlightIndex >= maxCount) {
        highlightIndex = 0;
      } // get highlight key


      var highlightItem = _this.dataStore.getEnableDS()[highlightIndex];

      highlightKey = highlightItem ? "".concat(highlightItem.value) : null;

      _this.setState({
        highlightKey: highlightKey,
        srReader: highlightItem.label
      });

      _this.scrollMenuIntoView();

      return highlightItem;
    });

    _defineProperty(_assertThisInitialized(_this), "scrollMenuIntoView", function () {
      var prefix = _this.props.prefix;
      clearTimeout(_this.highlightTimer);
      _this.highlightTimer = setTimeout(function () {
        try {
          var menuNode = findDOMNode(_this.menuRef);
          var itemNode = menuNode.querySelector(".".concat(prefix, "select-menu-item.").concat(prefix, "focused"));
          itemNode && itemNode.scrollIntoViewIfNeeded();
        } catch (ex) {// I don't care...
        }
      });
    });

    _defineProperty(_assertThisInitialized(_this), "renderMenuHeader", function () {
      return null;
    });

    _defineProperty(_assertThisInitialized(_this), "renderMenuFooter", function () {
      var _this$props2 = _this.props,
          useVirtual = _this$props2.useVirtual,
          footer = _this$props2.footer;
      return !useVirtual ? footer : null;
    });

    _defineProperty(_assertThisInitialized(_this), "handleSelect", function () {});

    _defineProperty(_assertThisInitialized(_this), "renderMenu", function () {
      var _classNames;

      var _this$props3 = _this.props,
          prefix = _this$props3.prefix,
          mode = _this$props3.mode,
          autoWidth = _this$props3.autoWidth,
          locale = _this$props3.locale,
          notFoundContent = _this$props3.notFoundContent,
          useVirtual = _this$props3.useVirtual,
          onPopupScroll = _this$props3.onPopupScroll;
      var _this$state = _this.state,
          dataSource = _this$state.dataSource,
          highlightKey = _this$state.highlightKey;
      var value = _this.state.value;
      var selectedKeys;

      if (isNull(value) || value.length === 0) {
        selectedKeys = [];
      } else if (isSingle(mode)) {
        selectedKeys = [valueToSelectKey(value)];
      } else {
        selectedKeys = [].concat(value).map(function (n) {
          return valueToSelectKey(n);
        });
      }

      var children = _this.renderMenuItem(dataSource);

      var menuClassName = classNames((_classNames = {}, _defineProperty(_classNames, "".concat(prefix, "select-menu"), true), _defineProperty(_classNames, "".concat(prefix, "select-menu-empty"), !children || !children.length), _classNames));

      if (!children || !children.length) {
        children = React.createElement("span", {
          className: "".concat(prefix, "select-menu-empty-content")
        }, notFoundContent || locale.notFoundContent);
      }

      var menuProps = {
        children: children,
        role: 'listbox',
        style: autoWidth ? {
          width: _this.width
        } : {
          minWidth: _this.width
        },
        selectedKeys: selectedKeys,
        focusedKey: highlightKey,
        focusable: false,
        selectMode: isSingle(mode) ? 'single' : 'multiple',
        onSelect: _this.handleMenuSelect,
        onItemClick: _this.handleItemClick,
        header: _this.renderMenuHeader(),
        footer: _this.renderMenuFooter(),
        onClick: _this.handleMenuBodyClick,
        onMouseDown: preventDefault,
        className: menuClassName,
        onScroll: onPopupScroll
      };
      return useVirtual && children.length ? React.createElement("div", {
        className: "".concat(prefix, "select-menu-wrapper"),
        style: {
          position: 'relative'
        }
      }, React.createElement(VirtualList, {
        itemsRenderer: function itemsRenderer(items, _ref) {
          return React.createElement(Menu, _extends({
            ref: function ref(c) {
              _ref(c);

              _this.menuRef = c;
            }
          }, menuProps), items);
        }
      }, children)) : React.createElement(Menu, _extends({
        ref: function ref(c) {
          _this.menuRef = c;
        }
      }, menuProps));
    });

    _defineProperty(_assertThisInitialized(_this), "renderMenuItem", function (dataSource) {
      var _this$props4 = _this.props,
          prefix = _this$props4.prefix,
          itemRender = _this$props4.itemRender; // If it has.

      var searchKey;

      if (_this.isAutoComplete) {
        // In AutoComplete, value is the searchKey
        searchKey = _this.state.value;
      } else {
        searchKey = _this.state.searchValue;
      }

      return dataSource.map(function (item, index) {
        if (!item) {
          return null;
        }

        if (Array.isArray(item.children)) {
          return React.createElement(MenuGroup, {
            key: index,
            label: item.label
          }, _this.renderMenuItem(item.children));
        } else {
          var itemProps = {
            role: 'option',
            key: item.value,
            className: "".concat(prefix, "select-menu-item"),
            disabled: item.disabled
          };

          if (item.title) {
            itemProps.title = item.title;
          }

          return React.createElement(MenuItem, itemProps, itemRender(item, searchKey));
        }
      });
    });

    _defineProperty(_assertThisInitialized(_this), "saveSelectRef", function (ref) {
      _this.selectDOM = findDOMNode(ref);
    });

    _defineProperty(_assertThisInitialized(_this), "saveInputRef", function (ref) {
      if (ref && ref.getInstance()) {
        _this.inputRef = ref.getInstance();
      }
    });

    _defineProperty(_assertThisInitialized(_this), "focusInput", function () {
      _this.inputRef && _this.inputRef.focus();
    });

    _defineProperty(_assertThisInitialized(_this), "beforeOpen", function () {
      var _this$state2 = _this.state,
          value = _this$state2.value,
          highlightKey = _this$state2.highlightKey;

      if (_this.props.mode === 'single' && !value && !highlightKey) {
        _this.setFirstHightLightKeyForMenu();
      }

      _this.syncWidth();
    });

    _defineProperty(_assertThisInitialized(_this), "beforeClose", function () {});

    _defineProperty(_assertThisInitialized(_this), "afterClose", function () {});

    _defineProperty(_assertThisInitialized(_this), "savePopupRef", function (ref) {
      _this.popupRef = ref;

      if (_this.props.popupProps && typeof _this.props.popupProps.ref === 'function') {
        _this.props.popupProps.ref(ref);
      }
    });

    _this.dataStore = new DataStore({
      filter: _props2.filter,
      filterLocal: _props2.filterLocal
    });
    _this.state = {
      value: 'value' in _props2 ? _props2.value : _props2.defaultValue,
      visible: 'visible' in _props2 ? _props2.visible : _props2.defaultVisible,
      dataSource: [],
      width: 100,
      // current highlight key
      highlightKey: null,
      srReader: ''
    };
    return _this;
  }

  _createClass(Base, [{
    key: "UNSAFE_componentWillMount",
    value: function UNSAFE_componentWillMount() {
      this.setState({
        dataSource: this.setDataSource(this.props)
      });
    }
  }, {
    key: "componentDidMount",
    value: function componentDidMount() {
      var _this2 = this;

      // overlay 还没有完成 mount，所以需要滞后同步宽度
      setTimeout(function () {
        return _this2.syncWidth();
      }, 0);
      events.on(window, 'resize', this.handleResize);
    }
  }, {
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps, prevState) {
      if (prevProps.label !== this.props.label || prevState.value !== this.state.value) {
        this.syncWidth();
      }
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      events.off(window, 'resize', this.handleResize);
      clearTimeout(this.resizeTimeout);
    }
    /**
     * Calculate and set width of popup menu
     * @protected
     */

  }, {
    key: "render",
    value: function render() {
      var _classNames2;

      var _this$props5 = this.props,
          prefix = _this$props5.prefix,
          mode = _this$props5.mode,
          state = _this$props5.state,
          popupProps = _this$props5.popupProps,
          popupContainer = _this$props5.popupContainer,
          popupClassName = _this$props5.popupClassName,
          popupStyle = _this$props5.popupStyle,
          popupContent = _this$props5.popupContent,
          autoWidth = _this$props5.autoWidth,
          canCloseByTrigger = _this$props5.canCloseByTrigger,
          followTrigger = _this$props5.followTrigger,
          cache = _this$props5.cache,
          showEmpty = _this$props5.showEmpty;
      var cls = classNames((_classNames2 = {}, _defineProperty(_classNames2, "".concat(prefix, "select-auto-complete-menu"), !popupContent && this.isAutoComplete), _defineProperty(_classNames2, "".concat(prefix, "select-").concat(mode, "-menu"), !popupContent && !!mode), _classNames2), popupClassName || popupProps.className);

      var _props = _objectSpread({
        offset: [0, 4],
        animation: {
          "in": 'fadeInDown',
          out: 'fadeOutUp'
        },
        triggerType: 'click',
        autoFocus: false,
        cache: cache
      }, popupProps, {
        // beforeOpen node not mount, afterOpen too slow.
        // from display:none to block, we may need to recompute width
        beforeOpen: makeChain(this.beforeOpen, popupProps.beforeOpen),
        beforeClose: makeChain(this.beforeClose, popupProps.beforeClose),
        afterClose: makeChain(this.afterClose, popupProps.afterClose),
        canCloseByTrigger: canCloseByTrigger,
        followTrigger: followTrigger,
        visible: this.state.visible,
        onVisibleChange: this.handleVisibleChange,
        shouldUpdatePosition: true,
        container: popupContainer || popupProps.container,
        className: cls,
        style: popupStyle || popupProps.style
      }); // 用于 Search 不显示弹出层


      if (!showEmpty) {
        return this.renderSelect();
      }

      return React.createElement(Popup, _extends({}, _props, {
        trigger: this.renderSelect(),
        ref: this.savePopupRef
      }), React.createElement(Loading, {
        className: "".concat(prefix, "select-loading"),
        visible: state === 'loading'
      }, popupContent ? React.createElement("div", {
        className: "".concat(prefix, "select-popup-wrap"),
        style: autoWidth ? {
          width: this.width
        } : {}
      }, popupContent) : this.renderMenu()));
    }
  }]);

  return Base;
}(React.Component);

_defineProperty(Base, "propTypes", {
  prefix: PropTypes.string,

  /**
   * 选择器尺寸
   */
  size: PropTypes.oneOf(['xs', 'small', 'medium']),
  // 当前值，用于受控模式
  value: PropTypes.any,
  // to be override
  // 初始化的默认值
  defaultValue: PropTypes.any,
  // to be override

  /**
   * 没有值的时候的占位符
   */
  placeholder: PropTypes.string,

  /**
   * 下拉菜单是否与选择器对齐
   */
  autoWidth: PropTypes.bool,

  /**
   * 自定义内联 label
   */
  label: PropTypes.node,

  /**
   * 是否有清除按钮（单选模式有效）
   */
  hasClear: PropTypes.bool,

  /**
   * 校验状态
   */
  state: PropTypes.oneOf(['error', 'loading']),

  /**
   * 是否只读，只读模式下可以展开弹层但不能选
   */
  readOnly: PropTypes.bool,

  /**
   * 是否禁用选择器
   */
  disabled: PropTypes.bool,

  /**
   * 当前弹层是否显示
   */
  visible: PropTypes.bool,

  /**
   * 弹层初始化是否显示
   */
  defaultVisible: PropTypes.bool,

  /**
   * 弹层显示或隐藏时触发的回调
   * @param {Boolean} visible 弹层是否显示
   * @param {String} type 触发弹层显示或隐藏的来源 fromContent 表示由Dropdown内容触发； fromTrigger 表示由trigger的点击触发； docClick 表示由document的点击触发
   */
  onVisibleChange: PropTypes.func,

  /**
   * value变化时回调
   */
  onChange: PropTypes.func,

  /**
   * 弹层挂载的容器节点
   */
  popupContainer: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),

  /**
   * 弹层的 className
   */
  popupClassName: PropTypes.any,

  /**
   * 弹层的内联样式
   */
  popupStyle: PropTypes.object,

  /**
   * 添加到弹层上的属性
   */
  popupProps: PropTypes.object,

  /**
   * 是否跟随滚动
   */
  followTrigger: PropTypes.bool,

  /**
   * 自定义弹层的内容
   */
  popupContent: PropTypes.node,

  /**
   * 是否使用本地过滤，在数据源为远程的时候需要关闭此项
   */
  filterLocal: PropTypes.bool,

  /**
   * 本地过滤方法，返回一个 Boolean 值确定是否保留
   */
  filter: PropTypes.func,

  /**
   * 键盘上下键切换菜单高亮选项的回调
   */
  onToggleHighlightItem: PropTypes.func,

  /**
   * 是否开启虚拟滚动模式
   */
  useVirtual: PropTypes.bool,
  // 自定义类名
  className: PropTypes.any,
  children: PropTypes.any,
  dataSource: PropTypes.array,
  itemRender: PropTypes.func,

  /**
   * 弹层菜单footer
   */
  footer: PropTypes.node,
  mode: PropTypes.string,
  notFoundContent: PropTypes.node,

  /**
   * 内容为空是否显示弹层
   */
  showEmpty: PropTypes.bool,
  locale: PropTypes.object,
  rtl: PropTypes.bool,

  /**
   * 监听滚动事件
   */
  onPopupScroll: PropTypes.func
});

_defineProperty(Base, "defaultProps", {
  prefix: 'next-',
  size: 'medium',
  autoWidth: true,
  onChange: noop,
  onVisibleChange: noop,
  onToggleHighlightItem: noop,
  popupProps: {},
  filterLocal: true,
  filter: filter,
  itemRender: function itemRender(item) {
    return item.label || item.value;
  },
  locale: zhCN.Select,
  showEmpty: true
});

export { Base as default };