UNPKG

wix-style-react

Version:
439 lines (436 loc) • 16.1 kB
"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 _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")); var _jsxFileName = "/home/builduser/work/a9c1ac8876d5057c/packages/wix-style-react/dist/cjs/SortableListBase/SortableListBase.js"; 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; } var noUserSelect = { userSelect: 'none', WebkitUserSelect: 'none' }; /** * Attaches Drag and Drop behavior to a list of items */ class SortableListBase extends _react.default.PureComponent { constructor() { var _this; super(...arguments); _this = this; this.noUserSelectionStyle = noUserSelect; this.state = { items: this.props.items || [], animationShifts: {}, draggedId: null }; this.wrapperNodes = []; this.setWrapperNode = (node, index, item) => { this.wrapperNodes[index] = { node, index, item }; }; this.reSetAnimationState = function () { var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _this.setState(_objectSpread({ animationShifts: {}, draggedId: null }, overrides)); }; this.handleMoveOut = id => { this.reSetAnimationState({ items: this.state.items.filter(it => it.id !== id) }); this.wrapperNodes = this.wrapperNodes.filter(_ref => { var { item } = _ref; 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 = (originalIndex, moveToIndex, shiftForward) => { var animationShifts = {}; var minIndex = Math.min(originalIndex, moveToIndex); var maxIndex = Math.max(originalIndex, moveToIndex); var previousNodeIndex = originalIndex + (shiftForward ? 1 : -1); var { node } = this.wrapperNodes[originalIndex] || {}; var { node: prevNode } = this.wrapperNodes[previousNodeIndex] || {}; 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, i => { var index = i + minIndex; if (index !== originalIndex && index !== previousNodeIndex) { animationShifts[index] = animationShifts[previousNodeIndex]; } }); } return animationShifts; }; this.getPlaceholderShift = (originalIndex, moveToIndex, shiftIndex) => { var shiftForward = shiftIndex > 0; var { node: target } = this.wrapperNodes[moveToIndex] || {}; var { node: placeholder } = this.wrapperNodes[originalIndex] || {}; 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 = (addedIndex, item) => { var { insertPosition } = this.props; var { items } = this.state; 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 = prop => { var { addedIndex, item } = prop; var indexToInsert = this.getInsertionIndex(addedIndex, item); this.setState(prevState => { var originalIndex = this.state.items.findIndex(_ref2 => { var { id } = _ref2; return id === item.id; }); var items = [...prevState.items]; var animationShifts = {}; var { draggedId } = this.state; // 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)), {}, { [originalIndex]: this.getPlaceholderShift(originalIndex, moveToIndex, shiftForward) }); } return { items, animationShifts, draggedId }; }); }; this.handleDrop = _ref3 => { var { payload, addedIndex, removedIndex, addedToContainerId, removedFromContainerId } = _ref3; var index = this.getInsertionIndex(addedIndex, payload); this.reSetAnimationState(); this.changeItemPlace(payload, index); // put element at right place after drop this.props.onDrop({ payload, addedIndex: index, removedIndex, addedToContainerId, removedFromContainerId }); }; this.changeItemPlace = (item, index) => { var items = [...this.state.items]; var originalIndex = items.indexOf(item); if (originalIndex !== -1) { items.splice(originalIndex, 1); } items.splice(index, 0, item); this.setState({ items }); }; this.handleDragStart = data => { this.reSetAnimationState({ draggedId: data.id }); if (this.props.onDragStart) { this.props.onDragStart(data); } }; this.handleDragEnd = data => { this.reSetAnimationState(); if (this.props.onDragEnd) { this.props.onDragEnd(data); } }; this.renderItem = 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 })); }; } UNSAFE_componentWillReceiveProps(_ref4) { var { items, style } = _ref4; // 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); } renderPreview() { var { className, contentClassName, renderItem } = this.props; return /*#__PURE__*/_react.default.createElement("div", { className: className, __self: this, __source: { fileName: _jsxFileName, lineNumber: 256, columnNumber: 7 } }, /*#__PURE__*/_react.default.createElement("div", { className: contentClassName, __self: this, __source: { fileName: _jsxFileName, lineNumber: 257, columnNumber: 9 } }, this.state.items.map((item, index) => /*#__PURE__*/_react.default.createElement("div", { key: "".concat(item.id, "-").concat(index, "-").concat(this.props.containerId), __self: this, __source: { fileName: _jsxFileName, lineNumber: 259, columnNumber: 13 } }, renderItem({ item, id: item.id, isPlaceholder: false, isPreview: false }))))); } render() { var { className, contentClassName, groupName, dragPreview, containerId, withHandle, usePortal, animationDuration, animationTiming, droppable, style } = this.props; var { items, animationShifts, draggedId } = this.state; var isDragging = !!draggedId; var isTextSelectionEnabled = isDragging || !withHandle; var common = { groupName, droppable, 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: 314, columnNumber: 7 } }), /*#__PURE__*/_react.default.createElement("div", { className: contentClassName, __self: this, __source: { fileName: _jsxFileName, lineNumber: 321, columnNumber: 9 } }, items.map((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: this.setWrapperNode, animationDuration: animationDuration, animationTiming: animationTiming }, common, { id: item.id, index: index, item: item, renderItem: this.renderItem, withHandle: withHandle, usePortal: usePortal, onDrop: this.handleDrop, onDragStart: this.handleDragStart, onDragEnd: this.handleDragEnd, canDrag: this.props.canDrag, delay: this.props.delay, listOfPropsThatAffectItems: this.props.listOfPropsThatAffectItems, __self: this, __source: { fileName: _jsxFileName, lineNumber: 324, columnNumber: 15 } })); }))); } } SortableListBase.defaultProps = { animationDuration: 0, animationTiming: '', droppable: true, insertPosition: 'any' }; SortableListBase.displayName = 'SortableListBase'; SortableListBase.contextTypes = { dragDropManager: _propTypes.default.object }; SortableListBase.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 SortableListBase to use portals */ usePortal: _propTypes.default.bool, /** if you are having nested SortableListBases, 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 ( <SortableListBase ... listOfPropsThatAffectItems={[this.props.myAwesomeProp]} /> ) } */ listOfPropsThatAffectItems: _propTypes.default.array }); var _default = exports.default = (0, _withDNDContext.default)(SortableListBase); //# sourceMappingURL=SortableListBase.js.map