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 _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 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 _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 _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }

function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }

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

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 from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { func, obj, KEYCODE } from '../util';
import Input from '../input';
import Base from './base';
var noop = func.noop;
/**
 * Select.AutoComplete
 */

var AutoComplete =
/*#__PURE__*/
function (_Base) {
  _inherits(AutoComplete, _Base);

  function AutoComplete(_props) {
    var _this;

    _classCallCheck(this, AutoComplete);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(AutoComplete).call(this, _props));

    _defineProperty(_assertThisInitialized(_this), "shouldControlPopup", function () {
      var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.props;
      var type = arguments.length > 1 ? arguments[1] : undefined;

      var hasPopup = props.popupContent || _this.dataStore.getMenuDS().length;

      if (hasPopup) {
        _this.setVisible(true, type);
      } else {
        _this.setVisible(false, type);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "handleMenuSelect", function (keys) {
      var key = keys[0];

      if (_this.state.value === keys[0]) {
        return _this.setVisible(false, 'itemClick');
      }

      var mapDS = _this.dataStore.getMapDS();

      if (key in mapDS) {
        var item = mapDS[key];

        _this.handleSelectEvent(key, item, 'itemClick');
      }
    });

    _defineProperty(_assertThisInitialized(_this), "handleItemClick", function () {
      _this.setVisible(false, 'itemClick');
    });

    _defineProperty(_assertThisInitialized(_this), "handleSelectEvent", function (key, item, triggerType) {
      var value = item && item[_this.props.fillProps] || key;

      if (triggerType === 'itemClick' || triggerType === 'enter') {
        // 点击 item 的时候不会触发关闭，需要手动关闭，其它类型比如 keyDown 等都会有其它事件句柄处理
        _this.setVisible(false, triggerType);
      }

      _this.handleChange(value, triggerType, item);
    });

    _defineProperty(_assertThisInitialized(_this), "handleChange", function (value, proxy, item) {
      var _this$props = _this.props,
          disabled = _this$props.disabled,
          readOnly = _this$props.readOnly,
          filterLocal = _this$props.filterLocal;

      if (disabled || readOnly) {
        return false;
      }

      var actionType = typeof proxy === 'string' ? proxy : 'change';
      _this.isInputing = actionType === 'change';

      if (filterLocal) {
        _this.setState({
          dataSource: _this.dataStore.updateByKey(value)
        });

        _this.shouldControlPopup(_this.props, actionType);

        _this.setFirstHightLightKeyForMenu();
      } // 非受控模式清空内部数据


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

      _this.props.onChange(value, actionType, item);

      if (actionType === 'itemClick' || actionType === 'enter') {
        // 点击 item 的时候不会触发关闭，需要手动关闭，其它类型比如 keyDown 等都会有其它事件句柄处理
        _this.setVisible(false, actionType);
      }
    });

    _defineProperty(_assertThisInitialized(_this), "handleVisibleChange", function (visible, type) {
      // 去掉这段逻辑，统一由base.jsx中的setVisible进行处理
      // if (
      //   !('visible' in this.props) &&
      //   visible &&
      //   !this.props.popupContent &&
      //   !this.dataStore.getMenuDS().length
      // ) {
      //   return;
      // }
      _this.setVisible(visible, type);
    });

    _defineProperty(_assertThisInitialized(_this), "beforeClose", function () {
      _this.isInputing = false; // 清空选项的获焦状态

      _this.setState({
        highlightKey: ''
      });
    });

    _defineProperty(_assertThisInitialized(_this), "handleTriggerKeyDown", function (e) {
      var _this$props2 = _this.props,
          popupContent = _this$props2.popupContent,
          onToggleHighlightItem = _this$props2.onToggleHighlightItem,
          onKeyDown = _this$props2.onKeyDown;

      if (popupContent) {
        // stopPropagation can make use onChange triggerd while typing space('') in Input
        e.stopPropagation();
        return onKeyDown(e);
      }

      switch (e.keyCode) {
        case KEYCODE.UP:
          e.preventDefault();
          onToggleHighlightItem(_this.toggleHighlightItem(-1, e), 'up');
          break;

        case KEYCODE.DOWN:
          e.preventDefault();
          onToggleHighlightItem(_this.toggleHighlightItem(1, e), 'down');
          break;

        case KEYCODE.ENTER:
          e.preventDefault();

          _this.chooseHighlightItem(e);

          break;

        case KEYCODE.SPACE:
          // stopPropagation can make use onChange triggerd while typing space('') in Input
          e.stopPropagation();
          break;

        case KEYCODE.ESC:
          e.preventDefault();
          _this.state.visible && _this.setVisible(false, 'esc');
          break;

        default:
          break;
      }

      onKeyDown(e);
    });

    _defineProperty(_assertThisInitialized(_this), "chooseHighlightItem", function () {
      if (!_this.state.visible) {
        return false;
      }

      var highlightKey = _this.state.highlightKey;

      var highlightItem = _this.dataStore.getEnableDS().find(function (item) {
        return highlightKey === "".concat(item.value);
      });

      if (highlightItem) {
        _this.handleSelectEvent(highlightKey, highlightItem, 'enter');
      }
    });

    _defineProperty(_assertThisInitialized(_this), "hasClear", function () {
      var _this$props3 = _this.props,
          hasClear = _this$props3.hasClear,
          readOnly = _this$props3.readOnly,
          disabled = _this$props3.disabled;
      var value = _this.state.value;
      return value && hasClear && !readOnly && !disabled;
    });

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

      var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : _this.props;
      var placeholder = props.placeholder,
          size = props.size,
          prefix = props.prefix,
          className = props.className,
          style = props.style,
          label = props.label,
          readOnly = props.readOnly,
          disabled = props.disabled,
          highlightHolder = props.highlightHolder,
          locale = props.locale,
          hasClear = props.hasClear,
          state = props.state,
          rtl = props.rtl;
      var others = obj.pickOthers(AutoComplete.propTypes, props);
      var othersData = obj.pickAttrsWith(others, 'data-');
      var value = _this.state.value;
      var visible = _this.state.visible; // // 下拉箭头
      // const arrowNode = this.renderArrowNode(props, () => {
      //     this.focusInput();
      //     this.setVisible(!this.state.visible);
      // });
      // trigger className

      var triggerClazz = classNames(["".concat(prefix, "select"), "".concat(prefix, "select-auto-complete"), "".concat(prefix, "size-").concat(size), className], (_classNames = {}, _defineProperty(_classNames, "".concat(prefix, "active"), visible), _defineProperty(_classNames, "".concat(prefix, "disabled"), disabled), _classNames)); // highlightKey into placeholder
      // compatible with selectPlaceHolder. TODO: removed in 2.0 version

      var _placeholder = placeholder || locale.autoCompletePlaceholder || locale.autoCompletePlaceHolder;

      if (highlightHolder && visible) {
        _placeholder = _this.state.highlightKey || _placeholder;
      } // Input props
      // state 为loading时效果转到弹层面板中


      var _inputProps = _objectSpread({}, obj.pickOthers(othersData, others), {
        state: state === 'loading' ? undefined : state,
        ref: _this.saveInputRef,
        hasClear: hasClear,
        value: value,
        size: size,
        disabled: disabled,
        readOnly: readOnly,
        placeholder: _placeholder,
        label: label,
        // extra: arrowNode,
        onChange: _this.handleChange,
        onKeyDown: _this.handleTriggerKeyDown
      });

      return React.createElement("span", _extends({}, othersData, {
        className: triggerClazz,
        style: style,
        dir: rtl ? 'rtl' : undefined,
        ref: _this.saveSelectRef,
        onClick: _this.focusInput
      }), React.createElement(Input, _extends({
        role: "combobox",
        "aria-autocomplete": "list",
        "aria-disabled": disabled,
        "aria-expanded": _this.state.visible
      }, _inputProps)), React.createElement("span", {
        className: "".concat(prefix, "sr-only"),
        "aria-live": "polite"
      }, _this.state.srReader));
    });

    _this.isAutoComplete = true;
    _this.isInputing = false;
    return _this;
  }

  _createClass(AutoComplete, [{
    key: "UNSAFE_componentWillMount",
    value: function UNSAFE_componentWillMount() {
      this.dataStore.setOptions({
        key: this.state.value
      });

      if (_get(_getPrototypeOf(AutoComplete.prototype), "UNSAFE_componentWillMount", this)) {
        _get(_getPrototypeOf(AutoComplete.prototype), "UNSAFE_componentWillMount", this).call(this);
      }
    }
  }, {
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(nextProps) {
      if ('value' in nextProps) {
        this.dataStore.setOptions({
          key: nextProps.value
        });
        this.setState({
          value: nextProps.value
        });
      }

      if ('visible' in nextProps) {
        this.setState({
          visible: nextProps.visible
        });
      }

      this.dataStore.setOptions({
        filter: nextProps.filter,
        filterLocal: nextProps.filterLocal
      });

      if (nextProps.children !== this.props.children || nextProps.dataSource !== this.props.dataSource) {
        var dataSource = this.setDataSource(nextProps);
        this.setState({
          dataSource: dataSource
        });
      } // remote dataSource and focused
      // 因为autoComplete没有下拉数据不展示，搜索并且有数据了需要自动展示下拉


      if (!nextProps.filterLocal && this.isInputing) {
        this.shouldControlPopup(nextProps, 'update');
      }

      if (!nextProps.filterLocal && !nextProps.popupContent) {
        this.setFirstHightLightKeyForMenu();
      }

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

        this.dataStore.updateByKey('');
      }
    }
  }, {
    key: "UNSAFE_componentWillUpdate",
    value: function UNSAFE_componentWillUpdate() {
      if (this.hasClear()) {
        var inputNode = ReactDOM.findDOMNode(this.inputRef);

        if (inputNode) {
          this.clearNode = inputNode.querySelector(".".concat(this.props.prefix, "input-control"));
        }
      }
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      if (this.hasClear()) {
        // clear 按钮点击后，会在 dom 结构中被删除掉，需要将其额外设置为安全节点，防止触发弹层的显示或隐藏
        var safeNode = this.props.popupProps.safeNode || [];
        var safeNodes = Array.isArray(safeNode) ? safeNode : [safeNode];
        safeNodes.push(function () {
          return _this2.clearNode;
        });
        this.props.popupProps.safeNode = safeNodes;
      }

      return _get(_getPrototypeOf(AutoComplete.prototype), "render", this).call(this, _extends({}, this.props, {
        canCloseByTrigger: false
      }));
    }
  }]);

  return AutoComplete;
}(Base);

_defineProperty(AutoComplete, "propTypes", _objectSpread({}, Base.propTypes, {
  /**
   * 当前值，用于受控模式
   */
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

  /**
   * 初始化的默认值
   */
  defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

  /**
   * Select发生改变时触发的回调
   * @param {*} value 选中的值
   * @param {String} actionType 触发的方式, 'itemClick', 'enter', 'change'
   * @param {*} item 选中的值的对象数据
   */
  onChange: PropTypes.func,

  /**
   * 传入的数据源，可以动态渲染子项
   */
  dataSource: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({
    value: PropTypes.string,
    label: PropTypes.any,
    disabled: PropTypes.bool,
    children: PropTypes.array
  }), PropTypes.string])),

  /**
   * 填充到选择框里的值的 key，默认是 value
   */
  fillProps: PropTypes.string,

  /**
   * 渲染 MenuItem 内容的方法
   * @param {Object} item 渲染节点的 item
   * @return {ReactNode} item node
   */
  itemRender: PropTypes.func,
  // input keydown
  onKeyDown: PropTypes.func,
  // 是否将当前高亮的选项作为 placeholder
  highlightHolder: PropTypes.bool,
  style: PropTypes.object
}));

_defineProperty(AutoComplete, "defaultProps", _objectSpread({}, Base.defaultProps, {
  onKeyDown: noop,
  fillProps: 'value'
}));

export default AutoComplete;