"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports["default"] = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
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 _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits"));
var _react = _interopRequireDefault(require("react"));
var _Draggable = require("../DragAndDrop/Draggable");
var _Container = _interopRequireDefault(require("../DragAndDrop/Draggable/components/Container"));
var _times = _interopRequireDefault(require("lodash/times"));
var _withDNDContext = _interopRequireDefault(require("./withDNDContext"));
var _jsxFileName = "/home/builduser/work/57e038ea7326c1ec/packages/wix-design-system/dist/cjs/SortableListBase/SortableListBase.jsx";
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2["default"])(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _callSuper(t, o, e) { return o = (0, _getPrototypeOf2["default"])(o), (0, _possibleConstructorReturn2["default"])(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], (0, _getPrototypeOf2["default"])(t).constructor) : o.apply(t, e)); }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
var noUserSelect = {
  userSelect: 'none',
  WebkitUserSelect: 'none'
};

/**
 * Attaches Drag and Drop behavior to a list of items
 */
var SortableListBase = /*#__PURE__*/function (_React$PureComponent) {
  function SortableListBase() {
    var _this;
    (0, _classCallCheck2["default"])(this, SortableListBase);
    for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
      _args[_key] = arguments[_key];
    }
    _this = _callSuper(this, SortableListBase, [].concat(_args));
    _this.noUserSelectionStyle = noUserSelect;
    _this.state = {
      items: _this.props.items || [],
      animationShifts: {},
      draggedId: null
    };
    _this.wrapperNodes = [];
    _this.setWrapperNode = function (node, index, item) {
      _this.wrapperNodes[index] = {
        node: node,
        index: index,
        item: item
      };
    };
    _this.reSetAnimationState = function () {
      var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
      _this.setState(_objectSpread({
        animationShifts: {},
        draggedId: null
      }, overrides));
    };
    _this.handleMoveOut = function (id) {
      _this.reSetAnimationState({
        items: _this.state.items.filter(function (it) {
          return it.id !== id;
        })
      });
      _this.wrapperNodes = _this.wrapperNodes.filter(function (_ref) {
        var item = _ref.item;
        return item.id !== id;
      });
    };
    /**
     * Calculates shifts (offsets) for every item that needs to be moved
     * @param {number} originalIndex Draggable item source index
     * @param {number} moveToIndex New index where is currently draggable item should appear
     * @param {boolean} shiftForward is shifting to forward position
     * @sample
     *  We have three nodes @ DOM:
     *  Item1 has position {top1, left1, bottom1, right1}
     *  Item2 has position {top2, left2, bottom2, right2}
     *  Item3 has position {top3, left3, bottom3, right3}
     *  When we're dragging Item2 to replace Item1 we have:
     *    originalIndex: 1
     *    moveToIndex: 0
     *    shiftForward: false
     *  Item2's placeholder should be animated to Item1's position
     *  Item1's container should be animated to Item2's position
     *  To be sure that new position is correct we should relay our calculations on moving direction:
     *    When we're dragging item to the top, another shifting items should be visually moved to difference of their bottom positions (it means a height of current item, but with its margins)
     *    When we're dragging item to the bottom, another shifting items should be visually moved to difference of their top positions (it means a height of current item, but with its margins)
     *  Same logic exists for horizontals sortable lists and all calculations are based on differences between left or right positions
     */
    _this.getAnimationShifts = function (originalIndex, moveToIndex, shiftForward) {
      var animationShifts = {};
      var minIndex = Math.min(originalIndex, moveToIndex);
      var maxIndex = Math.max(originalIndex, moveToIndex);
      var previousNodeIndex = originalIndex + (shiftForward ? 1 : -1);
      var _ref2 = _this.wrapperNodes[originalIndex] || {},
        node = _ref2.node;
      var _ref3 = _this.wrapperNodes[previousNodeIndex] || {},
        prevNode = _ref3.node;
      if (node && prevNode && originalIndex !== moveToIndex) {
        var nodeRect = node.getBoundingClientRect();
        var prevNodeRect = prevNode.getBoundingClientRect();
        if (shiftForward) {
          animationShifts[previousNodeIndex] = [nodeRect.y === prevNodeRect.y ? nodeRect.left - prevNodeRect.left : 0, nodeRect.x === prevNodeRect.x ? nodeRect.top - prevNodeRect.top : 0];
        } else {
          animationShifts[previousNodeIndex] = [nodeRect.y === prevNodeRect.y ? nodeRect.right - prevNodeRect.right : 0, nodeRect.x === prevNodeRect.x ? nodeRect.bottom - prevNodeRect.bottom : 0];
        }
        (0, _times["default"])(maxIndex - minIndex + 1, function (i) {
          var index = i + minIndex;
          if (index !== originalIndex && index !== previousNodeIndex) {
            animationShifts[index] = animationShifts[previousNodeIndex];
          }
        });
      }
      return animationShifts;
    };
    _this.getPlaceholderShift = function (originalIndex, moveToIndex, shiftIndex) {
      var shiftForward = shiftIndex > 0;
      var _ref4 = _this.wrapperNodes[moveToIndex] || {},
        target = _ref4.node;
      var _ref5 = _this.wrapperNodes[originalIndex] || {},
        placeholder = _ref5.node;
      var shiftX = 0;
      var shiftY = 0;
      if (target && placeholder) {
        var placeholderRect = placeholder.getBoundingClientRect();
        var targetRect = target.getBoundingClientRect();
        if (placeholderRect.y === targetRect.y) {
          shiftX = shiftForward ? targetRect.right - placeholderRect.right : targetRect.left - placeholderRect.left;
        }
        if (placeholderRect.x === targetRect.x) {
          shiftY = shiftForward ? targetRect.bottom - placeholderRect.bottom : targetRect.top - placeholderRect.top;
        }
      }
      return [shiftX, shiftY];
    };
    _this.getInsertionIndex = function (addedIndex, item) {
      var insertPosition = _this.props.insertPosition;
      var items = _this.state.items;
      if (insertPosition === 'start') {
        return 0;
      }
      if (insertPosition === 'end') {
        return items.includes(item) ? items.length - 1 : items.length;
      }
      return addedIndex;
    };
    /**
     * Called when DragSource (list item) is hovered over DragTarget (other list item)
     * Calculates animation shifts & adds new element if it was dragged from another list
     *
     * @param {object} prop Prop
     * @param {number} prop.addedIndex Index to where dragged element should be added
     * @param {number} prop.removedIndex Index from where dragged element was removed
     * @param {number|string} prop.id item's `id`
     * @param {object} prop.item item from `items` prop that is being dragged
     * */
    _this.handleHover = function (prop) {
      var addedIndex = prop.addedIndex,
        item = prop.item;
      var indexToInsert = _this.getInsertionIndex(addedIndex, item);
      _this.setState(function (prevState) {
        var originalIndex = _this.state.items.findIndex(function (_ref6) {
          var id = _ref6.id;
          return id === item.id;
        });
        var items = (0, _toConsumableArray2["default"])(prevState.items);
        var animationShifts = {};
        var draggedId = _this.state.draggedId;

        // New item added from other list
        if (originalIndex < 0) {
          items.splice(indexToInsert, 0, item);
          draggedId = item.id;
        }
        // Existing item moved
        else {
          var moveToIndex = Math.min(items.length - 1, indexToInsert);
          var shiftForward = moveToIndex > originalIndex;
          animationShifts = _objectSpread(_objectSpread({}, _this.getAnimationShifts(originalIndex, moveToIndex, shiftForward)), {}, (0, _defineProperty2["default"])({}, originalIndex, _this.getPlaceholderShift(originalIndex, moveToIndex, shiftForward)));
        }
        return {
          items: items,
          animationShifts: animationShifts,
          draggedId: draggedId
        };
      });
    };
    _this.handleDrop = function (_ref7) {
      var payload = _ref7.payload,
        addedIndex = _ref7.addedIndex,
        removedIndex = _ref7.removedIndex,
        addedToContainerId = _ref7.addedToContainerId,
        removedFromContainerId = _ref7.removedFromContainerId;
      var index = _this.getInsertionIndex(addedIndex, payload);
      _this.reSetAnimationState();
      _this.changeItemPlace(payload, index); // put element at right place after drop
      _this.props.onDrop({
        payload: payload,
        addedIndex: index,
        removedIndex: removedIndex,
        addedToContainerId: addedToContainerId,
        removedFromContainerId: removedFromContainerId
      });
    };
    _this.changeItemPlace = function (item, index) {
      var items = (0, _toConsumableArray2["default"])(_this.state.items);
      var originalIndex = items.indexOf(item);
      if (originalIndex !== -1) {
        items.splice(originalIndex, 1);
      }
      items.splice(index, 0, item);
      _this.setState({
        items: items
      });
    };
    _this.handleDragStart = function (data) {
      _this.reSetAnimationState({
        draggedId: data.id
      });
      if (_this.props.onDragStart) {
        _this.props.onDragStart(data);
      }
    };
    _this.handleDragEnd = function (data) {
      _this.reSetAnimationState();
      if (_this.props.onDragEnd) {
        _this.props.onDragEnd(data);
      }
    };
    _this.renderItem = function (args) {
      var dropped = _this.context.dragDropManager.monitor.didDrop();
      var dragging = _this.context.dragDropManager.monitor.isDragging();
      return _this.props.renderItem(_objectSpread(_objectSpread({}, args), {}, {
        isListInDragState: dragging && !dropped
      }));
    };
    return _this;
  }
  (0, _inherits2["default"])(SortableListBase, _React$PureComponent);
  return (0, _createClass2["default"])(SortableListBase, [{
    key: "UNSAFE_componentWillReceiveProps",
    value: function UNSAFE_componentWillReceiveProps(_ref8) {
      var items = _ref8.items,
        style = _ref8.style;
      // We clear state on drag end if element was dragged from another list,
      // `onDragEnd` will be called on "source" list, not "target" one.
      this.reSetAnimationState({
        items: items ? items : this.state.items
      });
      this.noUserSelectionStyle = _objectSpread(_objectSpread({}, noUserSelect), style);
    }
  }, {
    key: "renderPreview",
    value: function renderPreview() {
      var _this2 = this;
      var _this$props = this.props,
        className = _this$props.className,
        contentClassName = _this$props.contentClassName,
        renderItem = _this$props.renderItem;
      return /*#__PURE__*/_react["default"].createElement("div", {
        className: className,
        __self: this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 255,
          columnNumber: 7
        }
      }, /*#__PURE__*/_react["default"].createElement("div", {
        className: contentClassName,
        __self: this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 256,
          columnNumber: 9
        }
      }, this.state.items.map(function (item, index) {
        return /*#__PURE__*/_react["default"].createElement("div", {
          key: "".concat(item.id, "-").concat(index, "-").concat(_this2.props.containerId),
          __self: _this2,
          __source: {
            fileName: _jsxFileName,
            lineNumber: 258,
            columnNumber: 13
          }
        }, renderItem({
          item: item,
          id: item.id,
          isPlaceholder: false,
          isPreview: false
        }));
      })));
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;
      var _this$props2 = this.props,
        className = _this$props2.className,
        contentClassName = _this$props2.contentClassName,
        groupName = _this$props2.groupName,
        dragPreview = _this$props2.dragPreview,
        containerId = _this$props2.containerId,
        withHandle = _this$props2.withHandle,
        usePortal = _this$props2.usePortal,
        animationDuration = _this$props2.animationDuration,
        animationTiming = _this$props2.animationTiming,
        droppable = _this$props2.droppable,
        style = _this$props2.style;
      var _this$state = this.state,
        items = _this$state.items,
        animationShifts = _this$state.animationShifts,
        draggedId = _this$state.draggedId;
      var isDragging = !!draggedId;
      var isTextSelectionEnabled = isDragging || !withHandle;
      var common = {
        groupName: groupName,
        droppable: droppable,
        containerId: containerId,
        onHover: this.handleHover,
        onMoveOut: this.handleMoveOut
      };
      if (dragPreview) {
        return this.renderPreview();
      }
      return /*#__PURE__*/_react["default"].createElement(_Container["default"], (0, _extends2["default"])({
        className: className,
        onDrop: this.handleDrop,
        total: this.state.items.length,
        style: isTextSelectionEnabled ? this.noUserSelectionStyle : style
      }, common, {
        __self: this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 313,
          columnNumber: 7
        }
      }), /*#__PURE__*/_react["default"].createElement("div", {
        className: contentClassName,
        __self: this,
        __source: {
          fileName: _jsxFileName,
          lineNumber: 320,
          columnNumber: 9
        }
      }, items.map(function (item, index) {
        return /*#__PURE__*/_react["default"].createElement(_Draggable.Draggable, (0, _extends2["default"])({
          dataHook: item.dataHook,
          key: "".concat(item.id, "-").concat(containerId),
          shift: animationShifts[index],
          hasDragged: !!draggedId && draggedId !== item.id,
          setWrapperNode: _this3.setWrapperNode,
          animationDuration: animationDuration,
          animationTiming: animationTiming
        }, common, {
          id: item.id,
          index: index,
          item: item,
          renderItem: _this3.renderItem,
          withHandle: withHandle,
          usePortal: usePortal,
          onDrop: _this3.handleDrop,
          onDragStart: _this3.handleDragStart,
          onDragEnd: _this3.handleDragEnd,
          canDrag: _this3.props.canDrag,
          delay: _this3.props.delay,
          listOfPropsThatAffectItems: _this3.props.listOfPropsThatAffectItems,
          __self: _this3,
          __source: {
            fileName: _jsxFileName,
            lineNumber: 323,
            columnNumber: 15
          }
        }));
      })));
    }
  }]);
}(_react["default"].PureComponent);
SortableListBase.defaultProps = {
  animationDuration: 0,
  animationTiming: '',
  droppable: true,
  insertPosition: 'any'
};
SortableListBase.displayName = 'SortableListBase';
SortableListBase.contextTypes = {
  dragDropManager: function dragDropManager() {
    return null;
  }
};
var _default = exports["default"] = (0, _withDNDContext["default"])(SortableListBase);