wix-style-react
Version:
404 lines (331 loc) • 16.2 kB
JavaScript
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
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 _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn"));
var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf"));
var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
var _react = _interopRequireDefault(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _Container = _interopRequireDefault(require("../DragAndDrop/Draggable/components/Container"));
var _Draggable = require("../DragAndDrop/Draggable");
var _withDNDContext = _interopRequireDefault(require("./withDNDContext"));
var _SortableGridSt = require("./SortableGrid.st.css");
var _constants = require("./constants");
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) { (0, _defineProperty2["default"])(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 = (0, _getPrototypeOf2["default"])(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = (0, _getPrototypeOf2["default"])(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return (0, _possibleConstructorReturn2["default"])(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; } }
/** component allow you to implement drag and drop in grid layout */
var SortableGrid = /*#__PURE__*/function (_React$PureComponent) {
(0, _inherits2["default"])(SortableGrid, _React$PureComponent);
var _super = _createSuper(SortableGrid);
function SortableGrid() {
var _this;
(0, _classCallCheck2["default"])(this, SortableGrid);
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));
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "state", {
items: _this.props.items || [],
animationShifts: {},
draggedId: null,
indexToInsert: null,
originalIndex: null
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "wrapperNodes", []);
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "setWrapperNode", function (node, index, item) {
_this.wrapperNodes[index] = {
node: node,
index: index,
item: item
};
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "reSetAnimationState", function () {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_this.setState(_objectSpread({
animationShifts: {},
draggedId: null
}, overrides));
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_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;
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_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;
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleHover", function (prop) {
var addedIndex = prop.addedIndex,
item = prop.item;
var indexToInsert = _this.getInsertionIndex(addedIndex, item);
var originalIndex = _this.state.items.findIndex(function (_ref2) {
var id = _ref2.id;
return id === item.id;
});
_this.setState(function () {
return {
indexToInsert: indexToInsert,
originalIndex: originalIndex
};
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleDrop", function (_ref3) {
var payload = _ref3.payload,
addedIndex = _ref3.addedIndex,
removedIndex = _ref3.removedIndex,
addedToContainerId = _ref3.addedToContainerId,
removedFromContainerId = _ref3.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
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_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
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleDragStart", function (data) {
_this.reSetAnimationState({
draggedId: data.id
});
if (_this.props.onDragStart) {
_this.props.onDragStart(data);
}
_this.setState({
indexToInsert: null
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleDragEnd", function (data) {
_this.reSetAnimationState();
if (_this.props.onDragEnd) {
_this.props.onDragEnd(data);
}
_this.setState({
indexToInsert: null
});
});
(0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_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, _createClass2["default"])(SortableGrid, [{
key: "UNSAFE_componentWillReceiveProps",
value: function UNSAFE_componentWillReceiveProps(_ref4) {
var items = _ref4.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["default"].createElement("div", {
className: className
}, /*#__PURE__*/_react["default"].createElement("div", {
className: contentClassName
}, this.state.items.map(function (item, index) {
return /*#__PURE__*/_react["default"].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,
dataHook = _this$props2.dataHook,
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,
startFixedElement = _this$props2.startFixedElement,
endFixedElement = _this$props2.endFixedElement;
var _this$state = this.state,
items = _this$state.items,
animationShifts = _this$state.animationShifts,
draggedId = _this$state.draggedId,
indexToInsert = _this$state.indexToInsert,
originalIndex = _this$state.originalIndex;
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"])({
dataHook: dataHook,
className: className,
onDrop: this.handleDrop,
total: this.state.items.length
}, common), /*#__PURE__*/_react["default"].createElement("div", {
className: (0, _SortableGridSt.st)(_SortableGridSt.classes.sortableGridContent, contentClassName)
}, startFixedElement && /*#__PURE__*/_react["default"].createElement("div", {
"data-hook": _constants.dataHooks.START_FIXED_ELEMENT
}, startFixedElement), items.map(function (item, index) {
var isInitialPositionToDrop = indexToInsert === originalIndex;
/**
* define the strip position: in case when item is moved before the initial index, then
* the strip between the grid items must be appeared on the right side of hovered item. Otherwise, strip
* is on the left side of hovered item
* */
var stripPosition = indexToInsert < originalIndex ? _constants.StripPosition.RIGHT : _constants.StripPosition.LEFT;
return /*#__PURE__*/_react["default"].createElement(_Draggable.Draggable, (0, _extends2["default"])({
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,
withStrip: !isInitialPositionToDrop && index === indexToInsert && stripPosition,
isInitialPositionToDrop: isInitialPositionToDrop,
listOfPropsThatAffectItems: _this3.props.listOfPropsThatAffectItems
}));
}), endFixedElement && /*#__PURE__*/_react["default"].createElement("div", {
"data-hook": _constants.dataHooks.END_FIXED_ELEMENT
}, endFixedElement)));
}
}]);
return SortableGrid;
}(_react["default"].PureComponent);
(0, _defineProperty2["default"])(SortableGrid, "defaultProps", {
animationDuration: 0,
animationTiming: '',
droppable: true,
insertPosition: 'any'
});
SortableGrid.displayName = 'SortableGrid';
SortableGrid.contextTypes = {
dragDropManager: _propTypes["default"].object
};
SortableGrid.propTypes = _objectSpread(_objectSpread({
/** indicates if user can drop item in the list by default it's true */
droppable: _propTypes["default"].bool
}, _Draggable.Draggable.propTypes), {}, {
/** function that specifying where the item can be inserted */
insertPosition: _propTypes["default"].oneOf(['start', 'end', 'any']),
/** in case of wrong position of item during drag you can force SortableList to use portals */
usePortal: _propTypes["default"].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["default"].bool,
/** list of items with {id: any} */
items: _propTypes["default"].array,
/** callback for drag start */
onDragStart: _propTypes["default"].func,
/** callback for drag end */
onDragEnd: _propTypes["default"].func,
/** className of the root container */
className: _propTypes["default"].string,
/** className of the first items parent container */
contentClassName: _propTypes["default"].string,
/** animation duration in ms, default = 0 - disabled */
animationDuration: _propTypes["default"].number,
/** animation timing function, default = '' (ease) */
animationTiming: _propTypes["default"].string,
/** callback that could prevent item from dragging */
canDrag: _propTypes["default"].func,
/** number in seconds to add delay between initial mouseDown and drag start */
delay: _propTypes["default"].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["default"].array,
/** Node which will be rendered before draggable items and this element won't be draggable */
startFixedElement: _propTypes["default"].node,
/** Node which will be rendered after draggable items and this element won't be draggable */
endFixedElement: _propTypes["default"].node
});
SortableGrid.defaultProps = {};
var _default = (0, _withDNDContext["default"])(SortableGrid);
exports["default"] = _default;