"use strict";

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

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

Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "TransferDirection", {
  enumerable: true,
  get: function get() {
    return _enum.TransferDirection;
  }
});
exports["default"] = void 0;

var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));

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

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 _tslib = require("tslib");

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

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

var _mobx = require("mobx");

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

var _scrollIntoViewIfNeeded = _interopRequireDefault(require("scroll-into-view-if-needed"));

var _utils = require("../../pro/lib/data-set/utils");

var _list = _interopRequireDefault(require("./list"));

var _operation = _interopRequireDefault(require("./operation"));

var _SortButton = _interopRequireDefault(require("./SortButton"));

var _search = _interopRequireDefault(require("./search"));

var _LocaleReceiver = _interopRequireDefault(require("../locale-provider/LocaleReceiver"));

var _default = _interopRequireDefault(require("../locale-provider/default"));

var _enum = require("./enum");

var _ConfigContext = _interopRequireDefault(require("../config-provider/ConfigContext"));

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

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

  function Transfer(props) {
    var _this;

    (0, _classCallCheck2["default"])(this, Transfer);
    _this = _super.call(this, props);
    _this.splitedDataSource = null;
    _this.transferRef = null;

    _this.moveTo = function (direction) {
      var _this$setState;

      var _this$props = _this.props,
          _this$props$targetKey = _this$props.targetKeys,
          targetKeys = _this$props$targetKey === void 0 ? [] : _this$props$targetKey,
          _this$props$dataSourc = _this$props.dataSource,
          dataSource = _this$props$dataSourc === void 0 ? [] : _this$props$dataSourc,
          onChange = _this$props.onChange;
      var _this$state = _this.state,
          sourceSelectedKeys = _this$state.sourceSelectedKeys,
          targetSelectedKeys = _this$state.targetSelectedKeys;
      var moveKeys = direction === _enum.TransferDirection.right ? sourceSelectedKeys : targetSelectedKeys; // filter the disabled options

      var newMoveKeys = moveKeys.filter(function (key) {
        return !dataSource.some(function (data) {
          return !!(key === data.key && data.disabled);
        });
      }); // move items to target box

      var newTargetKeys = direction === _enum.TransferDirection.right ? newMoveKeys.concat(targetKeys) : targetKeys.filter(function (targetKey) {
        return newMoveKeys.indexOf(targetKey) === -1;
      }); // empty checked keys

      var oppositeDirection = direction === _enum.TransferDirection.right ? _enum.TransferDirection.left : _enum.TransferDirection.right;

      _this.setState((_this$setState = {}, (0, _defineProperty2["default"])(_this$setState, _this.getSelectedKeysName(oppositeDirection), []), (0, _defineProperty2["default"])(_this$setState, "sortKeys", null), (0, _defineProperty2["default"])(_this$setState, "highlightKey", ''), _this$setState));

      _this.handleSelectChange(oppositeDirection, []);

      if (onChange) {
        onChange(newTargetKeys, direction, newMoveKeys);
      }
    };

    _this.sortTo = function (direction) {
      var customizePrefixCls = _this.props.prefixCls;
      var highlightKey = _this.state.highlightKey;
      var to = direction === _enum.TransferDirection.up ? -1 : 1;

      var _this$splitDataSource = _this.splitDataSource(),
          rightDataSource = _this$splitDataSource.rightDataSource;

      var mapRightKey = rightDataSource.map(function (x) {
        return x.key;
      });
      var filterRightDataSource = _this.computedRightDataSource;
      var filterCurrentIndex = filterRightDataSource.findIndex(function (x) {
        return x.key === highlightKey;
      });
      var sourceIndex = rightDataSource.findIndex(function (x) {
        return x.key === highlightKey;
      });
      var moveToOption = filterRightDataSource[filterCurrentIndex + to];
      var moveToIndex = rightDataSource.findIndex(function (x) {
        return x.key === moveToOption.key;
      });
      (0, _utils.arrayMove)(mapRightKey, sourceIndex, moveToIndex);
      _this.splitedDataSource = null;

      _this.setState({
        sortKeys: mapRightKey
      }, function () {
        // 向下移动位置，滚动条跟随
        if (_this.transferRef) {
          var getPrefixCls = _this.context.getPrefixCls;
          var prefixCls = getPrefixCls('transfer', customizePrefixCls);
          var selectedCls = "".concat(prefixCls, "-list-content-item-highlight");

          var selectedDom = _this.transferRef.getElementsByClassName(selectedCls)[0];

          (0, _scrollIntoViewIfNeeded["default"])(selectedDom, {
            block: 'end',
            behavior: 'smooth',
            scrollMode: 'if-needed',
            boundary: _this.transferRef
          });
        }
      });
    };

    _this.moveToLeft = function () {
      return _this.moveTo(_enum.TransferDirection.left);
    };

    _this.moveToRight = function () {
      return _this.moveTo(_enum.TransferDirection.right);
    };

    _this.moveToUp = function () {
      return _this.sortTo(_enum.TransferDirection.up);
    };

    _this.moveToDown = function () {
      return _this.sortTo(_enum.TransferDirection.down);
    };

    _this.handleSelectAll = function (direction, filteredDataSource, checkAll) {
      var _assertThisInitialize = (0, _assertThisInitialized2["default"])(_this),
          state = _assertThisInitialize.state,
          selectedKeys = _assertThisInitialize.props.selectedKeys;

      var originalSelectedKeys = state[_this.getSelectedKeysName(direction)] || [];
      var currentKeys = filteredDataSource.map(function (item) {
        return item.key;
      }); // Only operate current keys from original selected keys

      var newKeys1 = originalSelectedKeys.filter(function (key) {
        return currentKeys.indexOf(key) === -1;
      });
      var newKeys2 = (0, _toConsumableArray2["default"])(originalSelectedKeys);
      currentKeys.forEach(function (key) {
        if (newKeys2.indexOf(key) === -1) {
          newKeys2.push(key);
        }
      });
      var holder = checkAll ? newKeys1 : newKeys2;

      _this.handleSelectChange(direction, holder);

      if (!selectedKeys) {
        _this.setState((0, _defineProperty2["default"])({}, _this.getSelectedKeysName(direction), holder));
      }
    };

    _this.handleLeftSelectAll = function (filteredDataSource, checkAll) {
      return _this.handleSelectAll(_enum.TransferDirection.left, filteredDataSource, checkAll);
    };

    _this.handleRightSelectAll = function (filteredDataSource, checkAll) {
      return _this.handleSelectAll(_enum.TransferDirection.right, filteredDataSource, checkAll);
    };

    _this.handleFilter = function (direction, e) {
      var onSearchChange = _this.props.onSearchChange;

      _this.setState((0, _defineProperty2["default"])({}, "".concat(direction, "Filter"), e.target.value));

      if (onSearchChange) {
        onSearchChange(direction, e);
      }
    };

    _this.handleLeftFilter = function (e) {
      return _this.handleFilter(_enum.TransferDirection.left, e);
    };

    _this.handleRightFilter = function (e) {
      return _this.handleFilter(_enum.TransferDirection.right, e);
    };

    _this.handleClear = function (direction) {
      _this.setState((0, _defineProperty2["default"])({}, "".concat(direction, "Filter"), ''));
    };

    _this.handleLeftClear = function () {
      return _this.handleClear(_enum.TransferDirection.left);
    };

    _this.handleRightClear = function () {
      return _this.handleClear(_enum.TransferDirection.right);
    };

    _this.handleSelect = function (direction, selectedItem, checked) {
      var selectedKeys = _this.props.selectedKeys;
      var _this$state2 = _this.state,
          sourceSelectedKeys = _this$state2.sourceSelectedKeys,
          targetSelectedKeys = _this$state2.targetSelectedKeys;
      var holder = direction === _enum.TransferDirection.left ? (0, _toConsumableArray2["default"])(sourceSelectedKeys) : (0, _toConsumableArray2["default"])(targetSelectedKeys);
      var index = holder.indexOf(selectedItem.key);

      if (index > -1) {
        holder.splice(index, 1);
      }

      if (checked) {
        holder.push(selectedItem.key);
      }

      _this.handleSelectChange(direction, holder);

      if (!selectedKeys) {
        _this.setState((0, _defineProperty2["default"])({}, _this.getSelectedKeysName(direction), holder));
      }

      if (direction === _enum.TransferDirection.right) {
        _this.setState({
          highlightKey: selectedItem.key
        });
      }
    };

    _this.handleLeftSelect = function (selectedItem, checked) {
      return _this.handleSelect(_enum.TransferDirection.left, selectedItem, checked);
    };

    _this.handleRightSelect = function (selectedItem, checked) {
      return _this.handleSelect(_enum.TransferDirection.right, selectedItem, checked);
    };

    _this.handleScroll = function (direction, e) {
      var onScroll = _this.props.onScroll;

      if (onScroll) {
        onScroll(direction, e);
      }
    };

    _this.handleLeftScroll = function (e) {
      return _this.handleScroll(_enum.TransferDirection.left, e);
    };

    _this.handleRightScroll = function (e) {
      return _this.handleScroll(_enum.TransferDirection.right, e);
    };

    _this.renderTransfer = function (locale) {
      var _this$props2 = _this.props,
          customizePrefixCls = _this$props2.prefixCls,
          className = _this$props2.className,
          _this$props2$operatio = _this$props2.operations,
          operations = _this$props2$operatio === void 0 ? [] : _this$props2$operatio,
          _this$props2$sortable = _this$props2.sortable,
          sortable = _this$props2$sortable === void 0 ? false : _this$props2$sortable,
          _this$props2$sortOper = _this$props2.sortOperations,
          sortOperations = _this$props2$sortOper === void 0 ? [] : _this$props2$sortOper,
          showSearch = _this$props2.showSearch,
          notFoundContent = _this$props2.notFoundContent,
          searchPlaceholder = _this$props2.searchPlaceholder,
          body = _this$props2.body,
          footer = _this$props2.footer,
          style = _this$props2.style,
          listStyle = _this$props2.listStyle,
          operationStyle = _this$props2.operationStyle,
          filterOption = _this$props2.filterOption,
          render = _this$props2.render,
          lazy = _this$props2.lazy,
          buttonProps = _this$props2.buttonProps,
          inputProps = _this$props2.inputProps,
          checkboxPrefixCls = _this$props2.checkboxPrefixCls;
      var getPrefixCls = _this.context.getPrefixCls;
      var prefixCls = getPrefixCls('transfer', customizePrefixCls);
      var _this$state3 = _this.state,
          leftFilter = _this$state3.leftFilter,
          rightFilter = _this$state3.rightFilter,
          sourceSelectedKeys = _this$state3.sourceSelectedKeys,
          targetSelectedKeys = _this$state3.targetSelectedKeys,
          highlightKey = _this$state3.highlightKey,
          sortKeys = _this$state3.sortKeys;

      var _this$splitDataSource2 = _this.splitDataSource(sortKeys),
          leftDataSource = _this$splitDataSource2.leftDataSource,
          rightDataSource = _this$splitDataSource2.rightDataSource;

      var leftActive = targetSelectedKeys.length > 0;
      var rightActive = sourceSelectedKeys.length > 0;
      var filterRightDataSource = _this.computedRightDataSource;
      var mapRightKey = filterRightDataSource.map(function (x) {
        return x.key;
      });
      var hasHighlight = !!highlightKey && mapRightKey.indexOf(highlightKey) > -1;
      var upActive = hasHighlight && mapRightKey.indexOf(highlightKey) !== 0;
      var downActive = hasHighlight && mapRightKey.indexOf(highlightKey) !== mapRightKey.length - 1;
      var cls = (0, _classnames["default"])(className, prefixCls);

      var titles = _this.getTitles(locale);

      return /*#__PURE__*/_react["default"].createElement("div", {
        className: cls,
        style: style,
        ref: function ref(dom) {
          _this.transferRef = dom;
        }
      }, /*#__PURE__*/_react["default"].createElement(_list["default"], {
        prefixCls: "".concat(prefixCls, "-list"),
        titleText: titles[0],
        dataSource: leftDataSource,
        filter: leftFilter,
        filterOption: filterOption,
        style: listStyle,
        checkedKeys: sourceSelectedKeys,
        handleFilter: _this.handleLeftFilter,
        handleClear: _this.handleLeftClear,
        handleSelect: _this.handleLeftSelect,
        handleSelectAll: _this.handleLeftSelectAll,
        render: render,
        showSearch: showSearch,
        searchPlaceholder: searchPlaceholder || locale.searchPlaceholder,
        notFoundContent: notFoundContent || locale.notFoundContent,
        itemUnit: locale.itemUnit,
        itemsUnit: locale.itemsUnit,
        body: body,
        footer: footer,
        lazy: lazy,
        onScroll: _this.handleLeftScroll,
        inputProps: inputProps,
        checkboxPrefixCls: checkboxPrefixCls
      }), /*#__PURE__*/_react["default"].createElement(_operation["default"], {
        className: "".concat(prefixCls, "-operation"),
        rightActive: rightActive,
        rightArrowText: operations[0],
        moveToRight: _this.moveToRight,
        leftActive: leftActive,
        leftArrowText: operations[1],
        moveToLeft: _this.moveToLeft,
        buttonProps: buttonProps,
        style: operationStyle
      }), /*#__PURE__*/_react["default"].createElement(_list["default"], {
        prefixCls: "".concat(prefixCls, "-list"),
        titleText: titles[1],
        dataSource: rightDataSource,
        filter: rightFilter,
        filterOption: filterOption,
        style: listStyle,
        checkedKeys: targetSelectedKeys,
        highlightKey: highlightKey,
        handleFilter: _this.handleRightFilter,
        handleClear: _this.handleRightClear,
        handleSelect: _this.handleRightSelect,
        handleSelectAll: _this.handleRightSelectAll,
        render: render,
        showSearch: showSearch,
        searchPlaceholder: searchPlaceholder || locale.searchPlaceholder,
        notFoundContent: notFoundContent || locale.notFoundContent,
        itemUnit: locale.itemUnit,
        itemsUnit: locale.itemsUnit,
        body: body,
        footer: footer,
        lazy: lazy,
        onScroll: _this.handleRightScroll,
        inputProps: inputProps,
        checkboxPrefixCls: checkboxPrefixCls
      }), !!sortable && /*#__PURE__*/_react["default"].createElement(_SortButton["default"], {
        className: "".concat(prefixCls, "-sort"),
        upActive: upActive,
        upArrowText: sortOperations[0],
        moveToUp: _this.moveToUp,
        downActive: downActive,
        downArrowText: sortOperations[1],
        moveToDown: _this.moveToDown
      }));
    };

    var _props$selectedKeys = props.selectedKeys,
        selectedKeys = _props$selectedKeys === void 0 ? [] : _props$selectedKeys,
        _props$targetKeys = props.targetKeys,
        targetKeys = _props$targetKeys === void 0 ? [] : _props$targetKeys;
    _this.state = {
      leftFilter: '',
      rightFilter: '',
      sourceSelectedKeys: selectedKeys.filter(function (key) {
        return targetKeys.indexOf(key) === -1;
      }),
      targetSelectedKeys: selectedKeys.filter(function (key) {
        return targetKeys.indexOf(key) > -1;
      }),
      highlightKey: '',
      sortKeys: null
    };
    return _this;
  }

  (0, _createClass2["default"])(Transfer, [{
    key: "componentWillReceiveProps",
    value: function componentWillReceiveProps(nextProps) {
      var _this$state4 = this.state,
          sourceSelectedKeys = _this$state4.sourceSelectedKeys,
          targetSelectedKeys = _this$state4.targetSelectedKeys;
      var props = this.props;

      if (nextProps.targetKeys !== props.targetKeys || nextProps.dataSource !== props.dataSource) {
        // clear cached separated dataSource
        this.splitedDataSource = null;

        if (!nextProps.selectedKeys) {
          // clear key no longer existed
          // clear checkedKeys according to targetKeys
          var dataSource = nextProps.dataSource,
              _nextProps$targetKeys = nextProps.targetKeys,
              targetKeys = _nextProps$targetKeys === void 0 ? [] : _nextProps$targetKeys;
          var newSourceSelectedKeys = [];
          var newTargetSelectedKeys = [];
          dataSource.forEach(function (_ref) {
            var key = _ref.key;

            if (sourceSelectedKeys.includes(key) && !targetKeys.includes(key)) {
              newSourceSelectedKeys.push(key);
            }

            if (targetSelectedKeys.includes(key) && targetKeys.includes(key)) {
              newTargetSelectedKeys.push(key);
            }
          });
          this.setState({
            sourceSelectedKeys: newSourceSelectedKeys,
            targetSelectedKeys: newTargetSelectedKeys
          });
        }
      }

      if (nextProps.selectedKeys) {
        var _targetKeys = nextProps.targetKeys || [];

        this.setState({
          sourceSelectedKeys: nextProps.selectedKeys.filter(function (key) {
            return !_targetKeys.includes(key);
          }),
          targetSelectedKeys: nextProps.selectedKeys.filter(function (key) {
            return _targetKeys.includes(key);
          })
        });
      }
    }
  }, {
    key: "splitDataSource",
    value: function splitDataSource(sortKeys) {
      if (this.splitedDataSource) {
        return this.splitedDataSource;
      }

      var _this$props3 = this.props,
          dataSource = _this$props3.dataSource,
          rowKey = _this$props3.rowKey,
          _this$props3$targetKe = _this$props3.targetKeys,
          targetKeys = _this$props3$targetKe === void 0 ? [] : _this$props3$targetKe;
      var useKeys = sortKeys || targetKeys;
      var leftDataSource = [];
      var rightDataSource = new Array(useKeys.length);
      dataSource.forEach(function (record) {
        if (rowKey) {
          record.key = rowKey(record);
        } // rightDataSource should be ordered by targetKeys
        // leftDataSource should be ordered by dataSource


        var indexOfKey = useKeys.indexOf(record.key);

        if (indexOfKey !== -1) {
          rightDataSource[indexOfKey] = record;
        } else {
          leftDataSource.push(record);
        }
      });
      this.splitedDataSource = {
        leftDataSource: leftDataSource,
        rightDataSource: rightDataSource
      };
      return this.splitedDataSource;
    }
  }, {
    key: "computedRightDataSource",
    get: function get() {
      var filterOption = this.props.filterOption;
      var rightFilter = this.state.rightFilter;

      var _this$splitDataSource3 = this.splitDataSource(),
          rightDataSource = _this$splitDataSource3.rightDataSource;

      if (filterOption && rightFilter) {
        return rightDataSource.filter(function (opt) {
          return filterOption(rightFilter, opt);
        });
      }

      return rightDataSource;
    }
  }, {
    key: "handleSelectChange",
    value: function handleSelectChange(direction, holder) {
      var onSelectChange = this.props.onSelectChange;

      if (!onSelectChange) {
        return;
      }

      if (direction === _enum.TransferDirection.left) {
        var targetSelectedKeys = this.state.targetSelectedKeys;
        onSelectChange(holder, targetSelectedKeys);
      } else {
        var sourceSelectedKeys = this.state.sourceSelectedKeys;
        onSelectChange(sourceSelectedKeys, holder);
      }
    }
  }, {
    key: "getTitles",
    value: function getTitles(transferLocale) {
      var props = this.props;

      if (props.titles) {
        return props.titles;
      }

      return transferLocale.titles;
    }
  }, {
    key: "getSelectedKeysName",
    value: function getSelectedKeysName(direction) {
      return direction === _enum.TransferDirection.left ? 'sourceSelectedKeys' : 'targetSelectedKeys';
    }
  }, {
    key: "render",
    value: function render() {
      return /*#__PURE__*/_react["default"].createElement(_LocaleReceiver["default"], {
        componentName: "Transfer",
        defaultLocale: _default["default"].Transfer
      }, this.renderTransfer);
    }
  }], [{
    key: "contextType",
    get: function get() {
      return _ConfigContext["default"];
    }
  }]);
  return Transfer;
}(_react.Component);

exports["default"] = Transfer;
Transfer.displayName = 'Transfer';
Transfer.List = _list["default"];
Transfer.Operation = _operation["default"];
Transfer.Search = _search["default"];
Transfer.defaultProps = {
  dataSource: [],
  render: _noop["default"],
  showSearch: false
};
(0, _tslib.__decorate)([_mobx.computed], Transfer.prototype, "computedRightDataSource", null);
//# sourceMappingURL=index.js.map
