UNPKG

wix-style-react

Version:
394 lines (324 loc) • 14.5 kB
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 Container from '../DragAndDrop/Draggable/components/Container'; import { Draggable } from '../DragAndDrop/Draggable'; import withDNDContext from './withDNDContext'; import { st, classes } from './SortableGrid.st.css'; import { dataHooks, StripPosition } from './constants'; /** component allow you to implement drag and drop in grid layout */ var SortableGrid = /*#__PURE__*/function (_React$PureComponent) { _inherits(SortableGrid, _React$PureComponent); var _super = _createSuper(SortableGrid); function SortableGrid() { var _this; _classCallCheck(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)); _defineProperty(_assertThisInitialized(_this), "state", { items: _this.props.items || [], animationShifts: {}, draggedId: null, indexToInsert: null, originalIndex: 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), "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); var originalIndex = _this.state.items.findIndex(function (_ref2) { var id = _ref2.id; return id === item.id; }); _this.setState(function () { return { indexToInsert: indexToInsert, originalIndex: originalIndex }; }); }); _defineProperty(_assertThisInitialized(_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 }); }); _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); } _this.setState({ indexToInsert: null }); }); _defineProperty(_assertThisInitialized(_this), "handleDragEnd", function (data) { _this.reSetAnimationState(); if (_this.props.onDragEnd) { _this.props.onDragEnd(data); } _this.setState({ indexToInsert: null }); }); _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(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.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, 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.createElement(Container, _extends({ dataHook: dataHook, className: className, onDrop: this.handleDrop, total: this.state.items.length }, common), /*#__PURE__*/React.createElement("div", { className: st(classes.sortableGridContent, contentClassName) }, startFixedElement && /*#__PURE__*/React.createElement("div", { "data-hook": 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 ? StripPosition.RIGHT : StripPosition.LEFT; return /*#__PURE__*/React.createElement(Draggable, _extends({ 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.createElement("div", { "data-hook": dataHooks.END_FIXED_ELEMENT }, endFixedElement))); } }]); return SortableGrid; }(React.PureComponent); _defineProperty(SortableGrid, "defaultProps", { animationDuration: 0, animationTiming: '', droppable: true, insertPosition: 'any' }); SortableGrid.displayName = 'SortableGrid'; SortableGrid.contextTypes = { dragDropManager: PropTypes.object }; SortableGrid.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, /** Node which will be rendered before draggable items and this element won't be draggable */ startFixedElement: PropTypes.node, /** Node which will be rendered after draggable items and this element won't be draggable */ endFixedElement: PropTypes.node }); SortableGrid.defaultProps = {}; export default withDNDContext(SortableGrid);