UNPKG

wix-style-react

Version:
449 lines (366 loc) • 17.9 kB
"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 _Draggable = require("../DragAndDrop/Draggable"); var _Container = _interopRequireDefault(require("../DragAndDrop/Draggable/components/Container")); var _times = _interopRequireDefault(require("../utils/operators/times")); var _withDNDContext = _interopRequireDefault(require("./withDNDContext")); 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; } } /** * Attaches Drag and Drop behavior to a list of items */ var SortableList = /*#__PURE__*/function (_React$PureComponent) { (0, _inherits2["default"])(SortableList, _React$PureComponent); var _super = _createSuper(SortableList); function SortableList() { var _this; (0, _classCallCheck2["default"])(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)); (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "state", { items: _this.props.items || [], animationShifts: {}, draggedId: 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), "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; }); (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_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]; }); (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); _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 }; }); }); (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_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 }); }); (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); } }); (0, _defineProperty2["default"])((0, _assertThisInitialized2["default"])(_this), "handleDragEnd", function (data) { _this.reSetAnimationState(); if (_this.props.onDragEnd) { _this.props.onDragEnd(data); } }); (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"])(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["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, 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["default"].createElement(_Container["default"], (0, _extends2["default"])({ className: className, onDrop: this.handleDrop, total: this.state.items.length }, common), /*#__PURE__*/_react["default"].createElement("div", { className: contentClassName }, 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 })); }))); } }]); return SortableList; }(_react["default"].PureComponent); (0, _defineProperty2["default"])(SortableList, "defaultProps", { animationDuration: 0, animationTiming: '', droppable: true, insertPosition: 'any' }); SortableList.displayName = 'SortableList'; SortableList.contextTypes = { dragDropManager: _propTypes["default"].object }; SortableList.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 }); var _default = (0, _withDNDContext["default"])(SortableList); exports["default"] = _default;