wix-style-react
Version:
443 lines (359 loc) • 16.2 kB
JavaScript
import _extends from "@babel/runtime/helpers/extends";
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized";
import _inherits from "@babel/runtime/helpers/inherits";
import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn";
import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
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 _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
import React from 'react';
import PropTypes from 'prop-types';
import { Draggable } from '../DragAndDrop/Draggable';
import Container from '../DragAndDrop/Draggable/components/Container';
import times from '../utils/operators/times';
import withDNDContext from './withDNDContext';
/**
* Attaches Drag and Drop behavior to a list of items
*/
var SortableList = /*#__PURE__*/function (_React$PureComponent) {
_inherits(SortableList, _React$PureComponent);
var _super = _createSuper(SortableList);
function SortableList() {
var _this;
_classCallCheck(this, SortableList);
for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
_args[_key] = arguments[_key];
}
_this = _super.call.apply(_super, [this].concat(_args));
_defineProperty(_assertThisInitialized(_this), "state", {
items: _this.props.items || [],
animationShifts: {},
draggedId: null
});
_defineProperty(_assertThisInitialized(_this), "wrapperNodes", []);
_defineProperty(_assertThisInitialized(_this), "setWrapperNode", function (node, index, item) {
_this.wrapperNodes[index] = {
node: node,
index: index,
item: item
};
});
_defineProperty(_assertThisInitialized(_this), "reSetAnimationState", function () {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_this.setState(_objectSpread({
animationShifts: {},
draggedId: null
}, overrides));
});
_defineProperty(_assertThisInitialized(_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;
});
});
_defineProperty(_assertThisInitialized(_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];
}
times(maxIndex - minIndex + 1, function (i) {
var index = i + minIndex;
if (index !== originalIndex && index !== previousNodeIndex) {
animationShifts[index] = animationShifts[previousNodeIndex];
}
});
}
return animationShifts;
});
_defineProperty(_assertThisInitialized(_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];
});
_defineProperty(_assertThisInitialized(_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;
});
_defineProperty(_assertThisInitialized(_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 = _toConsumableArray(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)), {}, _defineProperty({}, originalIndex, _this.getPlaceholderShift(originalIndex, moveToIndex, shiftForward)));
}
return {
items: items,
animationShifts: animationShifts,
draggedId: draggedId
};
});
});
_defineProperty(_assertThisInitialized(_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
});
});
_defineProperty(_assertThisInitialized(_this), "changeItemPlace", function (item, index) {
var items = _toConsumableArray(_this.state.items);
var originalIndex = items.indexOf(item);
if (originalIndex !== -1) {
items.splice(originalIndex, 1);
}
items.splice(index, 0, item);
_this.setState({
items: items
});
});
_defineProperty(_assertThisInitialized(_this), "handleDragStart", function (data) {
_this.reSetAnimationState({
draggedId: data.id
});
if (_this.props.onDragStart) {
_this.props.onDragStart(data);
}
});
_defineProperty(_assertThisInitialized(_this), "handleDragEnd", function (data) {
_this.reSetAnimationState();
if (_this.props.onDragEnd) {
_this.props.onDragEnd(data);
}
});
_defineProperty(_assertThisInitialized(_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;
}
_createClass(SortableList, [{
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(_ref8) {
var items = _ref8.items;
// 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
});
}
}, {
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.createElement("div", {
className: className
}, /*#__PURE__*/React.createElement("div", {
className: contentClassName
}, this.state.items.map(function (item, index) {
return /*#__PURE__*/React.createElement("div", {
key: "".concat(item.id, "-").concat(index, "-").concat(_this2.props.containerId)
}, 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;
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,
style: isTextSelectionEnabled ? {
userSelect: 'none',
WebkitUserSelect: 'none'
} : {}
};
if (dragPreview) {
return this.renderPreview();
}
return /*#__PURE__*/React.createElement(Container, _extends({
className: className,
onDrop: this.handleDrop,
total: this.state.items.length
}, common), /*#__PURE__*/React.createElement("div", {
className: contentClassName
}, items.map(function (item, index) {
return /*#__PURE__*/React.createElement(Draggable, _extends({
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
}));
})));
}
}]);
return SortableList;
}(React.PureComponent);
_defineProperty(SortableList, "defaultProps", {
animationDuration: 0,
animationTiming: '',
droppable: true,
insertPosition: 'any'
});
SortableList.displayName = 'SortableList';
SortableList.contextTypes = {
dragDropManager: PropTypes.object
};
SortableList.propTypes = _objectSpread(_objectSpread({
/** indicates if user can drop item in the list by default it's true */
droppable: PropTypes.bool
}, Draggable.propTypes), {}, {
/** function that specifying where the item can be inserted */
insertPosition: PropTypes.oneOf(['start', 'end', 'any']),
/** in case of wrong position of item during drag you can force SortableList to use portals */
usePortal: PropTypes.bool,
/**
if you are having nested SortableLists,
list that you are currently dragging need to be marked as dragPreview
inside of renderItem callback
*/
dragPreview: PropTypes.bool,
/** list of items with {id: any} */
items: PropTypes.array,
/** callback for drag start */
onDragStart: PropTypes.func,
/** callback for drag end */
onDragEnd: PropTypes.func,
/** className of the root container */
className: PropTypes.string,
/** className of the first items parent container */
contentClassName: PropTypes.string,
/** animation duration in ms, default = 0 - disabled */
animationDuration: PropTypes.number,
/** animation timing function, default = '' (ease) */
animationTiming: PropTypes.string,
/** callback that could prevent item from dragging */
canDrag: PropTypes.func,
/** number in seconds to add delay between initial mouseDown and drag start */
delay: PropTypes.number,
/**
In case that you are using some external props inside of renderItems method,
you need to define them here.
renderItem = ({ item }) => <div key={item.id}>{this.props.myAwesomeProp}</div>
render() {
return (
<SortableList
...
listOfPropsThatAffectItems={[this.props.myAwesomeProp]}
/>
)
}
*/
listOfPropsThatAffectItems: PropTypes.array
});
export default withDNDContext(SortableList);