diff --git a/.gitignore b/.gitignore index d88833ad6..51acaeb24 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,5 @@ *.DS_Store node_modules -dist styles.min.css styles.min.css.map coverage diff --git a/CHANGELOG.md b/CHANGELOG.md index 1d54594d0..f685d5ebb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,56 @@ All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. +<a name="1.12.1"></a> +## [1.12.1](https://github.com/clauderic/react-sortable-hoc/compare/v1.12.0...v1.12.1) (2022-01-28) + + + +<a name="1.12.0"></a> +# [1.12.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.1.0...v1.12.0) (2022-01-28) + + +### Bug Fixes + +* added prop-types to peerDependencies ([0e855c5](https://github.com/clauderic/react-sortable-hoc/commit/0e855c5)) +* clear autoscroller when autoscroll is disabled ([#604](https://github.com/clauderic/react-sortable-hoc/issues/604)) ([3fd83f9](https://github.com/clauderic/react-sortable-hoc/commit/3fd83f9)) +* copy canvas content into cloned node ([43ad122](https://github.com/clauderic/react-sortable-hoc/commit/43ad122)) +* do not copy canvas context if it has neither width nor height ([#530](https://github.com/clauderic/react-sortable-hoc/issues/530)) ([3808437](https://github.com/clauderic/react-sortable-hoc/commit/3808437)) +* don't spread the keysToOmit parameter in omit util ([#563](https://github.com/clauderic/react-sortable-hoc/issues/563)) ([1c69772](https://github.com/clauderic/react-sortable-hoc/commit/1c69772)) +* Fix broken UMD build ([#587](https://github.com/clauderic/react-sortable-hoc/issues/587)) ([6cb7750](https://github.com/clauderic/react-sortable-hoc/commit/6cb7750)) +* get updated index after updateBeforeSortStart ([4471a0a](https://github.com/clauderic/react-sortable-hoc/commit/4471a0a)) +* helperContainer PropType definition broke server-side rendering ([#471](https://github.com/clauderic/react-sortable-hoc/issues/471)) ([c0eef97](https://github.com/clauderic/react-sortable-hoc/commit/c0eef97)) +* invalid helperContainer PropType definition ([#493](https://github.com/clauderic/react-sortable-hoc/issues/493)) ([dc1d18f](https://github.com/clauderic/react-sortable-hoc/commit/dc1d18f)) +* issue with cloning canvas context of dragged items ([#512](https://github.com/clauderic/react-sortable-hoc/issues/512)) ([4df34ad](https://github.com/clauderic/react-sortable-hoc/commit/4df34ad)) +* issue with getComputedStyle and getScrollingParent ([b104249](https://github.com/clauderic/react-sortable-hoc/commit/b104249)) +* issue with radio input name collision when cloning helper ([5337c97](https://github.com/clauderic/react-sortable-hoc/commit/5337c97)) +* issue with windowAsScrollContainer and translation offsets ([0391e62](https://github.com/clauderic/react-sortable-hoc/commit/0391e62)) +* lock axis story should not use lockToContainerEdges ([db1d3a9](https://github.com/clauderic/react-sortable-hoc/commit/db1d3a9)) +* omit disableAutoscroll prop ([#502](https://github.com/clauderic/react-sortable-hoc/issues/502)) ([e994e73](https://github.com/clauderic/react-sortable-hoc/commit/e994e73)) +* omit spreading helperContainer prop ([#497](https://github.com/clauderic/react-sortable-hoc/issues/497)) ([12bafdf](https://github.com/clauderic/react-sortable-hoc/commit/12bafdf)) +* overflow bug while dragging an item upwards in a grid ([1a2c87e](https://github.com/clauderic/react-sortable-hoc/commit/1a2c87e)) +* pass isKeySorting to onSortOver and updateBeforeSortStart handler props ([#531](https://github.com/clauderic/react-sortable-hoc/issues/531)) ([763fd33](https://github.com/clauderic/react-sortable-hoc/commit/763fd33)) +* PropType definition for keyCodes was incorrect ([eaf5070](https://github.com/clauderic/react-sortable-hoc/commit/eaf5070)) +* remove browser field with umd bundle ([#541](https://github.com/clauderic/react-sortable-hoc/issues/541)) ([d3b30fd](https://github.com/clauderic/react-sortable-hoc/commit/d3b30fd)) +* replace process.env.NODE_ENV in UMD builds ([16135df](https://github.com/clauderic/react-sortable-hoc/commit/16135df)) +* update helperContainer prop type definition ([#491](https://github.com/clauderic/react-sortable-hoc/issues/491)) ([fd30383](https://github.com/clauderic/react-sortable-hoc/commit/fd30383)) +* updated the behaviour of disabled elements ([bd3d041](https://github.com/clauderic/react-sortable-hoc/commit/bd3d041)) +* virtualized collection grid bug ([a57975c](https://github.com/clauderic/react-sortable-hoc/commit/a57975c)) + + +### Features + +* Add CSS Grid grid-gap support ([#657](https://github.com/clauderic/react-sortable-hoc/issues/657)) ([4efcaa2](https://github.com/clauderic/react-sortable-hoc/commit/4efcaa2)) +* Add disableAutoscroll prop ([#484](https://github.com/clauderic/react-sortable-hoc/issues/484)) ([7845e76](https://github.com/clauderic/react-sortable-hoc/commit/7845e76)) +* Add keyCodes prop to configure the keyboard shortcuts ([#588](https://github.com/clauderic/react-sortable-hoc/issues/588)) ([4c6d8dd](https://github.com/clauderic/react-sortable-hoc/commit/4c6d8dd)) +* add support for keyboard sorting ([#501](https://github.com/clauderic/react-sortable-hoc/issues/501)) ([439b92f](https://github.com/clauderic/react-sortable-hoc/commit/439b92f)) +* added helperContainer prop ([286eff4](https://github.com/clauderic/react-sortable-hoc/commit/286eff4)) +* allow helperContainer prop to be a function returning an HTMLElement ([#489](https://github.com/clauderic/react-sortable-hoc/issues/489)) ([f4a9b4a](https://github.com/clauderic/react-sortable-hoc/commit/f4a9b4a)) +* Detect scroll container automatically ([#507](https://github.com/clauderic/react-sortable-hoc/issues/507)) ([6572921](https://github.com/clauderic/react-sortable-hoc/commit/6572921)) +* prevent sort start on contentEditable target ([d64c8cf](https://github.com/clauderic/react-sortable-hoc/commit/d64c8cf)) + + + <a name="1.11.0"></a> # [1.11.0](https://github.com/clauderic/react-sortable-hoc/compare/v1.10.1...v1.11.0) (2020-01-20) diff --git a/dist/react-sortable-hoc.esm.js b/dist/react-sortable-hoc.esm.js new file mode 100644 index 000000000..5e4073bec --- /dev/null +++ b/dist/react-sortable-hoc.esm.js @@ -0,0 +1,2146 @@ +import _extends from '@babel/runtime/helpers/esm/extends'; +import _slicedToArray from '@babel/runtime/helpers/esm/slicedToArray'; +import _objectSpread from '@babel/runtime/helpers/esm/objectSpread'; +import _classCallCheck from '@babel/runtime/helpers/esm/classCallCheck'; +import _createClass from '@babel/runtime/helpers/esm/createClass'; +import _possibleConstructorReturn from '@babel/runtime/helpers/esm/possibleConstructorReturn'; +import _getPrototypeOf from '@babel/runtime/helpers/esm/getPrototypeOf'; +import _inherits from '@babel/runtime/helpers/esm/inherits'; +import _assertThisInitialized from '@babel/runtime/helpers/esm/assertThisInitialized'; +import _defineProperty from '@babel/runtime/helpers/esm/defineProperty'; +import {createElement, Component} from 'react'; +import PropTypes from 'prop-types'; +import {findDOMNode} from 'react-dom'; +import invariant from 'invariant'; +import _toConsumableArray from '@babel/runtime/helpers/esm/toConsumableArray'; + +var Manager = (function() { + function Manager() { + _classCallCheck(this, Manager); + + _defineProperty(this, 'refs', {}); + } + + _createClass(Manager, [ + { + key: 'add', + value: function add(collection, ref) { + if (!this.refs[collection]) { + this.refs[collection] = []; + } + + this.refs[collection].push(ref); + }, + }, + { + key: 'remove', + value: function remove(collection, ref) { + var index = this.getIndex(collection, ref); + + if (index !== -1) { + this.refs[collection].splice(index, 1); + } + }, + }, + { + key: 'isActive', + value: function isActive() { + return this.active; + }, + }, + { + key: 'getActive', + value: function getActive() { + var _this = this; + + return this.refs[this.active.collection].find(function(_ref) { + var node = _ref.node; + return node.sortableInfo.index == _this.active.index; + }); + }, + }, + { + key: 'getIndex', + value: function getIndex(collection, ref) { + return this.refs[collection].indexOf(ref); + }, + }, + { + key: 'getOrderedRefs', + value: function getOrderedRefs() { + var collection = + arguments.length > 0 && arguments[0] !== undefined + ? arguments[0] + : this.active.collection; + return this.refs[collection].sort(sortByIndex); + }, + }, + ]); + + return Manager; +})(); + +function sortByIndex(_ref2, _ref3) { + var index1 = _ref2.node.sortableInfo.index; + var index2 = _ref3.node.sortableInfo.index; + return index1 - index2; +} + +function arrayMove(array, from, to) { + if (process.env.NODE_ENV !== 'production') { + if (typeof console !== 'undefined') { + console.warn( + "Deprecation warning: arrayMove will no longer be exported by 'react-sortable-hoc' in the next major release. Please install the `array-move` package locally instead. https://www.npmjs.com/package/array-move", + ); + } + } + + array = array.slice(); + array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]); + return array; +} +function omit(obj, keysToOmit) { + return Object.keys(obj).reduce(function(acc, key) { + if (keysToOmit.indexOf(key) === -1) { + acc[key] = obj[key]; + } + + return acc; + }, {}); +} +var events = { + end: ['touchend', 'touchcancel', 'mouseup'], + move: ['touchmove', 'mousemove'], + start: ['touchstart', 'mousedown'], +}; +var vendorPrefix = (function() { + if (typeof window === 'undefined' || typeof document === 'undefined') { + return ''; + } + + var styles = window.getComputedStyle(document.documentElement, '') || [ + '-moz-hidden-iframe', + ]; + var pre = (Array.prototype.slice + .call(styles) + .join('') + .match(/-(moz|webkit|ms)-/) || + (styles.OLink === '' && ['', 'o']))[1]; + + switch (pre) { + case 'ms': + return 'ms'; + + default: + return pre && pre.length ? pre[0].toUpperCase() + pre.substr(1) : ''; + } +})(); +function setInlineStyles(node, styles) { + Object.keys(styles).forEach(function(key) { + node.style[key] = styles[key]; + }); +} +function setTranslate3d(node, translate) { + node.style[''.concat(vendorPrefix, 'Transform')] = + translate == null + ? '' + : 'translate3d('.concat(translate.x, 'px,').concat(translate.y, 'px,0)'); +} +function setTransitionDuration(node, duration) { + node.style[''.concat(vendorPrefix, 'TransitionDuration')] = + duration == null ? '' : ''.concat(duration, 'ms'); +} +function closest(el, fn) { + while (el) { + if (fn(el)) { + return el; + } + + el = el.parentNode; + } + + return null; +} +function limit(min, max, value) { + return Math.max(min, Math.min(value, max)); +} + +function getPixelValue(stringValue) { + if (stringValue.substr(-2) === 'px') { + return parseFloat(stringValue); + } + + return 0; +} + +function getElementMargin(element) { + var style = window.getComputedStyle(element); + return { + bottom: getPixelValue(style.marginBottom), + left: getPixelValue(style.marginLeft), + right: getPixelValue(style.marginRight), + top: getPixelValue(style.marginTop), + }; +} +function provideDisplayName(prefix, Component$$1) { + var componentName = Component$$1.displayName || Component$$1.name; + return componentName + ? ''.concat(prefix, '(').concat(componentName, ')') + : prefix; +} +function getScrollAdjustedBoundingClientRect(node, scrollDelta) { + var boundingClientRect = node.getBoundingClientRect(); + return { + top: boundingClientRect.top + scrollDelta.top, + left: boundingClientRect.left + scrollDelta.left, + }; +} +function getPosition(event) { + if (event.touches && event.touches.length) { + return { + x: event.touches[0].pageX, + y: event.touches[0].pageY, + }; + } else if (event.changedTouches && event.changedTouches.length) { + return { + x: event.changedTouches[0].pageX, + y: event.changedTouches[0].pageY, + }; + } else { + return { + x: event.pageX, + y: event.pageY, + }; + } +} +function isTouchEvent(event) { + return ( + (event.touches && event.touches.length) || + (event.changedTouches && event.changedTouches.length) + ); +} +function getEdgeOffset(node, parent) { + var offset = + arguments.length > 2 && arguments[2] !== undefined + ? arguments[2] + : { + left: 0, + top: 0, + }; + + if (!node) { + return undefined; + } + + var nodeOffset = { + left: offset.left + node.getBoundingClientRect().left, + top: offset.top + node.getBoundingClientRect().top, + }; + + if (node.parentNode === parent) { + return nodeOffset; + } + + return getEdgeOffset(node.parentNode, parent, nodeOffset); +} +function getTargetIndex(newIndex, prevIndex, oldIndex) { + if (newIndex < oldIndex && newIndex > prevIndex) { + return newIndex - 1; + } else if (newIndex > oldIndex && newIndex < prevIndex) { + return newIndex + 1; + } else { + return newIndex; + } +} +function getLockPixelOffset(_ref) { + var lockOffset = _ref.lockOffset, + width = _ref.width, + height = _ref.height; + var offsetX = lockOffset; + var offsetY = lockOffset; + var unit = 'px'; + + if (typeof lockOffset === 'string') { + var match = /^[+-]?\d*(?:\.\d*)?(px|%)$/.exec(lockOffset); + invariant( + match !== null, + 'lockOffset value should be a number or a string of a ' + + 'number followed by "px" or "%". Given %s', + lockOffset, + ); + offsetX = parseFloat(lockOffset); + offsetY = parseFloat(lockOffset); + unit = match[1]; + } + + invariant( + isFinite(offsetX) && isFinite(offsetY), + 'lockOffset value should be a finite. Given %s', + lockOffset, + ); + + if (unit === '%') { + offsetX = (offsetX * width) / 100; + offsetY = (offsetY * height) / 100; + } + + return { + x: offsetX, + y: offsetY, + }; +} +function getLockPixelOffsets(_ref2) { + var height = _ref2.height, + width = _ref2.width, + lockOffset = _ref2.lockOffset; + var offsets = Array.isArray(lockOffset) + ? lockOffset + : [lockOffset, lockOffset]; + invariant( + offsets.length === 2, + 'lockOffset prop of SortableContainer should be a single ' + + 'value or an array of exactly two values. Given %s', + lockOffset, + ); + + var _offsets = _slicedToArray(offsets, 2), + minLockOffset = _offsets[0], + maxLockOffset = _offsets[1]; + + return [ + getLockPixelOffset({ + height: height, + lockOffset: minLockOffset, + width: width, + }), + getLockPixelOffset({ + height: height, + lockOffset: maxLockOffset, + width: width, + }), + ]; +} + +function isScrollable(el) { + var computedStyle = window.getComputedStyle(el); + var overflowRegex = /(auto|scroll)/; + var properties = ['overflow', 'overflowX', 'overflowY']; + return properties.find(function(property) { + return overflowRegex.test(computedStyle[property]); + }); +} + +function getScrollingParent(el) { + var container = + arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (container) { + return document.querySelector(container); + } + + if (!(el instanceof HTMLElement)) { + return null; + } else if (isScrollable(el)) { + return el; + } else { + return getScrollingParent(el.parentNode); + } +} +function getContainerGridGap(element) { + var style = window.getComputedStyle(element); + + if (style.display === 'grid') { + return { + x: getPixelValue(style.gridColumnGap), + y: getPixelValue(style.gridRowGap), + }; + } + + return { + x: 0, + y: 0, + }; +} +var KEYCODE = { + TAB: 9, + ESC: 27, + SPACE: 32, + LEFT: 37, + UP: 38, + RIGHT: 39, + DOWN: 40, +}; +var NodeType = { + Anchor: 'A', + Button: 'BUTTON', + Canvas: 'CANVAS', + Input: 'INPUT', + Option: 'OPTION', + Textarea: 'TEXTAREA', + Select: 'SELECT', +}; +function cloneNode(node) { + var selector = 'input, textarea, select, canvas, [contenteditable]'; + var fields = node.querySelectorAll(selector); + var clonedNode = node.cloneNode(true); + + var clonedFields = _toConsumableArray(clonedNode.querySelectorAll(selector)); + + clonedFields.forEach(function(field, i) { + if (field.type !== 'file') { + field.value = fields[i].value; + } + + if (field.type === 'radio' && field.name) { + field.name = '__sortableClone__'.concat(field.name); + } + + if ( + field.tagName === NodeType.Canvas && + fields[i].width > 0 && + fields[i].height > 0 + ) { + var destCtx = field.getContext('2d'); + destCtx.drawImage(fields[i], 0, 0); + } + }); + return clonedNode; +} + +function sortableHandle(WrappedComponent) { + var _class, _temp; + + var config = + arguments.length > 1 && arguments[1] !== undefined + ? arguments[1] + : { + withRef: false, + }; + return ( + (_temp = _class = (function(_React$Component) { + _inherits(WithSortableHandle, _React$Component); + + function WithSortableHandle() { + _classCallCheck(this, WithSortableHandle); + + return _possibleConstructorReturn( + this, + _getPrototypeOf(WithSortableHandle).apply(this, arguments), + ); + } + + _createClass(WithSortableHandle, [ + { + key: 'componentDidMount', + value: function componentDidMount() { + var node = findDOMNode(this); + node.sortableHandle = true; + }, + }, + { + key: 'getWrappedInstance', + value: function getWrappedInstance() { + invariant( + config.withRef, + 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableHandle() call', + ); + return this.refs.wrappedInstance; + }, + }, + { + key: 'render', + value: function render() { + var ref = config.withRef ? 'wrappedInstance' : null; + return createElement( + WrappedComponent, + _extends( + { + ref: ref, + }, + this.props, + ), + ); + }, + }, + ]); + + return WithSortableHandle; + })(Component)), + _defineProperty( + _class, + 'displayName', + provideDisplayName('sortableHandle', WrappedComponent), + ), + _temp + ); +} +function isSortableHandle(node) { + return node.sortableHandle != null; +} + +var AutoScroller = (function() { + function AutoScroller(container, onScrollCallback) { + _classCallCheck(this, AutoScroller); + + this.container = container; + this.onScrollCallback = onScrollCallback; + } + + _createClass(AutoScroller, [ + { + key: 'clear', + value: function clear() { + if (this.interval == null) { + return; + } + + clearInterval(this.interval); + this.interval = null; + }, + }, + { + key: 'update', + value: function update(_ref) { + var _this = this; + + var translate = _ref.translate, + minTranslate = _ref.minTranslate, + maxTranslate = _ref.maxTranslate, + width = _ref.width, + height = _ref.height; + var direction = { + x: 0, + y: 0, + }; + var speed = { + x: 1, + y: 1, + }; + var acceleration = { + x: 10, + y: 10, + }; + var _this$container = this.container, + scrollTop = _this$container.scrollTop, + scrollLeft = _this$container.scrollLeft, + scrollHeight = _this$container.scrollHeight, + scrollWidth = _this$container.scrollWidth, + clientHeight = _this$container.clientHeight, + clientWidth = _this$container.clientWidth; + var isTop = scrollTop === 0; + var isBottom = scrollHeight - scrollTop - clientHeight === 0; + var isLeft = scrollLeft === 0; + var isRight = scrollWidth - scrollLeft - clientWidth === 0; + + if (translate.y >= maxTranslate.y - height / 2 && !isBottom) { + direction.y = 1; + speed.y = + acceleration.y * + Math.abs((maxTranslate.y - height / 2 - translate.y) / height); + } else if (translate.x >= maxTranslate.x - width / 2 && !isRight) { + direction.x = 1; + speed.x = + acceleration.x * + Math.abs((maxTranslate.x - width / 2 - translate.x) / width); + } else if (translate.y <= minTranslate.y + height / 2 && !isTop) { + direction.y = -1; + speed.y = + acceleration.y * + Math.abs((translate.y - height / 2 - minTranslate.y) / height); + } else if (translate.x <= minTranslate.x + width / 2 && !isLeft) { + direction.x = -1; + speed.x = + acceleration.x * + Math.abs((translate.x - width / 2 - minTranslate.x) / width); + } + + if (this.interval) { + this.clear(); + this.isAutoScrolling = false; + } + + if (direction.x !== 0 || direction.y !== 0) { + this.interval = setInterval(function() { + _this.isAutoScrolling = true; + var offset = { + left: speed.x * direction.x, + top: speed.y * direction.y, + }; + _this.container.scrollTop += offset.top; + _this.container.scrollLeft += offset.left; + + _this.onScrollCallback(offset); + }, 5); + } + }, + }, + ]); + + return AutoScroller; +})(); + +function defaultGetHelperDimensions(_ref) { + var node = _ref.node; + return { + height: node.offsetHeight, + width: node.offsetWidth, + }; +} + +function defaultShouldCancelStart(event) { + var interactiveElements = [ + NodeType.Input, + NodeType.Textarea, + NodeType.Select, + NodeType.Option, + NodeType.Button, + ]; + + if (interactiveElements.indexOf(event.target.tagName) !== -1) { + return true; + } + + if ( + closest(event.target, function(el) { + return el.contentEditable === 'true'; + }) + ) { + return true; + } + + return false; +} + +var propTypes = { + axis: PropTypes.oneOf(['x', 'y', 'xy']), + contentWindow: PropTypes.any, + disableAutoscroll: PropTypes.bool, + distance: PropTypes.number, + getContainer: PropTypes.func, + getHelperDimensions: PropTypes.func, + helperClass: PropTypes.string, + helperContainer: PropTypes.oneOfType([ + PropTypes.func, + typeof HTMLElement === 'undefined' + ? PropTypes.any + : PropTypes.instanceOf(HTMLElement), + ]), + hideSortableGhost: PropTypes.bool, + keyboardSortingTransitionDuration: PropTypes.number, + lockAxis: PropTypes.string, + lockOffset: PropTypes.oneOfType([ + PropTypes.number, + PropTypes.string, + PropTypes.arrayOf( + PropTypes.oneOfType([PropTypes.number, PropTypes.string]), + ), + ]), + lockToContainerEdges: PropTypes.bool, + onSortEnd: PropTypes.func, + onSortMove: PropTypes.func, + onSortOver: PropTypes.func, + onSortStart: PropTypes.func, + pressDelay: PropTypes.number, + pressThreshold: PropTypes.number, + keyCodes: PropTypes.shape({ + lift: PropTypes.arrayOf(PropTypes.number), + drop: PropTypes.arrayOf(PropTypes.number), + cancel: PropTypes.arrayOf(PropTypes.number), + up: PropTypes.arrayOf(PropTypes.number), + down: PropTypes.arrayOf(PropTypes.number), + }), + shouldCancelStart: PropTypes.func, + transitionDuration: PropTypes.number, + updateBeforeSortStart: PropTypes.func, + useDragHandle: PropTypes.bool, + useWindowAsScrollContainer: PropTypes.bool, +}; +var defaultKeyCodes = { + lift: [KEYCODE.SPACE], + drop: [KEYCODE.SPACE], + cancel: [KEYCODE.ESC], + up: [KEYCODE.UP, KEYCODE.LEFT], + down: [KEYCODE.DOWN, KEYCODE.RIGHT], +}; +var defaultProps = { + axis: 'y', + disableAutoscroll: false, + distance: 0, + getHelperDimensions: defaultGetHelperDimensions, + hideSortableGhost: true, + lockOffset: '50%', + lockToContainerEdges: false, + pressDelay: 0, + pressThreshold: 5, + keyCodes: defaultKeyCodes, + shouldCancelStart: defaultShouldCancelStart, + transitionDuration: 300, + useWindowAsScrollContainer: false, +}; +var omittedProps = Object.keys(propTypes); +function validateProps(props) { + invariant( + !(props.distance && props.pressDelay), + 'Attempted to set both `pressDelay` and `distance` on SortableContainer, you may only use one or the other, not both at the same time.', + ); +} + +function _finallyRethrows(body, finalizer) { + try { + var result = body(); + } catch (e) { + return finalizer(true, e); + } + + if (result && result.then) { + return result.then(finalizer.bind(null, false), finalizer.bind(null, true)); + } + + return finalizer(false, value); +} +function sortableContainer(WrappedComponent) { + var _class, _temp; + + var config = + arguments.length > 1 && arguments[1] !== undefined + ? arguments[1] + : { + withRef: false, + }; + return ( + (_temp = _class = (function(_React$Component) { + _inherits(WithSortableContainer, _React$Component); + + function WithSortableContainer(props) { + var _this; + + _classCallCheck(this, WithSortableContainer); + + _this = _possibleConstructorReturn( + this, + _getPrototypeOf(WithSortableContainer).call(this, props), + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'state', + {}, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleStart', + function(event) { + var _this$props = _this.props, + distance = _this$props.distance, + shouldCancelStart = _this$props.shouldCancelStart; + + if (event.button === 2 || shouldCancelStart(event)) { + return; + } + + _this.touched = true; + _this.position = getPosition(event); + var node = closest(event.target, function(el) { + return el.sortableInfo != null; + }); + + if ( + node && + node.sortableInfo && + _this.nodeIsChild(node) && + !_this.state.sorting + ) { + var useDragHandle = _this.props.useDragHandle; + var _node$sortableInfo = node.sortableInfo, + index = _node$sortableInfo.index, + collection = _node$sortableInfo.collection, + disabled = _node$sortableInfo.disabled; + + if (disabled) { + return; + } + + if (useDragHandle && !closest(event.target, isSortableHandle)) { + return; + } + + _this.manager.active = { + collection: collection, + index: index, + }; + + if ( + !isTouchEvent(event) && + event.target.tagName === NodeType.Anchor + ) { + event.preventDefault(); + } + + if (!distance) { + if (_this.props.pressDelay === 0) { + _this.handlePress(event); + } else { + _this.pressTimer = setTimeout(function() { + return _this.handlePress(event); + }, _this.props.pressDelay); + } + } + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'nodeIsChild', + function(node) { + return node.sortableInfo.manager === _this.manager; + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleMove', + function(event) { + var _this$props2 = _this.props, + distance = _this$props2.distance, + pressThreshold = _this$props2.pressThreshold; + + if ( + !_this.state.sorting && + _this.touched && + !_this._awaitingUpdateBeforeSortStart + ) { + var position = getPosition(event); + var delta = { + x: _this.position.x - position.x, + y: _this.position.y - position.y, + }; + var combinedDelta = Math.abs(delta.x) + Math.abs(delta.y); + _this.delta = delta; + + if ( + !distance && + (!pressThreshold || combinedDelta >= pressThreshold) + ) { + clearTimeout(_this.cancelTimer); + _this.cancelTimer = setTimeout(_this.cancel, 0); + } else if ( + distance && + combinedDelta >= distance && + _this.manager.isActive() + ) { + _this.handlePress(event); + } + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleEnd', + function() { + _this.touched = false; + + _this.cancel(); + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'cancel', + function() { + var distance = _this.props.distance; + var sorting = _this.state.sorting; + + if (!sorting) { + if (!distance) { + clearTimeout(_this.pressTimer); + } + + _this.manager.active = null; + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handlePress', + function(event) { + try { + var active = _this.manager.getActive(); + + var _temp6 = (function() { + if (active) { + var _temp7 = function _temp7() { + var index = _node.sortableInfo.index; + var margin = getElementMargin(_node); + var gridGap = getContainerGridGap(_this.container); + + var containerBoundingRect = _this.scrollContainer.getBoundingClientRect(); + + var dimensions = _getHelperDimensions({ + index: index, + node: _node, + collection: _collection, + }); + + _this.node = _node; + _this.margin = margin; + _this.gridGap = gridGap; + _this.width = dimensions.width; + _this.height = dimensions.height; + _this.marginOffset = { + x: + _this.margin.left + + _this.margin.right + + _this.gridGap.x, + y: Math.max( + _this.margin.top, + _this.margin.bottom, + _this.gridGap.y, + ), + }; + _this.boundingClientRect = _node.getBoundingClientRect(); + _this.containerBoundingRect = containerBoundingRect; + _this.index = index; + _this.newIndex = index; + _this.axis = { + x: _axis.indexOf('x') >= 0, + y: _axis.indexOf('y') >= 0, + }; + _this.offsetEdge = getEdgeOffset(_node, _this.container); + + if (_isKeySorting) { + _this.initialOffset = getPosition( + _objectSpread({}, event, { + pageX: _this.boundingClientRect.left, + pageY: _this.boundingClientRect.top, + }), + ); + } else { + _this.initialOffset = getPosition(event); + } + + _this.initialScroll = { + left: _this.scrollContainer.scrollLeft, + top: _this.scrollContainer.scrollTop, + }; + _this.initialWindowScroll = { + left: window.pageXOffset, + top: window.pageYOffset, + }; + _this.helper = _this.helperContainer.appendChild( + cloneNode(_node), + ); + setInlineStyles(_this.helper, { + boxSizing: 'border-box', + height: ''.concat(_this.height, 'px'), + left: ''.concat( + _this.boundingClientRect.left - margin.left, + 'px', + ), + pointerEvents: 'none', + position: 'fixed', + top: ''.concat( + _this.boundingClientRect.top - margin.top, + 'px', + ), + width: ''.concat(_this.width, 'px'), + }); + + if (_isKeySorting) { + _this.helper.focus(); + } + + if (_hideSortableGhost) { + _this.sortableGhost = _node; + setInlineStyles(_node, { + opacity: 0, + }); + } + + _this.minTranslate = {}; + _this.maxTranslate = {}; + + if (_isKeySorting) { + var _ref = _useWindowAsScrollContainer + ? { + top: 0, + left: 0, + width: _this.contentWindow.innerWidth, + height: _this.contentWindow.innerHeight, + } + : _this.containerBoundingRect, + containerTop = _ref.top, + containerLeft = _ref.left, + containerWidth = _ref.width, + containerHeight = _ref.height; + + var containerBottom = containerTop + containerHeight; + var containerRight = containerLeft + containerWidth; + + if (_this.axis.x) { + _this.minTranslate.x = + containerLeft - _this.boundingClientRect.left; + _this.maxTranslate.x = + containerRight - + (_this.boundingClientRect.left + _this.width); + } + + if (_this.axis.y) { + _this.minTranslate.y = + containerTop - _this.boundingClientRect.top; + _this.maxTranslate.y = + containerBottom - + (_this.boundingClientRect.top + _this.height); + } + } else { + if (_this.axis.x) { + _this.minTranslate.x = + (_useWindowAsScrollContainer + ? 0 + : containerBoundingRect.left) - + _this.boundingClientRect.left - + _this.width / 2; + _this.maxTranslate.x = + (_useWindowAsScrollContainer + ? _this.contentWindow.innerWidth + : containerBoundingRect.left + + containerBoundingRect.width) - + _this.boundingClientRect.left - + _this.width / 2; + } + + if (_this.axis.y) { + _this.minTranslate.y = + (_useWindowAsScrollContainer + ? 0 + : containerBoundingRect.top) - + _this.boundingClientRect.top - + _this.height / 2; + _this.maxTranslate.y = + (_useWindowAsScrollContainer + ? _this.contentWindow.innerHeight + : containerBoundingRect.top + + containerBoundingRect.height) - + _this.boundingClientRect.top - + _this.height / 2; + } + } + + if (_helperClass) { + _helperClass.split(' ').forEach(function(className) { + return _this.helper.classList.add(className); + }); + } + + _this.listenerNode = event.touches + ? _node + : _this.contentWindow; + + if (_isKeySorting) { + _this.listenerNode.addEventListener( + 'wheel', + _this.handleKeyEnd, + true, + ); + + _this.listenerNode.addEventListener( + 'mousedown', + _this.handleKeyEnd, + true, + ); + + _this.listenerNode.addEventListener( + 'keydown', + _this.handleKeyDown, + ); + } else { + events.move.forEach(function(eventName) { + return _this.listenerNode.addEventListener( + eventName, + _this.handleSortMove, + false, + ); + }); + events.end.forEach(function(eventName) { + return _this.listenerNode.addEventListener( + eventName, + _this.handleSortEnd, + false, + ); + }); + } + + _this.setState({ + sorting: true, + sortingIndex: index, + }); + + if (_onSortStart) { + _onSortStart( + { + node: _node, + index: index, + collection: _collection, + isKeySorting: _isKeySorting, + nodes: _this.manager.getOrderedRefs(), + helper: _this.helper, + }, + event, + ); + } + + if (_isKeySorting) { + _this.keyMove(0); + } + }; + + var _this$props3 = _this.props, + _axis = _this$props3.axis, + _getHelperDimensions = _this$props3.getHelperDimensions, + _helperClass = _this$props3.helperClass, + _hideSortableGhost = _this$props3.hideSortableGhost, + updateBeforeSortStart = _this$props3.updateBeforeSortStart, + _onSortStart = _this$props3.onSortStart, + _useWindowAsScrollContainer = + _this$props3.useWindowAsScrollContainer; + var _node = active.node, + _collection = active.collection; + var _isKeySorting = _this.manager.isKeySorting; + + var _temp8 = (function() { + if (typeof updateBeforeSortStart === 'function') { + _this._awaitingUpdateBeforeSortStart = true; + + var _temp9 = _finallyRethrows( + function() { + var index = _node.sortableInfo.index; + return Promise.resolve( + updateBeforeSortStart( + { + collection: _collection, + index: index, + node: _node, + isKeySorting: _isKeySorting, + }, + event, + ), + ).then(function() {}); + }, + function(_wasThrown, _result) { + _this._awaitingUpdateBeforeSortStart = false; + if (_wasThrown) throw _result; + return _result; + }, + ); + + if (_temp9 && _temp9.then) + return _temp9.then(function() {}); + } + })(); + + return _temp8 && _temp8.then + ? _temp8.then(_temp7) + : _temp7(_temp8); + } + })(); + + return Promise.resolve( + _temp6 && _temp6.then ? _temp6.then(function() {}) : void 0, + ); + } catch (e) { + return Promise.reject(e); + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleSortMove', + function(event) { + var onSortMove = _this.props.onSortMove; + + if (typeof event.preventDefault === 'function') { + event.preventDefault(); + } + + _this.updateHelperPosition(event); + + _this.animateNodes(); + + _this.autoscroll(); + + if (onSortMove) { + onSortMove(event); + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleSortEnd', + function(event) { + var _this$props4 = _this.props, + hideSortableGhost = _this$props4.hideSortableGhost, + onSortEnd = _this$props4.onSortEnd; + var _this$manager = _this.manager, + collection = _this$manager.active.collection, + isKeySorting = _this$manager.isKeySorting; + + var nodes = _this.manager.getOrderedRefs(); + + if (_this.listenerNode) { + if (isKeySorting) { + _this.listenerNode.removeEventListener( + 'wheel', + _this.handleKeyEnd, + true, + ); + + _this.listenerNode.removeEventListener( + 'mousedown', + _this.handleKeyEnd, + true, + ); + + _this.listenerNode.removeEventListener( + 'keydown', + _this.handleKeyDown, + ); + } else { + events.move.forEach(function(eventName) { + return _this.listenerNode.removeEventListener( + eventName, + _this.handleSortMove, + ); + }); + events.end.forEach(function(eventName) { + return _this.listenerNode.removeEventListener( + eventName, + _this.handleSortEnd, + ); + }); + } + } + + _this.helper.parentNode.removeChild(_this.helper); + + if (hideSortableGhost && _this.sortableGhost) { + setInlineStyles(_this.sortableGhost, { + opacity: '', + }); + } + + for (var i = 0, len = nodes.length; i < len; i++) { + var _node2 = nodes[i]; + var el = _node2.node; + _node2.edgeOffset = null; + _node2.boundingClientRect = null; + setTranslate3d(el, null); + setTransitionDuration(el, null); + _node2.translate = null; + } + + _this.autoScroller.clear(); + + _this.manager.active = null; + _this.manager.isKeySorting = false; + + _this.setState({ + sorting: false, + sortingIndex: null, + }); + + if (typeof onSortEnd === 'function') { + onSortEnd( + { + collection: collection, + newIndex: _this.newIndex, + oldIndex: _this.index, + isKeySorting: isKeySorting, + nodes: nodes, + }, + event, + ); + } + + _this.touched = false; + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'autoscroll', + function() { + var disableAutoscroll = _this.props.disableAutoscroll; + var isKeySorting = _this.manager.isKeySorting; + + if (disableAutoscroll) { + _this.autoScroller.clear(); + + return; + } + + if (isKeySorting) { + var translate = _objectSpread({}, _this.translate); + + var scrollX = 0; + var scrollY = 0; + + if (_this.axis.x) { + translate.x = Math.min( + _this.maxTranslate.x, + Math.max(_this.minTranslate.x, _this.translate.x), + ); + scrollX = _this.translate.x - translate.x; + } + + if (_this.axis.y) { + translate.y = Math.min( + _this.maxTranslate.y, + Math.max(_this.minTranslate.y, _this.translate.y), + ); + scrollY = _this.translate.y - translate.y; + } + + _this.translate = translate; + setTranslate3d(_this.helper, _this.translate); + _this.scrollContainer.scrollLeft += scrollX; + _this.scrollContainer.scrollTop += scrollY; + return; + } + + _this.autoScroller.update({ + height: _this.height, + maxTranslate: _this.maxTranslate, + minTranslate: _this.minTranslate, + translate: _this.translate, + width: _this.width, + }); + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'onAutoScroll', + function(offset) { + _this.translate.x += offset.left; + _this.translate.y += offset.top; + + _this.animateNodes(); + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleKeyDown', + function(event) { + var keyCode = event.keyCode; + var _this$props5 = _this.props, + shouldCancelStart = _this$props5.shouldCancelStart, + _this$props5$keyCodes = _this$props5.keyCodes, + customKeyCodes = + _this$props5$keyCodes === void 0 ? {} : _this$props5$keyCodes; + + var keyCodes = _objectSpread({}, defaultKeyCodes, customKeyCodes); + + if ( + (_this.manager.active && !_this.manager.isKeySorting) || + (!_this.manager.active && + (!keyCodes.lift.includes(keyCode) || + shouldCancelStart(event) || + !_this.isValidSortingTarget(event))) + ) { + return; + } + + event.stopPropagation(); + event.preventDefault(); + + if (keyCodes.lift.includes(keyCode) && !_this.manager.active) { + _this.keyLift(event); + } else if ( + keyCodes.drop.includes(keyCode) && + _this.manager.active + ) { + _this.keyDrop(event); + } else if (keyCodes.cancel.includes(keyCode)) { + _this.newIndex = _this.manager.active.index; + + _this.keyDrop(event); + } else if (keyCodes.up.includes(keyCode)) { + _this.keyMove(-1); + } else if (keyCodes.down.includes(keyCode)) { + _this.keyMove(1); + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'keyLift', + function(event) { + var target = event.target; + var node = closest(target, function(el) { + return el.sortableInfo != null; + }); + var _node$sortableInfo2 = node.sortableInfo, + index = _node$sortableInfo2.index, + collection = _node$sortableInfo2.collection; + _this.initialFocusedNode = target; + _this.manager.isKeySorting = true; + _this.manager.active = { + index: index, + collection: collection, + }; + + _this.handlePress(event); + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'keyMove', + function(shift) { + var nodes = _this.manager.getOrderedRefs(); + + var lastIndex = nodes[nodes.length - 1].node.sortableInfo.index; + var newIndex = _this.newIndex + shift; + var prevIndex = _this.newIndex; + + if (newIndex < 0 || newIndex > lastIndex) { + return; + } + + _this.prevIndex = prevIndex; + _this.newIndex = newIndex; + var targetIndex = getTargetIndex( + _this.newIndex, + _this.prevIndex, + _this.index, + ); + var target = nodes.find(function(_ref2) { + var node = _ref2.node; + return node.sortableInfo.index === targetIndex; + }); + var targetNode = target.node; + var scrollDelta = _this.containerScrollDelta; + var targetBoundingClientRect = + target.boundingClientRect || + getScrollAdjustedBoundingClientRect(targetNode, scrollDelta); + var targetTranslate = target.translate || { + x: 0, + y: 0, + }; + var targetPosition = { + top: + targetBoundingClientRect.top + + targetTranslate.y - + scrollDelta.top, + left: + targetBoundingClientRect.left + + targetTranslate.x - + scrollDelta.left, + }; + var shouldAdjustForSize = prevIndex < newIndex; + var sizeAdjustment = { + x: + shouldAdjustForSize && _this.axis.x + ? targetNode.offsetWidth - _this.width + : 0, + y: + shouldAdjustForSize && _this.axis.y + ? targetNode.offsetHeight - _this.height + : 0, + }; + + _this.handleSortMove({ + pageX: targetPosition.left + sizeAdjustment.x, + pageY: targetPosition.top + sizeAdjustment.y, + ignoreTransition: shift === 0, + }); + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'keyDrop', + function(event) { + _this.handleSortEnd(event); + + if (_this.initialFocusedNode) { + _this.initialFocusedNode.focus(); + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleKeyEnd', + function(event) { + if (_this.manager.active) { + _this.keyDrop(event); + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'isValidSortingTarget', + function(event) { + var useDragHandle = _this.props.useDragHandle; + var target = event.target; + var node = closest(target, function(el) { + return el.sortableInfo != null; + }); + return ( + node && + node.sortableInfo && + !node.sortableInfo.disabled && + (useDragHandle ? isSortableHandle(target) : target.sortableInfo) + ); + }, + ); + + validateProps(props); + _this.manager = new Manager(); + _this.events = { + end: _this.handleEnd, + move: _this.handleMove, + start: _this.handleStart, + }; + return _this; + } + + _createClass(WithSortableContainer, [ + { + key: 'getChildContext', + value: function getChildContext() { + return { + manager: this.manager, + }; + }, + }, + { + key: 'componentDidMount', + value: function componentDidMount() { + var _this2 = this; + + var useWindowAsScrollContainer = this.props + .useWindowAsScrollContainer; + var container = this.getContainer(); + Promise.resolve(container).then(function(containerNode) { + _this2.container = containerNode; + _this2.document = _this2.container.ownerDocument || document; + var contentWindow = + _this2.props.contentWindow || + _this2.document.defaultView || + window; + _this2.contentWindow = + typeof contentWindow === 'function' + ? contentWindow() + : contentWindow; + _this2.scrollContainer = useWindowAsScrollContainer + ? _this2.document.scrollingElement || + _this2.document.documentElement + : getScrollingParent( + _this2.container, + _this2.props.scrollContainer, + ) || _this2.container; + _this2.autoScroller = new AutoScroller( + _this2.scrollContainer, + _this2.onAutoScroll, + ); + Object.keys(_this2.events).forEach(function(key) { + return events[key].forEach(function(eventName) { + return _this2.container.addEventListener( + eventName, + _this2.events[key], + false, + ); + }); + }); + + _this2.container.addEventListener( + 'keydown', + _this2.handleKeyDown, + ); + }); + }, + }, + { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + var _this3 = this; + + if (this.helper && this.helper.parentNode) { + this.helper.parentNode.removeChild(this.helper); + } + + if (!this.container) { + return; + } + + Object.keys(this.events).forEach(function(key) { + return events[key].forEach(function(eventName) { + return _this3.container.removeEventListener( + eventName, + _this3.events[key], + ); + }); + }); + this.container.removeEventListener('keydown', this.handleKeyDown); + }, + }, + { + key: 'updateHelperPosition', + value: function updateHelperPosition(event) { + var _this$props6 = this.props, + lockAxis = _this$props6.lockAxis, + lockOffset = _this$props6.lockOffset, + lockToContainerEdges = _this$props6.lockToContainerEdges, + transitionDuration = _this$props6.transitionDuration, + _this$props6$keyboard = + _this$props6.keyboardSortingTransitionDuration, + keyboardSortingTransitionDuration = + _this$props6$keyboard === void 0 + ? transitionDuration + : _this$props6$keyboard; + var isKeySorting = this.manager.isKeySorting; + var ignoreTransition = event.ignoreTransition; + var offset = getPosition(event); + var translate = { + x: offset.x - this.initialOffset.x, + y: offset.y - this.initialOffset.y, + }; + translate.y -= window.pageYOffset - this.initialWindowScroll.top; + translate.x -= window.pageXOffset - this.initialWindowScroll.left; + this.translate = translate; + + if (lockToContainerEdges) { + var _getLockPixelOffsets = getLockPixelOffsets({ + height: this.height, + lockOffset: lockOffset, + width: this.width, + }), + _getLockPixelOffsets2 = _slicedToArray(_getLockPixelOffsets, 2), + minLockOffset = _getLockPixelOffsets2[0], + maxLockOffset = _getLockPixelOffsets2[1]; + + var minOffset = { + x: this.width / 2 - minLockOffset.x, + y: this.height / 2 - minLockOffset.y, + }; + var maxOffset = { + x: this.width / 2 - maxLockOffset.x, + y: this.height / 2 - maxLockOffset.y, + }; + translate.x = limit( + this.minTranslate.x + minOffset.x, + this.maxTranslate.x - maxOffset.x, + translate.x, + ); + translate.y = limit( + this.minTranslate.y + minOffset.y, + this.maxTranslate.y - maxOffset.y, + translate.y, + ); + } + + if (lockAxis === 'x') { + translate.y = 0; + } else if (lockAxis === 'y') { + translate.x = 0; + } + + if ( + isKeySorting && + keyboardSortingTransitionDuration && + !ignoreTransition + ) { + setTransitionDuration( + this.helper, + keyboardSortingTransitionDuration, + ); + } + + setTranslate3d(this.helper, translate); + }, + }, + { + key: 'animateNodes', + value: function animateNodes() { + var _this$props7 = this.props, + transitionDuration = _this$props7.transitionDuration, + hideSortableGhost = _this$props7.hideSortableGhost, + onSortOver = _this$props7.onSortOver; + var containerScrollDelta = this.containerScrollDelta, + windowScrollDelta = this.windowScrollDelta; + var nodes = this.manager.getOrderedRefs(); + var sortingOffset = { + left: + this.offsetEdge.left + + this.translate.x + + containerScrollDelta.left, + top: + this.offsetEdge.top + + this.translate.y + + containerScrollDelta.top, + }; + var isKeySorting = this.manager.isKeySorting; + var prevIndex = this.newIndex; + this.newIndex = null; + + for (var i = 0, len = nodes.length; i < len; i++) { + var _node3 = nodes[i].node; + var index = _node3.sortableInfo.index; + + var width = _node3.getBoundingClientRect().width; + + var height = _node3.getBoundingClientRect().height; + + var offset = { + height: this.height > height ? height / 2 : this.height / 2, + width: this.width > width ? width / 2 : this.width / 2, + }; + var mustShiftBackward = + isKeySorting && index > this.index && index <= prevIndex; + var mustShiftForward = + isKeySorting && index < this.index && index >= prevIndex; + var translate = { + x: 0, + y: 0, + }; + var edgeOffset = nodes[i].edgeOffset; + + if (!edgeOffset) { + edgeOffset = getEdgeOffset(_node3, this.container); + nodes[i].edgeOffset = edgeOffset; + + if (isKeySorting) { + nodes[ + i + ].boundingClientRect = getScrollAdjustedBoundingClientRect( + _node3, + containerScrollDelta, + ); + } + } + + var nextNode = i < nodes.length - 1 && nodes[i + 1]; + var prevNode = i > 0 && nodes[i - 1]; + + if (nextNode && !nextNode.edgeOffset) { + nextNode.edgeOffset = getEdgeOffset( + nextNode.node, + this.container, + ); + + if (isKeySorting) { + nextNode.boundingClientRect = getScrollAdjustedBoundingClientRect( + nextNode.node, + containerScrollDelta, + ); + } + } + + if (index === this.index) { + if (hideSortableGhost) { + this.sortableGhost = _node3; + setInlineStyles(_node3, { + opacity: 0, + }); + } + + continue; + } + + if (transitionDuration) { + setTransitionDuration(_node3, transitionDuration); + } + + if (this.axis.x) { + if (this.axis.y) { + if ( + mustShiftForward || + (index < this.index && + ((sortingOffset.left + + windowScrollDelta.left - + offset.width <= + edgeOffset.left && + sortingOffset.top + windowScrollDelta.top <= + edgeOffset.top + offset.height) || + sortingOffset.top + + windowScrollDelta.top + + offset.height <= + edgeOffset.top)) + ) { + translate.x = this.width + this.marginOffset.x; + + if ( + edgeOffset.left + translate.x > + this.containerBoundingRect.width - offset.width + ) { + if (nextNode) { + translate.x = + nextNode.edgeOffset.left - edgeOffset.left; + translate.y = nextNode.edgeOffset.top - edgeOffset.top; + } + } + + if (this.newIndex === null) { + this.newIndex = index; + } + } else if ( + mustShiftBackward || + (index > this.index && + ((sortingOffset.left + + windowScrollDelta.left + + offset.width >= + edgeOffset.left && + sortingOffset.top + + windowScrollDelta.top + + offset.height >= + edgeOffset.top) || + sortingOffset.top + + windowScrollDelta.top + + offset.height >= + edgeOffset.top + height)) + ) { + translate.x = -(this.width + this.marginOffset.x); + + if ( + edgeOffset.left + translate.x < + this.containerBoundingRect.left + offset.width + ) { + if (prevNode) { + translate.x = + prevNode.edgeOffset.left - edgeOffset.left; + translate.y = prevNode.edgeOffset.top - edgeOffset.top; + } + } + + this.newIndex = index; + } + } else { + if ( + mustShiftBackward || + (index > this.index && + sortingOffset.left + + windowScrollDelta.left + + offset.width >= + edgeOffset.left) + ) { + translate.x = -(this.width + this.marginOffset.x); + this.newIndex = index; + } else if ( + mustShiftForward || + (index < this.index && + sortingOffset.left + windowScrollDelta.left <= + edgeOffset.left + offset.width) + ) { + translate.x = this.width + this.marginOffset.x; + + if (this.newIndex == null) { + this.newIndex = index; + } + } + } + } else if (this.axis.y) { + if ( + mustShiftBackward || + (index > this.index && + sortingOffset.top + + windowScrollDelta.top + + this.boundingClientRect.height >= + edgeOffset.top + offset.height) + ) { + translate.y = -(this.height + this.marginOffset.y); + this.newIndex = index; + } else if ( + mustShiftForward || + (index < this.index && + sortingOffset.top + windowScrollDelta.top <= + edgeOffset.top + offset.height) + ) { + translate.y = this.height + this.marginOffset.y; + + if (this.newIndex == null) { + this.newIndex = index; + } + } + } + + setTranslate3d(_node3, translate); + nodes[i].translate = translate; + } + + if (this.newIndex == null) { + this.newIndex = this.index; + } + + if (isKeySorting) { + this.newIndex = prevIndex; + } + + var oldIndex = isKeySorting ? this.prevIndex : prevIndex; + + if (onSortOver && this.newIndex !== oldIndex) { + onSortOver({ + collection: this.manager.active.collection, + index: this.index, + newIndex: this.newIndex, + oldIndex: oldIndex, + isKeySorting: isKeySorting, + nodes: nodes, + helper: this.helper, + }); + } + }, + }, + { + key: 'getWrappedInstance', + value: function getWrappedInstance() { + invariant( + config.withRef, + 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableContainer() call', + ); + return this.refs.wrappedInstance; + }, + }, + { + key: 'getContainer', + value: function getContainer() { + var getContainer = this.props.getContainer; + + if (typeof getContainer !== 'function') { + return findDOMNode(this); + } + + return getContainer( + config.withRef ? this.getWrappedInstance() : undefined, + ); + }, + }, + { + key: 'render', + value: function render() { + var ref = config.withRef ? 'wrappedInstance' : null; + return createElement( + WrappedComponent, + _extends( + { + ref: ref, + }, + omit(this.props, omittedProps), + ), + ); + }, + }, + { + key: 'helperContainer', + get: function get() { + var helperContainer = this.props.helperContainer; + + if (typeof helperContainer === 'function') { + return helperContainer(); + } + + return this.props.helperContainer || this.document.body; + }, + }, + { + key: 'containerScrollDelta', + get: function get() { + var useWindowAsScrollContainer = this.props + .useWindowAsScrollContainer; + + if (useWindowAsScrollContainer) { + return { + left: 0, + top: 0, + }; + } + + return { + left: this.scrollContainer.scrollLeft - this.initialScroll.left, + top: this.scrollContainer.scrollTop - this.initialScroll.top, + }; + }, + }, + { + key: 'windowScrollDelta', + get: function get() { + return { + left: + this.contentWindow.pageXOffset - this.initialWindowScroll.left, + top: + this.contentWindow.pageYOffset - this.initialWindowScroll.top, + }; + }, + }, + ]); + + return WithSortableContainer; + })(Component)), + _defineProperty( + _class, + 'displayName', + provideDisplayName('sortableList', WrappedComponent), + ), + _defineProperty(_class, 'defaultProps', defaultProps), + _defineProperty(_class, 'propTypes', propTypes), + _defineProperty(_class, 'childContextTypes', { + manager: PropTypes.object.isRequired, + }), + _temp + ); +} + +var propTypes$1 = { + index: PropTypes.number.isRequired, + collection: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), + disabled: PropTypes.bool, +}; +var omittedProps$1 = Object.keys(propTypes$1); +function sortableElement(WrappedComponent) { + var _class, _temp; + + var config = + arguments.length > 1 && arguments[1] !== undefined + ? arguments[1] + : { + withRef: false, + }; + return ( + (_temp = _class = (function(_React$Component) { + _inherits(WithSortableElement, _React$Component); + + function WithSortableElement() { + _classCallCheck(this, WithSortableElement); + + return _possibleConstructorReturn( + this, + _getPrototypeOf(WithSortableElement).apply(this, arguments), + ); + } + + _createClass(WithSortableElement, [ + { + key: 'componentDidMount', + value: function componentDidMount() { + this.register(); + }, + }, + { + key: 'componentDidUpdate', + value: function componentDidUpdate(prevProps) { + if (this.node) { + if (prevProps.index !== this.props.index) { + this.node.sortableInfo.index = this.props.index; + } + + if (prevProps.disabled !== this.props.disabled) { + this.node.sortableInfo.disabled = this.props.disabled; + } + } + + if (prevProps.collection !== this.props.collection) { + this.unregister(prevProps.collection); + this.register(); + } + }, + }, + { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + this.unregister(); + }, + }, + { + key: 'register', + value: function register() { + var _this$props = this.props, + collection = _this$props.collection, + disabled = _this$props.disabled, + index = _this$props.index; + var node = findDOMNode(this); + node.sortableInfo = { + collection: collection, + disabled: disabled, + index: index, + manager: this.context.manager, + }; + this.node = node; + this.ref = { + node: node, + }; + this.context.manager.add(collection, this.ref); + }, + }, + { + key: 'unregister', + value: function unregister() { + var collection = + arguments.length > 0 && arguments[0] !== undefined + ? arguments[0] + : this.props.collection; + this.context.manager.remove(collection, this.ref); + }, + }, + { + key: 'getWrappedInstance', + value: function getWrappedInstance() { + invariant( + config.withRef, + 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableElement() call', + ); + return this.refs.wrappedInstance; + }, + }, + { + key: 'render', + value: function render() { + var ref = config.withRef ? 'wrappedInstance' : null; + return createElement( + WrappedComponent, + _extends( + { + ref: ref, + }, + omit(this.props, omittedProps$1), + ), + ); + }, + }, + ]); + + return WithSortableElement; + })(Component)), + _defineProperty( + _class, + 'displayName', + provideDisplayName('sortableElement', WrappedComponent), + ), + _defineProperty(_class, 'contextTypes', { + manager: PropTypes.object.isRequired, + }), + _defineProperty(_class, 'propTypes', propTypes$1), + _defineProperty(_class, 'defaultProps', { + collection: 0, + }), + _temp + ); +} + +export { + sortableContainer as SortableContainer, + sortableContainer, + sortableElement as SortableElement, + sortableElement, + sortableHandle as SortableHandle, + sortableHandle, + arrayMove, +}; diff --git a/dist/react-sortable-hoc.js b/dist/react-sortable-hoc.js new file mode 100644 index 000000000..f8d73f396 --- /dev/null +++ b/dist/react-sortable-hoc.js @@ -0,0 +1,2896 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var _extends = _interopDefault(require('@babel/runtime/helpers/extends')); +var _slicedToArray = _interopDefault(require('@babel/runtime/helpers/slicedToArray')); +var _classCallCheck = _interopDefault(require('@babel/runtime/helpers/classCallCheck')); +var _createClass = _interopDefault(require('@babel/runtime/helpers/createClass')); +var _assertThisInitialized = _interopDefault(require('@babel/runtime/helpers/assertThisInitialized')); +var _inherits = _interopDefault(require('@babel/runtime/helpers/inherits')); +var _possibleConstructorReturn = _interopDefault(require('@babel/runtime/helpers/possibleConstructorReturn')); +var _getPrototypeOf = _interopDefault(require('@babel/runtime/helpers/getPrototypeOf')); +var _defineProperty = _interopDefault(require('@babel/runtime/helpers/defineProperty')); +var React = require('react'); +var PropTypes = _interopDefault(require('prop-types')); +var reactDom = require('react-dom'); +var invariant = _interopDefault(require('invariant')); +var _toConsumableArray = _interopDefault(require('@babel/runtime/helpers/toConsumableArray')); + +var Manager = function () { + function Manager() { + _classCallCheck(this, Manager); + + _defineProperty(this, "refs", {}); + } + + _createClass(Manager, [{ + key: "add", + value: function add(collection, ref) { + if (!this.refs[collection]) { + this.refs[collection] = []; + } + + this.refs[collection].push(ref); + } + }, { + key: "remove", + value: function remove(collection, ref) { + var index = this.getIndex(collection, ref); + + if (index !== -1) { + this.refs[collection].splice(index, 1); + } + } + }, { + key: "isActive", + value: function isActive() { + return this.active; + } + }, { + key: "getActive", + value: function getActive() { + var _this = this; + + return this.refs[this.active.collection].find(function (_ref) { + var node = _ref.node; + return node.sortableInfo.index == _this.active.index; + }); + } + }, { + key: "getIndex", + value: function getIndex(collection, ref) { + return this.refs[collection].indexOf(ref); + } + }, { + key: "getOrderedRefs", + value: function getOrderedRefs() { + var collection = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.active.collection; + return this.refs[collection].sort(sortByIndex); + } + }]); + + return Manager; +}(); + +function sortByIndex(_ref2, _ref3) { + var index1 = _ref2.node.sortableInfo.index; + var index2 = _ref3.node.sortableInfo.index; + return index1 - index2; +} + +function arrayMove(array, from, to) { + if (process.env.NODE_ENV !== 'production') { + if (typeof console !== 'undefined') { + console.warn("Deprecation warning: arrayMove will no longer be exported by 'react-sortable-hoc' in the next major release. Please install the `array-move` package locally instead. https://www.npmjs.com/package/array-move"); + } + } + + array = array.slice(); + array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]); + return array; +} +function omit(obj, keysToOmit) { + return Object.keys(obj).reduce(function (acc, key) { + if (keysToOmit.indexOf(key) === -1) { + acc[key] = obj[key]; + } + + return acc; + }, {}); +} +var events = { + end: ['touchend', 'touchcancel', 'mouseup'], + move: ['touchmove', 'mousemove'], + start: ['touchstart', 'mousedown'] +}; +var vendorPrefix = function () { + if (typeof window === 'undefined' || typeof document === 'undefined') { + return ''; + } + + var styles = window.getComputedStyle(document.documentElement, '') || ['-moz-hidden-iframe']; + var pre = (Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/) || styles.OLink === '' && ['', 'o'])[1]; + + switch (pre) { + case 'ms': + return 'ms'; + + default: + return pre && pre.length ? pre[0].toUpperCase() + pre.substr(1) : ''; + } +}(); +function setInlineStyles(node, styles) { + Object.keys(styles).forEach(function (key) { + node.style[key] = styles[key]; + }); +} +function setTranslate3d(node, translate) { + node.style["".concat(vendorPrefix, "Transform")] = translate == null ? '' : "translate3d(".concat(translate.x, "px,").concat(translate.y, "px,0)"); +} +function setTransitionDuration(node, duration) { + node.style["".concat(vendorPrefix, "TransitionDuration")] = duration == null ? '' : "".concat(duration, "ms"); +} +function closest(el, fn) { + while (el) { + if (fn(el)) { + return el; + } + + el = el.parentNode; + } + + return null; +} +function limit(min, max, value) { + return Math.max(min, Math.min(value, max)); +} + +function getPixelValue(stringValue) { + if (stringValue.substr(-2) === 'px') { + return parseFloat(stringValue); + } + + return 0; +} + +function getElementMargin(element) { + var style = window.getComputedStyle(element); + return { + bottom: getPixelValue(style.marginBottom), + left: getPixelValue(style.marginLeft), + right: getPixelValue(style.marginRight), + top: getPixelValue(style.marginTop) + }; +} +function provideDisplayName(prefix, Component) { + var componentName = Component.displayName || Component.name; + return componentName ? "".concat(prefix, "(").concat(componentName, ")") : prefix; +} +function getScrollAdjustedBoundingClientRect(node, scrollDelta) { + var boundingClientRect = node.getBoundingClientRect(); + return { + top: boundingClientRect.top + scrollDelta.top, + left: boundingClientRect.left + scrollDelta.left + }; +} +function getPosition(event) { + if (event.touches && event.touches.length) { + return { + x: event.touches[0].pageX, + y: event.touches[0].pageY + }; + } else if (event.changedTouches && event.changedTouches.length) { + return { + x: event.changedTouches[0].pageX, + y: event.changedTouches[0].pageY + }; + } else { + return { + x: event.pageX, + y: event.pageY + }; + } +} +function isTouchEvent(event) { + return event.touches && event.touches.length || event.changedTouches && event.changedTouches.length; +} +function getEdgeOffset(node, parent) { + var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + left: 0, + top: 0 + }; + + if (!node) { + return undefined; + } + + var nodeOffset = { + left: offset.left + node.offsetLeft, + top: offset.top + node.offsetTop + }; + + if (node.parentNode === parent) { + return nodeOffset; + } + + return getEdgeOffset(node.parentNode, parent, nodeOffset); +} +function getTargetIndex(newIndex, prevIndex, oldIndex) { + if (newIndex < oldIndex && newIndex > prevIndex) { + return newIndex - 1; + } else if (newIndex > oldIndex && newIndex < prevIndex) { + return newIndex + 1; + } else { + return newIndex; + } +} +function getLockPixelOffset(_ref) { + var lockOffset = _ref.lockOffset, + width = _ref.width, + height = _ref.height; + var offsetX = lockOffset; + var offsetY = lockOffset; + var unit = 'px'; + + if (typeof lockOffset === 'string') { + var match = /^[+-]?\d*(?:\.\d*)?(px|%)$/.exec(lockOffset); + invariant(match !== null, 'lockOffset value should be a number or a string of a ' + 'number followed by "px" or "%". Given %s', lockOffset); + offsetX = parseFloat(lockOffset); + offsetY = parseFloat(lockOffset); + unit = match[1]; + } + + invariant(isFinite(offsetX) && isFinite(offsetY), 'lockOffset value should be a finite. Given %s', lockOffset); + + if (unit === '%') { + offsetX = offsetX * width / 100; + offsetY = offsetY * height / 100; + } + + return { + x: offsetX, + y: offsetY + }; +} +function getLockPixelOffsets(_ref2) { + var height = _ref2.height, + width = _ref2.width, + lockOffset = _ref2.lockOffset; + var offsets = Array.isArray(lockOffset) ? lockOffset : [lockOffset, lockOffset]; + invariant(offsets.length === 2, 'lockOffset prop of SortableContainer should be a single ' + 'value or an array of exactly two values. Given %s', lockOffset); + + var _offsets = _slicedToArray(offsets, 2), + minLockOffset = _offsets[0], + maxLockOffset = _offsets[1]; + + return [getLockPixelOffset({ + height: height, + lockOffset: minLockOffset, + width: width + }), getLockPixelOffset({ + height: height, + lockOffset: maxLockOffset, + width: width + })]; +} + +function isScrollable(el) { + var computedStyle = window.getComputedStyle(el); + var overflowRegex = /(auto|scroll)/; + var properties = ['overflow', 'overflowX', 'overflowY']; + return properties.find(function (property) { + return overflowRegex.test(computedStyle[property]); + }); +} + +function getScrollingParent(el) { + var container = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (container) { + return document.querySelector(container); + } + + if (!(el instanceof HTMLElement)) { + return null; + } else if (isScrollable(el)) { + return el; + } else { + return getScrollingParent(el.parentNode); + } +} +function getContainerGridGap(element) { + var style = window.getComputedStyle(element); + + if (style.display === 'grid') { + return { + x: getPixelValue(style.gridColumnGap), + y: getPixelValue(style.gridRowGap) + }; + } + + return { + x: 0, + y: 0 + }; +} +var KEYCODE = { + TAB: 9, + ESC: 27, + SPACE: 32, + LEFT: 37, + UP: 38, + RIGHT: 39, + DOWN: 40 +}; +var NodeType = { + Anchor: 'A', + Button: 'BUTTON', + Canvas: 'CANVAS', + Input: 'INPUT', + Option: 'OPTION', + Textarea: 'TEXTAREA', + Select: 'SELECT' +}; +function cloneNode(node) { + var selector = 'input, textarea, select, canvas, [contenteditable]'; + var fields = node.querySelectorAll(selector); + var clonedNode = node.cloneNode(true); + + var clonedFields = _toConsumableArray(clonedNode.querySelectorAll(selector)); + + clonedFields.forEach(function (field, i) { + if (field.type !== 'file') { + field.value = fields[i].value; + } + + if (field.type === 'radio' && field.name) { + field.name = "__sortableClone__".concat(field.name); + } + + if (field.tagName === NodeType.Canvas && fields[i].width > 0 && fields[i].height > 0) { + var destCtx = field.getContext('2d'); + destCtx.drawImage(fields[i], 0, 0); + } + }); + return clonedNode; +} + +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; } } +function sortableHandle(WrappedComponent) { + var _class, _temp; + + var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + withRef: false + }; + return _temp = _class = function (_React$Component) { + _inherits(WithSortableHandle, _React$Component); + + var _super = _createSuper(WithSortableHandle); + + function WithSortableHandle() { + _classCallCheck(this, WithSortableHandle); + + return _super.apply(this, arguments); + } + + _createClass(WithSortableHandle, [{ + key: "componentDidMount", + value: function componentDidMount() { + var node = reactDom.findDOMNode(this); + node.sortableHandle = true; + } + }, { + key: "getWrappedInstance", + value: function getWrappedInstance() { + invariant(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableHandle() call'); + return this.refs.wrappedInstance; + } + }, { + key: "render", + value: function render() { + var ref = config.withRef ? 'wrappedInstance' : null; + return React.createElement(WrappedComponent, _extends({ + ref: ref + }, this.props)); + } + }]); + + return WithSortableHandle; + }(React.Component), _defineProperty(_class, "displayName", provideDisplayName('sortableHandle', WrappedComponent)), _temp; +} +function isSortableHandle(node) { + return node.sortableHandle != null; +} + +var AutoScroller = function () { + function AutoScroller(container, onScrollCallback) { + _classCallCheck(this, AutoScroller); + + this.container = container; + this.onScrollCallback = onScrollCallback; + } + + _createClass(AutoScroller, [{ + key: "clear", + value: function clear() { + if (this.interval == null) { + return; + } + + clearInterval(this.interval); + this.interval = null; + } + }, { + key: "update", + value: function update(_ref) { + var _this = this; + + var translate = _ref.translate, + minTranslate = _ref.minTranslate, + maxTranslate = _ref.maxTranslate, + width = _ref.width, + height = _ref.height; + var direction = { + x: 0, + y: 0 + }; + var speed = { + x: 1, + y: 1 + }; + var acceleration = { + x: 10, + y: 10 + }; + var _this$container = this.container, + scrollTop = _this$container.scrollTop, + scrollLeft = _this$container.scrollLeft, + scrollHeight = _this$container.scrollHeight, + scrollWidth = _this$container.scrollWidth, + clientHeight = _this$container.clientHeight, + clientWidth = _this$container.clientWidth; + var isTop = scrollTop === 0; + var isBottom = scrollHeight - scrollTop - clientHeight === 0; + var isLeft = scrollLeft === 0; + var isRight = scrollWidth - scrollLeft - clientWidth === 0; + + if (translate.y >= maxTranslate.y - height / 2 && !isBottom) { + direction.y = 1; + speed.y = acceleration.y * Math.abs((maxTranslate.y - height / 2 - translate.y) / height); + } else if (translate.x >= maxTranslate.x - width / 2 && !isRight) { + direction.x = 1; + speed.x = acceleration.x * Math.abs((maxTranslate.x - width / 2 - translate.x) / width); + } else if (translate.y <= minTranslate.y + height / 2 && !isTop) { + direction.y = -1; + speed.y = acceleration.y * Math.abs((translate.y - height / 2 - minTranslate.y) / height); + } else if (translate.x <= minTranslate.x + width / 2 && !isLeft) { + direction.x = -1; + speed.x = acceleration.x * Math.abs((translate.x - width / 2 - minTranslate.x) / width); + } + + if (this.interval) { + this.clear(); + this.isAutoScrolling = false; + } + + if (direction.x !== 0 || direction.y !== 0) { + this.interval = setInterval(function () { + _this.isAutoScrolling = true; + var offset = { + left: speed.x * direction.x, + top: speed.y * direction.y + }; + _this.container.scrollTop += offset.top; + _this.container.scrollLeft += offset.left; + + _this.onScrollCallback(offset); + }, 5); + } + } + }]); + + return AutoScroller; +}(); + +function defaultGetHelperDimensions(_ref) { + var node = _ref.node; + return { + height: node.offsetHeight, + width: node.offsetWidth + }; +} + +function defaultShouldCancelStart(event) { + var interactiveElements = [NodeType.Input, NodeType.Textarea, NodeType.Select, NodeType.Option, NodeType.Button]; + + if (interactiveElements.indexOf(event.target.tagName) !== -1) { + return true; + } + + if (closest(event.target, function (el) { + return el.contentEditable === 'true'; + })) { + return true; + } + + return false; +} + +var propTypes = { + axis: PropTypes.oneOf(['x', 'y', 'xy']), + contentWindow: PropTypes.any, + disableAutoscroll: PropTypes.bool, + distance: PropTypes.number, + getContainer: PropTypes.func, + getHelperDimensions: PropTypes.func, + helperClass: PropTypes.string, + helperContainer: PropTypes.oneOfType([PropTypes.func, typeof HTMLElement === 'undefined' ? PropTypes.any : PropTypes.instanceOf(HTMLElement)]), + hideSortableGhost: PropTypes.bool, + keyboardSortingTransitionDuration: PropTypes.number, + lockAxis: PropTypes.string, + lockOffset: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string]))]), + lockToContainerEdges: PropTypes.bool, + onSortEnd: PropTypes.func, + onSortMove: PropTypes.func, + onSortOver: PropTypes.func, + onSortStart: PropTypes.func, + pressDelay: PropTypes.number, + pressThreshold: PropTypes.number, + keyCodes: PropTypes.shape({ + lift: PropTypes.arrayOf(PropTypes.number), + drop: PropTypes.arrayOf(PropTypes.number), + cancel: PropTypes.arrayOf(PropTypes.number), + up: PropTypes.arrayOf(PropTypes.number), + down: PropTypes.arrayOf(PropTypes.number) + }), + shouldCancelStart: PropTypes.func, + transitionDuration: PropTypes.number, + updateBeforeSortStart: PropTypes.func, + useDragHandle: PropTypes.bool, + useWindowAsScrollContainer: PropTypes.bool +}; +var defaultKeyCodes = { + lift: [KEYCODE.SPACE], + drop: [KEYCODE.SPACE], + cancel: [KEYCODE.ESC], + up: [KEYCODE.UP, KEYCODE.LEFT], + down: [KEYCODE.DOWN, KEYCODE.RIGHT] +}; +var defaultProps = { + axis: 'y', + disableAutoscroll: false, + distance: 0, + getHelperDimensions: defaultGetHelperDimensions, + hideSortableGhost: true, + lockOffset: '50%', + lockToContainerEdges: false, + pressDelay: 0, + pressThreshold: 5, + keyCodes: defaultKeyCodes, + shouldCancelStart: defaultShouldCancelStart, + transitionDuration: 300, + useWindowAsScrollContainer: false +}; +var omittedProps = Object.keys(propTypes); +function validateProps(props) { + invariant(!(props.distance && props.pressDelay), 'Attempted to set both `pressDelay` and `distance` on SortableContainer, you may only use one or the other, not both at the same time.'); +} + +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 _finallyRethrows(body, finalizer) { + try { + var result = body(); + } catch (e) { + return finalizer(true, e); + } + + if (result && result.then) { + return result.then(finalizer.bind(null, false), finalizer.bind(null, true)); + } + + return finalizer(false, result); +} + +function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); 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$1() { 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; } } +function sortableContainer(WrappedComponent) { + var _class, _temp; + + var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + withRef: false + }; + return _temp = _class = function (_React$Component) { + _inherits(WithSortableContainer, _React$Component); + + var _super = _createSuper$1(WithSortableContainer); + + function WithSortableContainer(props) { + var _this; + + _classCallCheck(this, WithSortableContainer); + + _this = _super.call(this, props); + + _defineProperty(_assertThisInitialized(_this), "state", {}); + + _defineProperty(_assertThisInitialized(_this), "handleStart", function (event) { + var _this$props = _this.props, + distance = _this$props.distance, + shouldCancelStart = _this$props.shouldCancelStart; + + if (event.button === 2 || shouldCancelStart(event)) { + return; + } + + _this.touched = true; + _this.position = getPosition(event); + var node = closest(event.target, function (el) { + return el.sortableInfo != null; + }); + + if (node && node.sortableInfo && _this.nodeIsChild(node) && !_this.state.sorting) { + var useDragHandle = _this.props.useDragHandle; + var _node$sortableInfo = node.sortableInfo, + index = _node$sortableInfo.index, + collection = _node$sortableInfo.collection, + disabled = _node$sortableInfo.disabled; + + if (disabled) { + return; + } + + if (useDragHandle && !closest(event.target, isSortableHandle)) { + return; + } + + _this.manager.active = { + collection: collection, + index: index + }; + + if (!isTouchEvent(event) && event.target.tagName === NodeType.Anchor) { + event.preventDefault(); + } + + if (!distance) { + if (_this.props.pressDelay === 0) { + _this.handlePress(event); + } else { + _this.pressTimer = setTimeout(function () { + return _this.handlePress(event); + }, _this.props.pressDelay); + } + } + } + }); + + _defineProperty(_assertThisInitialized(_this), "nodeIsChild", function (node) { + return node.sortableInfo.manager === _this.manager; + }); + + _defineProperty(_assertThisInitialized(_this), "handleMove", function (event) { + var _this$props2 = _this.props, + distance = _this$props2.distance, + pressThreshold = _this$props2.pressThreshold; + + if (!_this.state.sorting && _this.touched && !_this._awaitingUpdateBeforeSortStart) { + var position = getPosition(event); + var delta = { + x: _this.position.x - position.x, + y: _this.position.y - position.y + }; + var combinedDelta = Math.abs(delta.x) + Math.abs(delta.y); + _this.delta = delta; + + if (!distance && (!pressThreshold || combinedDelta >= pressThreshold)) { + clearTimeout(_this.cancelTimer); + _this.cancelTimer = setTimeout(_this.cancel, 0); + } else if (distance && combinedDelta >= distance && _this.manager.isActive()) { + _this.handlePress(event); + } + } + }); + + _defineProperty(_assertThisInitialized(_this), "handleEnd", function () { + _this.touched = false; + + _this.cancel(); + }); + + _defineProperty(_assertThisInitialized(_this), "cancel", function () { + var distance = _this.props.distance; + var sorting = _this.state.sorting; + + if (!sorting) { + if (!distance) { + clearTimeout(_this.pressTimer); + } + + _this.manager.active = null; + } + }); + + _defineProperty(_assertThisInitialized(_this), "handlePress", function (event) { + try { + var active = _this.manager.getActive(); + + var _temp6 = function () { + if (active) { + var _temp7 = function _temp7() { + var index = _node.sortableInfo.index; + var margin = getElementMargin(_node); + var gridGap = getContainerGridGap(_this.container); + + var containerBoundingRect = _this.scrollContainer.getBoundingClientRect(); + +var _extends = _interopDefault(require('@babel/runtime/helpers/extends')); +var _slicedToArray = _interopDefault( + require('@babel/runtime/helpers/slicedToArray'), +); +var _objectSpread = _interopDefault( + require('@babel/runtime/helpers/objectSpread'), +); +var _classCallCheck = _interopDefault( + require('@babel/runtime/helpers/classCallCheck'), +); +var _createClass = _interopDefault( + require('@babel/runtime/helpers/createClass'), +); +var _possibleConstructorReturn = _interopDefault( + require('@babel/runtime/helpers/possibleConstructorReturn'), +); +var _getPrototypeOf = _interopDefault( + require('@babel/runtime/helpers/getPrototypeOf'), +); +var _inherits = _interopDefault(require('@babel/runtime/helpers/inherits')); +var _assertThisInitialized = _interopDefault( + require('@babel/runtime/helpers/assertThisInitialized'), +); +var _defineProperty = _interopDefault( + require('@babel/runtime/helpers/defineProperty'), +); +var React = require('react'); +var PropTypes = _interopDefault(require('prop-types')); +var reactDom = require('react-dom'); +var invariant = _interopDefault(require('invariant')); +var _toConsumableArray = _interopDefault( + require('@babel/runtime/helpers/toConsumableArray'), +); + +var Manager = (function() { + function Manager() { + _classCallCheck(this, Manager); + + _defineProperty(this, 'refs', {}); + } + + _createClass(Manager, [ + { + key: 'add', + value: function add(collection, ref) { + if (!this.refs[collection]) { + this.refs[collection] = []; + } + + this.refs[collection].push(ref); + }, + }, + { + key: 'remove', + value: function remove(collection, ref) { + var index = this.getIndex(collection, ref); + + if (index !== -1) { + this.refs[collection].splice(index, 1); + } + }, + }, + { + key: 'isActive', + value: function isActive() { + return this.active; + }, + }, + { + key: 'getActive', + value: function getActive() { + var _this = this; + + return this.refs[this.active.collection].find(function(_ref) { + var node = _ref.node; + return node.sortableInfo.index == _this.active.index; + }); + }, + }, + { + key: 'getIndex', + value: function getIndex(collection, ref) { + return this.refs[collection].indexOf(ref); + }, + }, + { + key: 'getOrderedRefs', + value: function getOrderedRefs() { + var collection = + arguments.length > 0 && arguments[0] !== undefined + ? arguments[0] + : this.active.collection; + return this.refs[collection].sort(sortByIndex); + }, + }, + ]); + + return Manager; +})(); + +function sortByIndex(_ref2, _ref3) { + var index1 = _ref2.node.sortableInfo.index; + var index2 = _ref3.node.sortableInfo.index; + return index1 - index2; +} + +function arrayMove(array, from, to) { + if (process.env.NODE_ENV !== 'production') { + if (typeof console !== 'undefined') { + console.warn( + "Deprecation warning: arrayMove will no longer be exported by 'react-sortable-hoc' in the next major release. Please install the `array-move` package locally instead. https://www.npmjs.com/package/array-move", + ); + } + } + + array = array.slice(); + array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]); + return array; +} +function omit(obj, keysToOmit) { + return Object.keys(obj).reduce(function(acc, key) { + if (keysToOmit.indexOf(key) === -1) { + acc[key] = obj[key]; + } + + return acc; + }, {}); +} +var events = { + end: ['touchend', 'touchcancel', 'mouseup'], + move: ['touchmove', 'mousemove'], + start: ['touchstart', 'mousedown'], +}; +var vendorPrefix = (function() { + if (typeof window === 'undefined' || typeof document === 'undefined') { + return ''; + } + + var styles = window.getComputedStyle(document.documentElement, '') || [ + '-moz-hidden-iframe', + ]; + var pre = (Array.prototype.slice + .call(styles) + .join('') + .match(/-(moz|webkit|ms)-/) || + (styles.OLink === '' && ['', 'o']))[1]; + + switch (pre) { + case 'ms': + return 'ms'; + + default: + return pre && pre.length ? pre[0].toUpperCase() + pre.substr(1) : ''; + } +})(); +function setInlineStyles(node, styles) { + Object.keys(styles).forEach(function(key) { + node.style[key] = styles[key]; + }); +} +function setTranslate3d(node, translate) { + node.style[''.concat(vendorPrefix, 'Transform')] = + translate == null + ? '' + : 'translate3d('.concat(translate.x, 'px,').concat(translate.y, 'px,0)'); +} +function setTransitionDuration(node, duration) { + node.style[''.concat(vendorPrefix, 'TransitionDuration')] = + duration == null ? '' : ''.concat(duration, 'ms'); +} +function closest(el, fn) { + while (el) { + if (fn(el)) { + return el; + } + + el = el.parentNode; + } + + return null; +} +function limit(min, max, value) { + return Math.max(min, Math.min(value, max)); +} + +function getPixelValue(stringValue) { + if (stringValue.substr(-2) === 'px') { + return parseFloat(stringValue); + } + + return 0; +} + +function getElementMargin(element) { + var style = window.getComputedStyle(element); + return { + bottom: getPixelValue(style.marginBottom), + left: getPixelValue(style.marginLeft), + right: getPixelValue(style.marginRight), + top: getPixelValue(style.marginTop), + }; +} +function provideDisplayName(prefix, Component) { + var componentName = Component.displayName || Component.name; + return componentName + ? ''.concat(prefix, '(').concat(componentName, ')') + : prefix; +} +function getScrollAdjustedBoundingClientRect(node, scrollDelta) { + var boundingClientRect = node.getBoundingClientRect(); + return { + top: boundingClientRect.top + scrollDelta.top, + left: boundingClientRect.left + scrollDelta.left, + }; +} +function getPosition(event) { + if (event.touches && event.touches.length) { + return { + x: event.touches[0].pageX, + y: event.touches[0].pageY, + }; + } else if (event.changedTouches && event.changedTouches.length) { + return { + x: event.changedTouches[0].pageX, + y: event.changedTouches[0].pageY, + }; + } else { + return { + x: event.pageX, + y: event.pageY, + }; + } +} +function isTouchEvent(event) { + return ( + (event.touches && event.touches.length) || + (event.changedTouches && event.changedTouches.length) + ); +} +function getEdgeOffset(node, parent) { + var offset = + arguments.length > 2 && arguments[2] !== undefined + ? arguments[2] + : { + left: 0, + top: 0, + }; + + if (!node) { + return undefined; + } + + var nodeOffset = { + left: offset.left + node.getBoundingClientRect().left, + top: offset.top + node.getBoundingClientRect().top, + }; + + if (node.parentNode === parent) { + return nodeOffset; + } + + return getEdgeOffset(node.parentNode, parent, nodeOffset); +} +function getTargetIndex(newIndex, prevIndex, oldIndex) { + if (newIndex < oldIndex && newIndex > prevIndex) { + return newIndex - 1; + } else if (newIndex > oldIndex && newIndex < prevIndex) { + return newIndex + 1; + } else { + return newIndex; + } +} +function getLockPixelOffset(_ref) { + var lockOffset = _ref.lockOffset, + width = _ref.width, + height = _ref.height; + var offsetX = lockOffset; + var offsetY = lockOffset; + var unit = 'px'; + + if (typeof lockOffset === 'string') { + var match = /^[+-]?\d*(?:\.\d*)?(px|%)$/.exec(lockOffset); + invariant( + match !== null, + 'lockOffset value should be a number or a string of a ' + + 'number followed by "px" or "%". Given %s', + lockOffset, + ); + offsetX = parseFloat(lockOffset); + offsetY = parseFloat(lockOffset); + unit = match[1]; + } + + invariant( + isFinite(offsetX) && isFinite(offsetY), + 'lockOffset value should be a finite. Given %s', + lockOffset, + ); + + if (unit === '%') { + offsetX = (offsetX * width) / 100; + offsetY = (offsetY * height) / 100; + } + + return { + x: offsetX, + y: offsetY, + }; +} +function getLockPixelOffsets(_ref2) { + var height = _ref2.height, + width = _ref2.width, + lockOffset = _ref2.lockOffset; + var offsets = Array.isArray(lockOffset) + ? lockOffset + : [lockOffset, lockOffset]; + invariant( + offsets.length === 2, + 'lockOffset prop of SortableContainer should be a single ' + + 'value or an array of exactly two values. Given %s', + lockOffset, + ); + + var _offsets = _slicedToArray(offsets, 2), + minLockOffset = _offsets[0], + maxLockOffset = _offsets[1]; + + return [ + getLockPixelOffset({ + height: height, + lockOffset: minLockOffset, + width: width, + }), + getLockPixelOffset({ + height: height, + lockOffset: maxLockOffset, + width: width, + }), + ]; +} + +function isScrollable(el) { + var computedStyle = window.getComputedStyle(el); + var overflowRegex = /(auto|scroll)/; + var properties = ['overflow', 'overflowX', 'overflowY']; + return properties.find(function(property) { + return overflowRegex.test(computedStyle[property]); + }); +} + +function getScrollingParent(el) { + var container = + arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (container) { + return document.querySelector(container); + } + + if (!(el instanceof HTMLElement)) { + return null; + } else if (isScrollable(el)) { + return el; + } else { + return getScrollingParent(el.parentNode); + } +} +function getContainerGridGap(element) { + var style = window.getComputedStyle(element); + + if (style.display === 'grid') { + return { + x: getPixelValue(style.gridColumnGap), + y: getPixelValue(style.gridRowGap), + }; + } + + return { + x: 0, + y: 0, + }; +} +var KEYCODE = { + TAB: 9, + ESC: 27, + SPACE: 32, + LEFT: 37, + UP: 38, + RIGHT: 39, + DOWN: 40, +}; +var NodeType = { + Anchor: 'A', + Button: 'BUTTON', + Canvas: 'CANVAS', + Input: 'INPUT', + Option: 'OPTION', + Textarea: 'TEXTAREA', + Select: 'SELECT', +}; +function cloneNode(node) { + var selector = 'input, textarea, select, canvas, [contenteditable]'; + var fields = node.querySelectorAll(selector); + var clonedNode = node.cloneNode(true); + + var clonedFields = _toConsumableArray(clonedNode.querySelectorAll(selector)); + + clonedFields.forEach(function(field, i) { + if (field.type !== 'file') { + field.value = fields[i].value; + } + + if (field.type === 'radio' && field.name) { + field.name = '__sortableClone__'.concat(field.name); + } + + if ( + field.tagName === NodeType.Canvas && + fields[i].width > 0 && + fields[i].height > 0 + ) { + var destCtx = field.getContext('2d'); + destCtx.drawImage(fields[i], 0, 0); + } + }); + return clonedNode; +} + +function sortableHandle(WrappedComponent) { + var _class, _temp; + + var config = + arguments.length > 1 && arguments[1] !== undefined + ? arguments[1] + : { + withRef: false, + }; + return ( + (_temp = _class = (function(_React$Component) { + _inherits(WithSortableHandle, _React$Component); + + function WithSortableHandle() { + _classCallCheck(this, WithSortableHandle); + + return _possibleConstructorReturn( + this, + _getPrototypeOf(WithSortableHandle).apply(this, arguments), + ); + } + + _createClass(WithSortableHandle, [ + { + key: 'componentDidMount', + value: function componentDidMount() { + var node = reactDom.findDOMNode(this); + node.sortableHandle = true; + }, + }, + { + key: 'getWrappedInstance', + value: function getWrappedInstance() { + invariant( + config.withRef, + 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableHandle() call', + ); + return this.refs.wrappedInstance; + }, + }, + { + key: 'render', + value: function render() { + var ref = config.withRef ? 'wrappedInstance' : null; + return React.createElement( + WrappedComponent, + _extends( + { + ref: ref, + }, + this.props, + ), + ); + }, + }, + ]); + + return WithSortableHandle; + })(React.Component)), + _defineProperty( + _class, + 'displayName', + provideDisplayName('sortableHandle', WrappedComponent), + ), + _temp + ); +} +function isSortableHandle(node) { + return node.sortableHandle != null; +} + +var AutoScroller = (function() { + function AutoScroller(container, onScrollCallback) { + _classCallCheck(this, AutoScroller); + + this.container = container; + this.onScrollCallback = onScrollCallback; + } + + _createClass(AutoScroller, [ + { + key: 'clear', + value: function clear() { + if (this.interval == null) { + return; + } + + clearInterval(this.interval); + this.interval = null; + }, + }, + { + key: 'update', + value: function update(_ref) { + var _this = this; + + var translate = _ref.translate, + minTranslate = _ref.minTranslate, + maxTranslate = _ref.maxTranslate, + width = _ref.width, + height = _ref.height; + var direction = { + x: 0, + y: 0, + }; + var speed = { + x: 1, + y: 1, + }; + var acceleration = { + x: 10, + y: 10, + }; + var _this$container = this.container, + scrollTop = _this$container.scrollTop, + scrollLeft = _this$container.scrollLeft, + scrollHeight = _this$container.scrollHeight, + scrollWidth = _this$container.scrollWidth, + clientHeight = _this$container.clientHeight, + clientWidth = _this$container.clientWidth; + var isTop = scrollTop === 0; + var isBottom = scrollHeight - scrollTop - clientHeight === 0; + var isLeft = scrollLeft === 0; + var isRight = scrollWidth - scrollLeft - clientWidth === 0; + + if (translate.y >= maxTranslate.y - height / 2 && !isBottom) { + direction.y = 1; + speed.y = + acceleration.y * + Math.abs((maxTranslate.y - height / 2 - translate.y) / height); + } else if (translate.x >= maxTranslate.x - width / 2 && !isRight) { + direction.x = 1; + speed.x = + acceleration.x * + Math.abs((maxTranslate.x - width / 2 - translate.x) / width); + } else if (translate.y <= minTranslate.y + height / 2 && !isTop) { + direction.y = -1; + speed.y = + acceleration.y * + Math.abs((translate.y - height / 2 - minTranslate.y) / height); + } else if (translate.x <= minTranslate.x + width / 2 && !isLeft) { + direction.x = -1; + speed.x = + acceleration.x * + Math.abs((translate.x - width / 2 - minTranslate.x) / width); + } + + if (this.interval) { + this.clear(); + this.isAutoScrolling = false; + } + + if (direction.x !== 0 || direction.y !== 0) { + this.interval = setInterval(function() { + _this.isAutoScrolling = true; + var offset = { + left: speed.x * direction.x, + top: speed.y * direction.y, + }; + _this.container.scrollTop += offset.top; + _this.container.scrollLeft += offset.left; + + _this.onScrollCallback(offset); + }, 5); + } + }, + }, + ]); + + return AutoScroller; +})(); + +function defaultGetHelperDimensions(_ref) { + var node = _ref.node; + return { + height: node.offsetHeight, + width: node.offsetWidth, + }; +} + +function defaultShouldCancelStart(event) { + var interactiveElements = [ + NodeType.Input, + NodeType.Textarea, + NodeType.Select, + NodeType.Option, + NodeType.Button, + ]; + + if (interactiveElements.indexOf(event.target.tagName) !== -1) { + return true; + } + + if ( + closest(event.target, function(el) { + return el.contentEditable === 'true'; + }) + ) { + return true; + } + + return false; +} + +var propTypes = { + axis: PropTypes.oneOf(['x', 'y', 'xy']), + contentWindow: PropTypes.any, + disableAutoscroll: PropTypes.bool, + distance: PropTypes.number, + getContainer: PropTypes.func, + getHelperDimensions: PropTypes.func, + helperClass: PropTypes.string, + helperContainer: PropTypes.oneOfType([ + PropTypes.func, + typeof HTMLElement === 'undefined' + ? PropTypes.any + : PropTypes.instanceOf(HTMLElement), + ]), + hideSortableGhost: PropTypes.bool, + keyboardSortingTransitionDuration: PropTypes.number, + lockAxis: PropTypes.string, + lockOffset: PropTypes.oneOfType([ + PropTypes.number, + PropTypes.string, + PropTypes.arrayOf( + PropTypes.oneOfType([PropTypes.number, PropTypes.string]), + ), + ]), + lockToContainerEdges: PropTypes.bool, + onSortEnd: PropTypes.func, + onSortMove: PropTypes.func, + onSortOver: PropTypes.func, + onSortStart: PropTypes.func, + pressDelay: PropTypes.number, + pressThreshold: PropTypes.number, + keyCodes: PropTypes.shape({ + lift: PropTypes.arrayOf(PropTypes.number), + drop: PropTypes.arrayOf(PropTypes.number), + cancel: PropTypes.arrayOf(PropTypes.number), + up: PropTypes.arrayOf(PropTypes.number), + down: PropTypes.arrayOf(PropTypes.number), + }), + shouldCancelStart: PropTypes.func, + transitionDuration: PropTypes.number, + updateBeforeSortStart: PropTypes.func, + useDragHandle: PropTypes.bool, + useWindowAsScrollContainer: PropTypes.bool, +}; +var defaultKeyCodes = { + lift: [KEYCODE.SPACE], + drop: [KEYCODE.SPACE], + cancel: [KEYCODE.ESC], + up: [KEYCODE.UP, KEYCODE.LEFT], + down: [KEYCODE.DOWN, KEYCODE.RIGHT], +}; +var defaultProps = { + axis: 'y', + disableAutoscroll: false, + distance: 0, + getHelperDimensions: defaultGetHelperDimensions, + hideSortableGhost: true, + lockOffset: '50%', + lockToContainerEdges: false, + pressDelay: 0, + pressThreshold: 5, + keyCodes: defaultKeyCodes, + shouldCancelStart: defaultShouldCancelStart, + transitionDuration: 300, + useWindowAsScrollContainer: false, +}; +var omittedProps = Object.keys(propTypes); +function validateProps(props) { + invariant( + !(props.distance && props.pressDelay), + 'Attempted to set both `pressDelay` and `distance` on SortableContainer, you may only use one or the other, not both at the same time.', + ); +} + +function _finallyRethrows(body, finalizer) { + try { + var result = body(); + } catch (e) { + return finalizer(true, e); + } + + if (result && result.then) { + return result.then(finalizer.bind(null, false), finalizer.bind(null, true)); + } + + return finalizer(false, value); +} +function sortableContainer(WrappedComponent) { + var _class, _temp; + + var config = + arguments.length > 1 && arguments[1] !== undefined + ? arguments[1] + : { + withRef: false, + }; + return ( + (_temp = _class = (function(_React$Component) { + _inherits(WithSortableContainer, _React$Component); + + function WithSortableContainer(props) { + var _this; + + _classCallCheck(this, WithSortableContainer); + + _this = _possibleConstructorReturn( + this, + _getPrototypeOf(WithSortableContainer).call(this, props), + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'state', + {}, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleStart', + function(event) { + var _this$props = _this.props, + distance = _this$props.distance, + shouldCancelStart = _this$props.shouldCancelStart; + + if (event.button === 2 || shouldCancelStart(event)) { + return; + } + + _this.touched = true; + _this.position = getPosition(event); + var node = closest(event.target, function(el) { + return el.sortableInfo != null; + }); + + if ( + node && + node.sortableInfo && + _this.nodeIsChild(node) && + !_this.state.sorting + ) { + var useDragHandle = _this.props.useDragHandle; + var _node$sortableInfo = node.sortableInfo, + index = _node$sortableInfo.index, + collection = _node$sortableInfo.collection, + disabled = _node$sortableInfo.disabled; + + if (disabled) { + return; + } + + if (useDragHandle && !closest(event.target, isSortableHandle)) { + return; + } + + _this.manager.active = { + collection: collection, + index: index, + }; + + if ( + !isTouchEvent(event) && + event.target.tagName === NodeType.Anchor + ) { + event.preventDefault(); + } + + if (!distance) { + if (_this.props.pressDelay === 0) { + _this.handlePress(event); + } else { + _this.pressTimer = setTimeout(function() { + return _this.handlePress(event); + }, _this.props.pressDelay); + } + } + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'nodeIsChild', + function(node) { + return node.sortableInfo.manager === _this.manager; + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleMove', + function(event) { + var _this$props2 = _this.props, + distance = _this$props2.distance, + pressThreshold = _this$props2.pressThreshold; + + if ( + !_this.state.sorting && + _this.touched && + !_this._awaitingUpdateBeforeSortStart + ) { + var position = getPosition(event); + var delta = { + x: _this.position.x - position.x, + y: _this.position.y - position.y, + }; + var combinedDelta = Math.abs(delta.x) + Math.abs(delta.y); + _this.delta = delta; + + if ( + !distance && + (!pressThreshold || combinedDelta >= pressThreshold) + ) { + clearTimeout(_this.cancelTimer); + _this.cancelTimer = setTimeout(_this.cancel, 0); + } else if ( + distance && + combinedDelta >= distance && + _this.manager.isActive() + ) { + _this.handlePress(event); + } + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleEnd', + function() { + _this.touched = false; + + _this.cancel(); + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'cancel', + function() { + var distance = _this.props.distance; + var sorting = _this.state.sorting; + + if (!sorting) { + if (!distance) { + clearTimeout(_this.pressTimer); + } + + _this.manager.active = null; + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handlePress', + function(event) { + try { + var active = _this.manager.getActive(); + + var _temp6 = (function() { + if (active) { + var _temp7 = function _temp7() { + var index = _node.sortableInfo.index; + var margin = getElementMargin(_node); + var gridGap = getContainerGridGap(_this.container); + + var containerBoundingRect = _this.scrollContainer.getBoundingClientRect(); + + var dimensions = _getHelperDimensions({ + index: index, + node: _node, + collection: _collection, + }); + + _this.node = _node; + _this.margin = margin; + _this.gridGap = gridGap; + _this.width = dimensions.width; + _this.height = dimensions.height; + _this.marginOffset = { + x: + _this.margin.left + + _this.margin.right + + _this.gridGap.x, + y: Math.max( + _this.margin.top, + _this.margin.bottom, + _this.gridGap.y, + ), + }; + _this.boundingClientRect = _node.getBoundingClientRect(); + _this.containerBoundingRect = containerBoundingRect; + _this.index = index; + _this.newIndex = index; + _this.axis = { + x: _axis.indexOf('x') >= 0, + y: _axis.indexOf('y') >= 0, + }; + _this.offsetEdge = getEdgeOffset(_node, _this.container); + + if (_isKeySorting) { + _this.initialOffset = getPosition( + _objectSpread({}, event, { + pageX: _this.boundingClientRect.left, + pageY: _this.boundingClientRect.top, + }), + ); + } else { + _this.initialOffset = getPosition(event); + } + + _this.initialScroll = { + left: _this.scrollContainer.scrollLeft, + top: _this.scrollContainer.scrollTop, + }; + _this.initialWindowScroll = { + left: window.pageXOffset, + top: window.pageYOffset, + }; + _this.helper = _this.helperContainer.appendChild( + cloneNode(_node), + ); + setInlineStyles(_this.helper, { + boxSizing: 'border-box', + height: ''.concat(_this.height, 'px'), + left: ''.concat( + _this.boundingClientRect.left - margin.left, + 'px', + ), + pointerEvents: 'none', + position: 'fixed', + top: ''.concat( + _this.boundingClientRect.top - margin.top, + 'px', + ), + width: ''.concat(_this.width, 'px'), + }); + + if (_isKeySorting) { + _this.helper.focus(); + } + + if (_hideSortableGhost) { + _this.sortableGhost = _node; + setInlineStyles(_node, { + opacity: 0, + }); + } + + _this.minTranslate = {}; + _this.maxTranslate = {}; + + if (_isKeySorting) { + var _ref = _useWindowAsScrollContainer + ? { + top: 0, + left: 0, + width: _this.contentWindow.innerWidth, + height: _this.contentWindow.innerHeight, + } + : _this.containerBoundingRect, + containerTop = _ref.top, + containerLeft = _ref.left, + containerWidth = _ref.width, + containerHeight = _ref.height; + + var containerBottom = containerTop + containerHeight; + var containerRight = containerLeft + containerWidth; + + if (_this.axis.x) { + _this.minTranslate.x = + containerLeft - _this.boundingClientRect.left; + _this.maxTranslate.x = + containerRight - + (_this.boundingClientRect.left + _this.width); + } + + if (_this.axis.y) { + _this.minTranslate.y = + containerTop - _this.boundingClientRect.top; + _this.maxTranslate.y = + containerBottom - + (_this.boundingClientRect.top + _this.height); + } + } else { + if (_this.axis.x) { + _this.minTranslate.x = + (_useWindowAsScrollContainer + ? 0 + : containerBoundingRect.left) - + _this.boundingClientRect.left - + _this.width / 2; + _this.maxTranslate.x = + (_useWindowAsScrollContainer + ? _this.contentWindow.innerWidth + : containerBoundingRect.left + + containerBoundingRect.width) - + _this.boundingClientRect.left - + _this.width / 2; + } + + if (_this.axis.y) { + _this.minTranslate.y = + (_useWindowAsScrollContainer + ? 0 + : containerBoundingRect.top) - + _this.boundingClientRect.top - + _this.height / 2; + _this.maxTranslate.y = + (_useWindowAsScrollContainer + ? _this.contentWindow.innerHeight + : containerBoundingRect.top + + containerBoundingRect.height) - + _this.boundingClientRect.top - + _this.height / 2; + } + } + + if (_helperClass) { + _helperClass.split(' ').forEach(function(className) { + return _this.helper.classList.add(className); + }); + } + + _this.listenerNode = event.touches + ? _node + : _this.contentWindow; + + if (_isKeySorting) { + _this.listenerNode.addEventListener( + 'wheel', + _this.handleKeyEnd, + true, + ); + + _this.listenerNode.addEventListener( + 'mousedown', + _this.handleKeyEnd, + true, + ); + + _this.listenerNode.addEventListener( + 'keydown', + _this.handleKeyDown, + ); + } else { + events.move.forEach(function(eventName) { + return _this.listenerNode.addEventListener( + eventName, + _this.handleSortMove, + false, + ); + }); + events.end.forEach(function(eventName) { + return _this.listenerNode.addEventListener( + eventName, + _this.handleSortEnd, + false, + ); + }); + } + + _this.setState({ + sorting: true, + sortingIndex: index, + }); + + if (_onSortStart) { + _onSortStart( + { + node: _node, + index: index, + collection: _collection, + isKeySorting: _isKeySorting, + nodes: _this.manager.getOrderedRefs(), + helper: _this.helper, + }, + event, + ); + } + + if (_isKeySorting) { + _this.keyMove(0); + } + }; + + var _this$props3 = _this.props, + _axis = _this$props3.axis, + _getHelperDimensions = _this$props3.getHelperDimensions, + _helperClass = _this$props3.helperClass, + _hideSortableGhost = _this$props3.hideSortableGhost, + updateBeforeSortStart = _this$props3.updateBeforeSortStart, + _onSortStart = _this$props3.onSortStart, + _useWindowAsScrollContainer = + _this$props3.useWindowAsScrollContainer; + var _node = active.node, + _collection = active.collection; + var _isKeySorting = _this.manager.isKeySorting; + + var _temp8 = (function() { + if (typeof updateBeforeSortStart === 'function') { + _this._awaitingUpdateBeforeSortStart = true; + + var _temp9 = _finallyRethrows( + function() { + var index = _node.sortableInfo.index; + return Promise.resolve( + updateBeforeSortStart( + { + collection: _collection, + index: index, + node: _node, + isKeySorting: _isKeySorting, + }, + event, + ), + ).then(function() {}); + }, + function(_wasThrown, _result) { + _this._awaitingUpdateBeforeSortStart = false; + if (_wasThrown) throw _result; + return _result; + }, + ); + + if (_temp9 && _temp9.then) + return _temp9.then(function() {}); + } + })(); + + return _temp8 && _temp8.then + ? _temp8.then(_temp7) + : _temp7(_temp8); + } + })(); + + return Promise.resolve( + _temp6 && _temp6.then ? _temp6.then(function() {}) : void 0, + ); + } catch (e) { + return Promise.reject(e); + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleSortMove', + function(event) { + var onSortMove = _this.props.onSortMove; + + if (typeof event.preventDefault === 'function') { + event.preventDefault(); + } + + _this.updateHelperPosition(event); + + _this.animateNodes(); + + _this.autoscroll(); + + if (onSortMove) { + onSortMove(event); + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleSortEnd', + function(event) { + var _this$props4 = _this.props, + hideSortableGhost = _this$props4.hideSortableGhost, + onSortEnd = _this$props4.onSortEnd; + var _this$manager = _this.manager, + collection = _this$manager.active.collection, + isKeySorting = _this$manager.isKeySorting; + + var nodes = _this.manager.getOrderedRefs(); + + if (_this.listenerNode) { + if (isKeySorting) { + _this.listenerNode.removeEventListener( + 'wheel', + _this.handleKeyEnd, + true, + ); + + _this.listenerNode.removeEventListener( + 'mousedown', + _this.handleKeyEnd, + true, + ); + + _this.listenerNode.removeEventListener( + 'keydown', + _this.handleKeyDown, + ); + } else { + events.move.forEach(function(eventName) { + return _this.listenerNode.removeEventListener( + eventName, + _this.handleSortMove, + ); + }); + events.end.forEach(function(eventName) { + return _this.listenerNode.removeEventListener( + eventName, + _this.handleSortEnd, + ); + }); + } + } + + _this.helper.parentNode.removeChild(_this.helper); + + if (hideSortableGhost && _this.sortableGhost) { + setInlineStyles(_this.sortableGhost, { + opacity: '', + }); + } + + for (var i = 0, len = nodes.length; i < len; i++) { + var _node2 = nodes[i]; + var el = _node2.node; + _node2.edgeOffset = null; + _node2.boundingClientRect = null; + setTranslate3d(el, null); + setTransitionDuration(el, null); + _node2.translate = null; + } + + _this.autoScroller.clear(); + + _this.manager.active = null; + _this.manager.isKeySorting = false; + + _this.setState({ + sorting: false, + sortingIndex: null, + }); + + if (typeof onSortEnd === 'function') { + onSortEnd( + { + collection: collection, + newIndex: _this.newIndex, + oldIndex: _this.index, + isKeySorting: isKeySorting, + nodes: nodes, + }, + event, + ); + } + + _this.touched = false; + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'autoscroll', + function() { + var disableAutoscroll = _this.props.disableAutoscroll; + var isKeySorting = _this.manager.isKeySorting; + + if (disableAutoscroll) { + _this.autoScroller.clear(); + + return; + } + + if (isKeySorting) { + var translate = _objectSpread({}, _this.translate); + + var scrollX = 0; + var scrollY = 0; + + if (_this.axis.x) { + translate.x = Math.min( + _this.maxTranslate.x, + Math.max(_this.minTranslate.x, _this.translate.x), + ); + scrollX = _this.translate.x - translate.x; + } + + if (_this.axis.y) { + translate.y = Math.min( + _this.maxTranslate.y, + Math.max(_this.minTranslate.y, _this.translate.y), + ); + scrollY = _this.translate.y - translate.y; + } + + _this.translate = translate; + setTranslate3d(_this.helper, _this.translate); + _this.scrollContainer.scrollLeft += scrollX; + _this.scrollContainer.scrollTop += scrollY; + return; + } + + _this.autoScroller.update({ + height: _this.height, + maxTranslate: _this.maxTranslate, + minTranslate: _this.minTranslate, + translate: _this.translate, + width: _this.width, + }); + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'onAutoScroll', + function(offset) { + _this.translate.x += offset.left; + _this.translate.y += offset.top; + + _this.animateNodes(); + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleKeyDown', + function(event) { + var keyCode = event.keyCode; + var _this$props5 = _this.props, + shouldCancelStart = _this$props5.shouldCancelStart, + _this$props5$keyCodes = _this$props5.keyCodes, + customKeyCodes = + _this$props5$keyCodes === void 0 ? {} : _this$props5$keyCodes; + + var keyCodes = _objectSpread({}, defaultKeyCodes, customKeyCodes); + + if ( + (_this.manager.active && !_this.manager.isKeySorting) || + (!_this.manager.active && + (!keyCodes.lift.includes(keyCode) || + shouldCancelStart(event) || + !_this.isValidSortingTarget(event))) + ) { + return; + } + + event.stopPropagation(); + event.preventDefault(); + + if (keyCodes.lift.includes(keyCode) && !_this.manager.active) { + _this.keyLift(event); + } else if ( + keyCodes.drop.includes(keyCode) && + _this.manager.active + ) { + _this.keyDrop(event); + } else if (keyCodes.cancel.includes(keyCode)) { + _this.newIndex = _this.manager.active.index; + + _this.keyDrop(event); + } else if (keyCodes.up.includes(keyCode)) { + _this.keyMove(-1); + } else if (keyCodes.down.includes(keyCode)) { + _this.keyMove(1); + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'keyLift', + function(event) { + var target = event.target; + var node = closest(target, function(el) { + return el.sortableInfo != null; + }); + var _node$sortableInfo2 = node.sortableInfo, + index = _node$sortableInfo2.index, + collection = _node$sortableInfo2.collection; + _this.initialFocusedNode = target; + _this.manager.isKeySorting = true; + _this.manager.active = { + index: index, + collection: collection, + }; + + _this.handlePress(event); + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'keyMove', + function(shift) { + var nodes = _this.manager.getOrderedRefs(); + + var lastIndex = nodes[nodes.length - 1].node.sortableInfo.index; + var newIndex = _this.newIndex + shift; + var prevIndex = _this.newIndex; + + if (newIndex < 0 || newIndex > lastIndex) { + return; + } + + _this.prevIndex = prevIndex; + _this.newIndex = newIndex; + var targetIndex = getTargetIndex( + _this.newIndex, + _this.prevIndex, + _this.index, + ); + var target = nodes.find(function(_ref2) { + var node = _ref2.node; + return node.sortableInfo.index === targetIndex; + }); + var targetNode = target.node; + var scrollDelta = _this.containerScrollDelta; + var targetBoundingClientRect = + target.boundingClientRect || + getScrollAdjustedBoundingClientRect(targetNode, scrollDelta); + var targetTranslate = target.translate || { + x: 0, + y: 0, + }; + var targetPosition = { + top: + targetBoundingClientRect.top + + targetTranslate.y - + scrollDelta.top, + left: + targetBoundingClientRect.left + + targetTranslate.x - + scrollDelta.left, + }; + var shouldAdjustForSize = prevIndex < newIndex; + var sizeAdjustment = { + x: + shouldAdjustForSize && _this.axis.x + ? targetNode.offsetWidth - _this.width + : 0, + y: + shouldAdjustForSize && _this.axis.y + ? targetNode.offsetHeight - _this.height + : 0, + }; + + _this.handleSortMove({ + pageX: targetPosition.left + sizeAdjustment.x, + pageY: targetPosition.top + sizeAdjustment.y, + ignoreTransition: shift === 0, + }); + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'keyDrop', + function(event) { + _this.handleSortEnd(event); + + if (_this.initialFocusedNode) { + _this.initialFocusedNode.focus(); + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'handleKeyEnd', + function(event) { + if (_this.manager.active) { + _this.keyDrop(event); + } + }, + ); + + _defineProperty( + _assertThisInitialized(_assertThisInitialized(_this)), + 'isValidSortingTarget', + function(event) { + var useDragHandle = _this.props.useDragHandle; + var target = event.target; + var node = closest(target, function(el) { + return el.sortableInfo != null; + }); + return ( + node && + node.sortableInfo && + !node.sortableInfo.disabled && + (useDragHandle ? isSortableHandle(target) : target.sortableInfo) + ); + }, + ); + + validateProps(props); + _this.manager = new Manager(); + _this.events = { + end: _this.handleEnd, + move: _this.handleMove, + start: _this.handleStart, + }; + return _this; + } + + _createClass(WithSortableContainer, [ + { + key: 'getChildContext', + value: function getChildContext() { + return { + manager: this.manager, + }; + }, + }, + { + key: 'componentDidMount', + value: function componentDidMount() { + var _this2 = this; + + var useWindowAsScrollContainer = this.props + .useWindowAsScrollContainer; + var container = this.getContainer(); + Promise.resolve(container).then(function(containerNode) { + _this2.container = containerNode; + _this2.document = _this2.container.ownerDocument || document; + var contentWindow = + _this2.props.contentWindow || + _this2.document.defaultView || + window; + _this2.contentWindow = + typeof contentWindow === 'function' + ? contentWindow() + : contentWindow; + _this2.scrollContainer = useWindowAsScrollContainer + ? _this2.document.scrollingElement || + _this2.document.documentElement + : getScrollingParent( + _this2.container, + _this2.props.scrollContainer, + ) || _this2.container; + _this2.autoScroller = new AutoScroller( + _this2.scrollContainer, + _this2.onAutoScroll, + ); + Object.keys(_this2.events).forEach(function(key) { + return events[key].forEach(function(eventName) { + return _this2.container.addEventListener( + eventName, + _this2.events[key], + false, + ); + }); + }); + + _this2.container.addEventListener( + 'keydown', + _this2.handleKeyDown, + ); + }); + }, + }, + { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + var _this3 = this; + + if (this.helper && this.helper.parentNode) { + this.helper.parentNode.removeChild(this.helper); + } + + if (!this.container) { + return; + } + + Object.keys(this.events).forEach(function(key) { + return events[key].forEach(function(eventName) { + return _this3.container.removeEventListener( + eventName, + _this3.events[key], + ); + }); + }); + this.container.removeEventListener('keydown', this.handleKeyDown); + }, + }, + { + key: 'updateHelperPosition', + value: function updateHelperPosition(event) { + var _this$props6 = this.props, + lockAxis = _this$props6.lockAxis, + lockOffset = _this$props6.lockOffset, + lockToContainerEdges = _this$props6.lockToContainerEdges, + transitionDuration = _this$props6.transitionDuration, + _this$props6$keyboard = + _this$props6.keyboardSortingTransitionDuration, + keyboardSortingTransitionDuration = + _this$props6$keyboard === void 0 + ? transitionDuration + : _this$props6$keyboard; + var isKeySorting = this.manager.isKeySorting; + var ignoreTransition = event.ignoreTransition; + var offset = getPosition(event); + var translate = { + x: offset.x - this.initialOffset.x, + y: offset.y - this.initialOffset.y, + }; + translate.y -= window.pageYOffset - this.initialWindowScroll.top; + translate.x -= window.pageXOffset - this.initialWindowScroll.left; + this.translate = translate; + + if (lockToContainerEdges) { + var _getLockPixelOffsets = getLockPixelOffsets({ + height: this.height, + lockOffset: lockOffset, + width: this.width, + }), + _getLockPixelOffsets2 = _slicedToArray(_getLockPixelOffsets, 2), + minLockOffset = _getLockPixelOffsets2[0], + maxLockOffset = _getLockPixelOffsets2[1]; + + var minOffset = { + x: this.width / 2 - minLockOffset.x, + y: this.height / 2 - minLockOffset.y, + }; + var maxOffset = { + x: this.width / 2 - maxLockOffset.x, + y: this.height / 2 - maxLockOffset.y, + }; + translate.x = limit( + this.minTranslate.x + minOffset.x, + this.maxTranslate.x - maxOffset.x, + translate.x, + ); + translate.y = limit( + this.minTranslate.y + minOffset.y, + this.maxTranslate.y - maxOffset.y, + translate.y, + ); + } + + if (lockAxis === 'x') { + translate.y = 0; + } else if (lockAxis === 'y') { + translate.x = 0; + } + + if ( + isKeySorting && + keyboardSortingTransitionDuration && + !ignoreTransition + ) { + setTransitionDuration( + this.helper, + keyboardSortingTransitionDuration, + ); + } + + setTranslate3d(this.helper, translate); + }, + }, + { + key: 'animateNodes', + value: function animateNodes() { + var _this$props7 = this.props, + transitionDuration = _this$props7.transitionDuration, + hideSortableGhost = _this$props7.hideSortableGhost, + onSortOver = _this$props7.onSortOver; + var containerScrollDelta = this.containerScrollDelta, + windowScrollDelta = this.windowScrollDelta; + var nodes = this.manager.getOrderedRefs(); + var sortingOffset = { + left: + this.offsetEdge.left + + this.translate.x + + containerScrollDelta.left, + top: + this.offsetEdge.top + + this.translate.y + + containerScrollDelta.top, + }; + var isKeySorting = this.manager.isKeySorting; + var prevIndex = this.newIndex; + this.newIndex = null; + + for (var i = 0, len = nodes.length; i < len; i++) { + var _node3 = nodes[i].node; + var index = _node3.sortableInfo.index; + + var width = _node3.getBoundingClientRect().width; + + var height = _node3.getBoundingClientRect().height; + + var offset = { + height: this.height > height ? height / 2 : this.height / 2, + width: this.width > width ? width / 2 : this.width / 2, + }; + var mustShiftBackward = + isKeySorting && index > this.index && index <= prevIndex; + var mustShiftForward = + isKeySorting && index < this.index && index >= prevIndex; + var translate = { + x: 0, + y: 0, + }; + var edgeOffset = nodes[i].edgeOffset; + + if (!edgeOffset) { + edgeOffset = getEdgeOffset(_node3, this.container); + nodes[i].edgeOffset = edgeOffset; + + if (isKeySorting) { + nodes[ + i + ].boundingClientRect = getScrollAdjustedBoundingClientRect( + _node3, + containerScrollDelta, + ); + } + } + + var nextNode = i < nodes.length - 1 && nodes[i + 1]; + var prevNode = i > 0 && nodes[i - 1]; + + if (nextNode && !nextNode.edgeOffset) { + nextNode.edgeOffset = getEdgeOffset( + nextNode.node, + this.container, + ); + + if (isKeySorting) { + nextNode.boundingClientRect = getScrollAdjustedBoundingClientRect( + nextNode.node, + containerScrollDelta, + ); + } + } + + if (index === this.index) { + if (hideSortableGhost) { + this.sortableGhost = _node3; + setInlineStyles(_node3, { + opacity: 0, + }); + } + + continue; + } + + if (transitionDuration) { + setTransitionDuration(_node3, transitionDuration); + } + + if (this.axis.x) { + if (this.axis.y) { + if ( + mustShiftForward || + (index < this.index && + ((sortingOffset.left + + windowScrollDelta.left - + offset.width <= + edgeOffset.left && + sortingOffset.top + windowScrollDelta.top <= + edgeOffset.top + offset.height) || + sortingOffset.top + + windowScrollDelta.top + + offset.height <= + edgeOffset.top)) + ) { + translate.x = this.width + this.marginOffset.x; + + if ( + edgeOffset.left + translate.x > + this.containerBoundingRect.width - offset.width + ) { + if (nextNode) { + translate.x = + nextNode.edgeOffset.left - edgeOffset.left; + translate.y = nextNode.edgeOffset.top - edgeOffset.top; + } + } + + if (this.newIndex === null) { + this.newIndex = index; + } + } else if ( + mustShiftBackward || + (index > this.index && + ((sortingOffset.left + + windowScrollDelta.left + + offset.width >= + edgeOffset.left && + sortingOffset.top + + windowScrollDelta.top + + offset.height >= + edgeOffset.top) || + sortingOffset.top + + windowScrollDelta.top + + offset.height >= + edgeOffset.top + height)) + ) { + translate.x = -(this.width + this.marginOffset.x); + + if ( + edgeOffset.left + translate.x < + this.containerBoundingRect.left + offset.width + ) { + if (prevNode) { + translate.x = + prevNode.edgeOffset.left - edgeOffset.left; + translate.y = prevNode.edgeOffset.top - edgeOffset.top; + } + } + + this.newIndex = index; + } + } else { + if ( + mustShiftBackward || + (index > this.index && + sortingOffset.left + + windowScrollDelta.left + + offset.width >= + edgeOffset.left) + ) { + translate.x = -(this.width + this.marginOffset.x); + this.newIndex = index; + } else if ( + mustShiftForward || + (index < this.index && + sortingOffset.left + windowScrollDelta.left <= + edgeOffset.left + offset.width) + ) { + translate.x = this.width + this.marginOffset.x; + + if (this.newIndex == null) { + this.newIndex = index; + } + } + } + } else if (this.axis.y) { + if ( + mustShiftBackward || + (index > this.index && + sortingOffset.top + + windowScrollDelta.top + + this.boundingClientRect.height >= + edgeOffset.top + offset.height) + ) { + translate.y = -(this.height + this.marginOffset.y); + this.newIndex = index; + } else if ( + mustShiftForward || + (index < this.index && + sortingOffset.top + windowScrollDelta.top <= + edgeOffset.top + offset.height) + ) { + translate.y = this.height + this.marginOffset.y; + + if (this.newIndex == null) { + this.newIndex = index; + } + } + } + + setTranslate3d(_node3, translate); + nodes[i].translate = translate; + } + + if (this.newIndex == null) { + this.newIndex = this.index; + } + + if (isKeySorting) { + this.newIndex = prevIndex; + } + + var oldIndex = isKeySorting ? this.prevIndex : prevIndex; + + if (onSortOver && this.newIndex !== oldIndex) { + onSortOver({ + collection: this.manager.active.collection, + index: this.index, + newIndex: this.newIndex, + oldIndex: oldIndex, + isKeySorting: isKeySorting, + nodes: nodes, + helper: this.helper, + }); + } + }, + }, + { + key: 'getWrappedInstance', + value: function getWrappedInstance() { + invariant( + config.withRef, + 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableContainer() call', + ); + return this.refs.wrappedInstance; + }, + }, + { + key: 'getContainer', + value: function getContainer() { + var getContainer = this.props.getContainer; + + if (typeof getContainer !== 'function') { + return reactDom.findDOMNode(this); + } + + return getContainer( + config.withRef ? this.getWrappedInstance() : undefined, + ); + }, + }, + { + key: 'render', + value: function render() { + var ref = config.withRef ? 'wrappedInstance' : null; + return React.createElement( + WrappedComponent, + _extends( + { + ref: ref, + }, + omit(this.props, omittedProps), + ), + ); + }, + }, + { + key: 'helperContainer', + get: function get() { + var helperContainer = this.props.helperContainer; + + if (typeof helperContainer === 'function') { + return helperContainer(); + } + + return this.props.helperContainer || this.document.body; + }, + }, + { + key: 'containerScrollDelta', + get: function get() { + var useWindowAsScrollContainer = this.props + .useWindowAsScrollContainer; + + if (useWindowAsScrollContainer) { + return { + left: 0, + top: 0, + }; + } + + return { + left: this.scrollContainer.scrollLeft - this.initialScroll.left, + top: this.scrollContainer.scrollTop - this.initialScroll.top, + }; + }, + }, + { + key: 'windowScrollDelta', + get: function get() { + return { + left: + this.contentWindow.pageXOffset - this.initialWindowScroll.left, + top: + this.contentWindow.pageYOffset - this.initialWindowScroll.top, + }; + }, + }, + ]); + + return WithSortableContainer; + })(React.Component)), + _defineProperty( + _class, + 'displayName', + provideDisplayName('sortableList', WrappedComponent), + ), + _defineProperty(_class, 'defaultProps', defaultProps), + _defineProperty(_class, 'propTypes', propTypes), + _defineProperty(_class, 'childContextTypes', { + manager: PropTypes.object.isRequired, + }), + _temp + ); +} + +var propTypes$1 = { + index: PropTypes.number.isRequired, + collection: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), + disabled: PropTypes.bool, +}; +var omittedProps$1 = Object.keys(propTypes$1); +function sortableElement(WrappedComponent) { + var _class, _temp; + + var config = + arguments.length > 1 && arguments[1] !== undefined + ? arguments[1] + : { + withRef: false, + }; + return ( + (_temp = _class = (function(_React$Component) { + _inherits(WithSortableElement, _React$Component); + + function WithSortableElement() { + _classCallCheck(this, WithSortableElement); + + return _possibleConstructorReturn( + this, + _getPrototypeOf(WithSortableElement).apply(this, arguments), + ); + } + + _createClass(WithSortableElement, [ + { + key: 'componentDidMount', + value: function componentDidMount() { + this.register(); + }, + }, + { + key: 'componentDidUpdate', + value: function componentDidUpdate(prevProps) { + if (this.node) { + if (prevProps.index !== this.props.index) { + this.node.sortableInfo.index = this.props.index; + } + + if (prevProps.disabled !== this.props.disabled) { + this.node.sortableInfo.disabled = this.props.disabled; + } + } + + if (prevProps.collection !== this.props.collection) { + this.unregister(prevProps.collection); + this.register(); + } + }, + }, + { + key: 'componentWillUnmount', + value: function componentWillUnmount() { + this.unregister(); + }, + }, + { + key: 'register', + value: function register() { + var _this$props = this.props, + collection = _this$props.collection, + disabled = _this$props.disabled, + index = _this$props.index; + var node = reactDom.findDOMNode(this); + node.sortableInfo = { + collection: collection, + disabled: disabled, + index: index, + manager: this.context.manager, + }; + this.node = node; + this.ref = { + node: node, + }; + this.context.manager.add(collection, this.ref); + }, + }, + { + key: 'unregister', + value: function unregister() { + var collection = + arguments.length > 0 && arguments[0] !== undefined + ? arguments[0] + : this.props.collection; + this.context.manager.remove(collection, this.ref); + }, + }, + { + key: 'getWrappedInstance', + value: function getWrappedInstance() { + invariant( + config.withRef, + 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableElement() call', + ); + return this.refs.wrappedInstance; + }, + }, + { + key: 'render', + value: function render() { + var ref = config.withRef ? 'wrappedInstance' : null; + return React.createElement( + WrappedComponent, + _extends( + { + ref: ref, + }, + omit(this.props, omittedProps$1), + ), + ); + }, + }, + ]); + + return WithSortableElement; + })(React.Component)), + _defineProperty( + _class, + 'displayName', + provideDisplayName('sortableElement', WrappedComponent), + ), + _defineProperty(_class, 'contextTypes', { + manager: PropTypes.object.isRequired, + }), + _defineProperty(_class, 'propTypes', propTypes$1), + _defineProperty(_class, 'defaultProps', { + collection: 0, + }), + _temp + ); +} + +exports.SortableContainer = sortableContainer; +exports.sortableContainer = sortableContainer; +exports.SortableElement = sortableElement; +exports.sortableElement = sortableElement; +exports.SortableHandle = sortableHandle; +exports.sortableHandle = sortableHandle; +exports.arrayMove = arrayMove; \ No newline at end of file diff --git a/dist/react-sortable-hoc.umd.js b/dist/react-sortable-hoc.umd.js new file mode 100644 index 000000000..817c49108 --- /dev/null +++ b/dist/react-sortable-hoc.umd.js @@ -0,0 +1,1996 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('prop-types'), require('react-dom')) : + typeof define === 'function' && define.amd ? define(['exports', 'react', 'prop-types', 'react-dom'], factory) : + (global = global || self, factory(global.SortableHOC = {}, global.React, global.PropTypes, global.ReactDOM)); +}(this, (function (exports, React, PropTypes, reactDom) { 'use strict'; + + PropTypes = PropTypes && Object.prototype.hasOwnProperty.call(PropTypes, 'default') ? PropTypes['default'] : PropTypes; + + function unwrapExports (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; + } + + function createCommonjsModule(fn, module) { + return module = { exports: {} }, fn(module, module.exports), module.exports; + } + + var _extends_1 = createCommonjsModule(function (module) { + function _extends() { + module.exports = _extends = Object.assign || function (target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i]; + + for (var key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + target[key] = source[key]; + } + } + } + + return target; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + return _extends.apply(this, arguments); + } + + module.exports = _extends; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + var _extends = unwrapExports(_extends_1); + + var arrayWithHoles = createCommonjsModule(function (module) { + function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; + } + + module.exports = _arrayWithHoles; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + unwrapExports(arrayWithHoles); + + var iterableToArrayLimit = createCommonjsModule(function (module) { + function _iterableToArrayLimit(arr, i) { + if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + module.exports = _iterableToArrayLimit; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + unwrapExports(iterableToArrayLimit); + + var arrayLikeToArray = createCommonjsModule(function (module) { + function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + + return arr2; + } + + module.exports = _arrayLikeToArray; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + unwrapExports(arrayLikeToArray); + + var unsupportedIterableToArray = createCommonjsModule(function (module) { + function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); + } + + module.exports = _unsupportedIterableToArray; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + unwrapExports(unsupportedIterableToArray); + + var nonIterableRest = createCommonjsModule(function (module) { + function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + module.exports = _nonIterableRest; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + unwrapExports(nonIterableRest); + + var slicedToArray = createCommonjsModule(function (module) { + function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); + } + + module.exports = _slicedToArray; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + var _slicedToArray = unwrapExports(slicedToArray); + + var classCallCheck = createCommonjsModule(function (module) { + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + + module.exports = _classCallCheck; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + var _classCallCheck = unwrapExports(classCallCheck); + + var createClass = createCommonjsModule(function (module) { + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; + } + + module.exports = _createClass; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + var _createClass = unwrapExports(createClass); + + var assertThisInitialized = createCommonjsModule(function (module) { + function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; + } + + module.exports = _assertThisInitialized; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + var _assertThisInitialized = unwrapExports(assertThisInitialized); + + var setPrototypeOf = createCommonjsModule(function (module) { + function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + return _setPrototypeOf(o, p); + } + + module.exports = _setPrototypeOf; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + unwrapExports(setPrototypeOf); + + var inherits = createCommonjsModule(function (module) { + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) setPrototypeOf(subClass, superClass); + } + + module.exports = _inherits; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + var _inherits = unwrapExports(inherits); + + var _typeof_1 = createCommonjsModule(function (module) { + function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + module.exports = _typeof = function _typeof(obj) { + return typeof obj; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + } else { + module.exports = _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + } + + return _typeof(obj); + } + + module.exports = _typeof; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + unwrapExports(_typeof_1); + + var possibleConstructorReturn = createCommonjsModule(function (module) { + var _typeof = _typeof_1["default"]; + + + + function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } + + return assertThisInitialized(self); + } + + module.exports = _possibleConstructorReturn; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + var _possibleConstructorReturn = unwrapExports(possibleConstructorReturn); + + var getPrototypeOf = createCommonjsModule(function (module) { + function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + module.exports["default"] = module.exports, module.exports.__esModule = true; + return _getPrototypeOf(o); + } + + module.exports = _getPrototypeOf; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + var _getPrototypeOf = unwrapExports(getPrototypeOf); + + var defineProperty = createCommonjsModule(function (module) { + function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; + } + + module.exports = _defineProperty; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + var _defineProperty = unwrapExports(defineProperty); + + /** + * Copyright (c) 2013-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + + var invariant = function(condition, format, a, b, c, d, e, f) { + { + if (format === undefined) { + throw new Error('invariant requires an error message argument'); + } + } + + if (!condition) { + var error; + if (format === undefined) { + error = new Error( + 'Minified exception occurred; use the non-minified dev environment ' + + 'for the full error message and additional helpful warnings.' + ); + } else { + var args = [a, b, c, d, e, f]; + var argIndex = 0; + error = new Error( + format.replace(/%s/g, function() { return args[argIndex++]; }) + ); + error.name = 'Invariant Violation'; + } + + error.framesToPop = 1; // we don't care about invariant's own frame + throw error; + } + }; + + var invariant_1 = invariant; + + var Manager = function () { + function Manager() { + _classCallCheck(this, Manager); + + _defineProperty(this, "refs", {}); + } + + _createClass(Manager, [{ + key: "add", + value: function add(collection, ref) { + if (!this.refs[collection]) { + this.refs[collection] = []; + } + + this.refs[collection].push(ref); + } + }, { + key: "remove", + value: function remove(collection, ref) { + var index = this.getIndex(collection, ref); + + if (index !== -1) { + this.refs[collection].splice(index, 1); + } + } + }, { + key: "isActive", + value: function isActive() { + return this.active; + } + }, { + key: "getActive", + value: function getActive() { + var _this = this; + + return this.refs[this.active.collection].find(function (_ref) { + var node = _ref.node; + return node.sortableInfo.index == _this.active.index; + }); + } + }, { + key: "getIndex", + value: function getIndex(collection, ref) { + return this.refs[collection].indexOf(ref); + } + }, { + key: "getOrderedRefs", + value: function getOrderedRefs() { + var collection = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.active.collection; + return this.refs[collection].sort(sortByIndex); + } + }]); + + return Manager; + }(); + + function sortByIndex(_ref2, _ref3) { + var index1 = _ref2.node.sortableInfo.index; + var index2 = _ref3.node.sortableInfo.index; + return index1 - index2; + } + + var arrayWithoutHoles = createCommonjsModule(function (module) { + function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); + } + + module.exports = _arrayWithoutHoles; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + unwrapExports(arrayWithoutHoles); + + var iterableToArray = createCommonjsModule(function (module) { + function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); + } + + module.exports = _iterableToArray; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + unwrapExports(iterableToArray); + + var nonIterableSpread = createCommonjsModule(function (module) { + function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); + } + + module.exports = _nonIterableSpread; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + unwrapExports(nonIterableSpread); + + var toConsumableArray = createCommonjsModule(function (module) { + function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); + } + + module.exports = _toConsumableArray; + module.exports["default"] = module.exports, module.exports.__esModule = true; + }); + + var _toConsumableArray = unwrapExports(toConsumableArray); + + function arrayMove(array, from, to) { + { + if (typeof console !== 'undefined') { + console.warn("Deprecation warning: arrayMove will no longer be exported by 'react-sortable-hoc' in the next major release. Please install the `array-move` package locally instead. https://www.npmjs.com/package/array-move"); + } + } + + array = array.slice(); + array.splice(to < 0 ? array.length + to : to, 0, array.splice(from, 1)[0]); + return array; + } + function omit(obj, keysToOmit) { + return Object.keys(obj).reduce(function (acc, key) { + if (keysToOmit.indexOf(key) === -1) { + acc[key] = obj[key]; + } + + return acc; + }, {}); + } + var events = { + end: ['touchend', 'touchcancel', 'mouseup'], + move: ['touchmove', 'mousemove'], + start: ['touchstart', 'mousedown'] + }; + var vendorPrefix = function () { + if (typeof window === 'undefined' || typeof document === 'undefined') { + return ''; + } + + var styles = window.getComputedStyle(document.documentElement, '') || ['-moz-hidden-iframe']; + var pre = (Array.prototype.slice.call(styles).join('').match(/-(moz|webkit|ms)-/) || styles.OLink === '' && ['', 'o'])[1]; + + switch (pre) { + case 'ms': + return 'ms'; + + default: + return pre && pre.length ? pre[0].toUpperCase() + pre.substr(1) : ''; + } + }(); + function setInlineStyles(node, styles) { + Object.keys(styles).forEach(function (key) { + node.style[key] = styles[key]; + }); + } + function setTranslate3d(node, translate) { + node.style["".concat(vendorPrefix, "Transform")] = translate == null ? '' : "translate3d(".concat(translate.x, "px,").concat(translate.y, "px,0)"); + } + function setTransitionDuration(node, duration) { + node.style["".concat(vendorPrefix, "TransitionDuration")] = duration == null ? '' : "".concat(duration, "ms"); + } + function closest(el, fn) { + while (el) { + if (fn(el)) { + return el; + } + + el = el.parentNode; + } + + return null; + } + function limit(min, max, value) { + return Math.max(min, Math.min(value, max)); + } + + function getPixelValue(stringValue) { + if (stringValue.substr(-2) === 'px') { + return parseFloat(stringValue); + } + + return 0; + } + + function getElementMargin(element) { + var style = window.getComputedStyle(element); + return { + bottom: getPixelValue(style.marginBottom), + left: getPixelValue(style.marginLeft), + right: getPixelValue(style.marginRight), + top: getPixelValue(style.marginTop) + }; + } + function provideDisplayName(prefix, Component) { + var componentName = Component.displayName || Component.name; + return componentName ? "".concat(prefix, "(").concat(componentName, ")") : prefix; + } + function getScrollAdjustedBoundingClientRect(node, scrollDelta) { + var boundingClientRect = node.getBoundingClientRect(); + return { + top: boundingClientRect.top + scrollDelta.top, + left: boundingClientRect.left + scrollDelta.left + }; + } + function getPosition(event) { + if (event.touches && event.touches.length) { + return { + x: event.touches[0].pageX, + y: event.touches[0].pageY + }; + } else if (event.changedTouches && event.changedTouches.length) { + return { + x: event.changedTouches[0].pageX, + y: event.changedTouches[0].pageY + }; + } else { + return { + x: event.pageX, + y: event.pageY + }; + } + } + function isTouchEvent(event) { + return event.touches && event.touches.length || event.changedTouches && event.changedTouches.length; + } + function getEdgeOffset(node, parent) { + var offset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : { + left: 0, + top: 0 + }; + + if (!node) { + return undefined; + } + + var nodeOffset = { + left: offset.left + node.offsetLeft, + top: offset.top + node.offsetTop + }; + + if (node.parentNode === parent) { + return nodeOffset; + } + + return getEdgeOffset(node.parentNode, parent, nodeOffset); + } + function getTargetIndex(newIndex, prevIndex, oldIndex) { + if (newIndex < oldIndex && newIndex > prevIndex) { + return newIndex - 1; + } else if (newIndex > oldIndex && newIndex < prevIndex) { + return newIndex + 1; + } else { + return newIndex; + } + } + function getLockPixelOffset(_ref) { + var lockOffset = _ref.lockOffset, + width = _ref.width, + height = _ref.height; + var offsetX = lockOffset; + var offsetY = lockOffset; + var unit = 'px'; + + if (typeof lockOffset === 'string') { + var match = /^[+-]?\d*(?:\.\d*)?(px|%)$/.exec(lockOffset); + invariant_1(match !== null, 'lockOffset value should be a number or a string of a ' + 'number followed by "px" or "%". Given %s', lockOffset); + offsetX = parseFloat(lockOffset); + offsetY = parseFloat(lockOffset); + unit = match[1]; + } + + invariant_1(isFinite(offsetX) && isFinite(offsetY), 'lockOffset value should be a finite. Given %s', lockOffset); + + if (unit === '%') { + offsetX = offsetX * width / 100; + offsetY = offsetY * height / 100; + } + + return { + x: offsetX, + y: offsetY + }; + } + function getLockPixelOffsets(_ref2) { + var height = _ref2.height, + width = _ref2.width, + lockOffset = _ref2.lockOffset; + var offsets = Array.isArray(lockOffset) ? lockOffset : [lockOffset, lockOffset]; + invariant_1(offsets.length === 2, 'lockOffset prop of SortableContainer should be a single ' + 'value or an array of exactly two values. Given %s', lockOffset); + + var _offsets = _slicedToArray(offsets, 2), + minLockOffset = _offsets[0], + maxLockOffset = _offsets[1]; + + return [getLockPixelOffset({ + height: height, + lockOffset: minLockOffset, + width: width + }), getLockPixelOffset({ + height: height, + lockOffset: maxLockOffset, + width: width + })]; + } + + function isScrollable(el) { + var computedStyle = window.getComputedStyle(el); + var overflowRegex = /(auto|scroll)/; + var properties = ['overflow', 'overflowX', 'overflowY']; + return properties.find(function (property) { + return overflowRegex.test(computedStyle[property]); + }); + } + + function getScrollingParent(el) { + var container = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + + if (container) { + return document.querySelector(container); + } + + if (!(el instanceof HTMLElement)) { + return null; + } else if (isScrollable(el)) { + return el; + } else { + return getScrollingParent(el.parentNode); + } + } + function getContainerGridGap(element) { + var style = window.getComputedStyle(element); + + if (style.display === 'grid') { + return { + x: getPixelValue(style.gridColumnGap), + y: getPixelValue(style.gridRowGap) + }; + } + + return { + x: 0, + y: 0 + }; + } + var KEYCODE = { + TAB: 9, + ESC: 27, + SPACE: 32, + LEFT: 37, + UP: 38, + RIGHT: 39, + DOWN: 40 + }; + var NodeType = { + Anchor: 'A', + Button: 'BUTTON', + Canvas: 'CANVAS', + Input: 'INPUT', + Option: 'OPTION', + Textarea: 'TEXTAREA', + Select: 'SELECT' + }; + function cloneNode(node) { + var selector = 'input, textarea, select, canvas, [contenteditable]'; + var fields = node.querySelectorAll(selector); + var clonedNode = node.cloneNode(true); + + var clonedFields = _toConsumableArray(clonedNode.querySelectorAll(selector)); + + clonedFields.forEach(function (field, i) { + if (field.type !== 'file') { + field.value = fields[i].value; + } + + if (field.type === 'radio' && field.name) { + field.name = "__sortableClone__".concat(field.name); + } + + if (field.tagName === NodeType.Canvas && fields[i].width > 0 && fields[i].height > 0) { + var destCtx = field.getContext('2d'); + destCtx.drawImage(fields[i], 0, 0); + } + }); + return clonedNode; + } + + 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; } } + function sortableHandle(WrappedComponent) { + var _class, _temp; + + var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + withRef: false + }; + return _temp = _class = function (_React$Component) { + _inherits(WithSortableHandle, _React$Component); + + var _super = _createSuper(WithSortableHandle); + + function WithSortableHandle() { + _classCallCheck(this, WithSortableHandle); + + return _super.apply(this, arguments); + } + + _createClass(WithSortableHandle, [{ + key: "componentDidMount", + value: function componentDidMount() { + var node = reactDom.findDOMNode(this); + node.sortableHandle = true; + } + }, { + key: "getWrappedInstance", + value: function getWrappedInstance() { + invariant_1(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableHandle() call'); + return this.refs.wrappedInstance; + } + }, { + key: "render", + value: function render() { + var ref = config.withRef ? 'wrappedInstance' : null; + return React.createElement(WrappedComponent, _extends({ + ref: ref + }, this.props)); + } + }]); + + return WithSortableHandle; + }(React.Component), _defineProperty(_class, "displayName", provideDisplayName('sortableHandle', WrappedComponent)), _temp; + } + function isSortableHandle(node) { + return node.sortableHandle != null; + } + + var AutoScroller = function () { + function AutoScroller(container, onScrollCallback) { + _classCallCheck(this, AutoScroller); + + this.container = container; + this.onScrollCallback = onScrollCallback; + } + + _createClass(AutoScroller, [{ + key: "clear", + value: function clear() { + if (this.interval == null) { + return; + } + + clearInterval(this.interval); + this.interval = null; + } + }, { + key: "update", + value: function update(_ref) { + var _this = this; + + var translate = _ref.translate, + minTranslate = _ref.minTranslate, + maxTranslate = _ref.maxTranslate, + width = _ref.width, + height = _ref.height; + var direction = { + x: 0, + y: 0 + }; + var speed = { + x: 1, + y: 1 + }; + var acceleration = { + x: 10, + y: 10 + }; + var _this$container = this.container, + scrollTop = _this$container.scrollTop, + scrollLeft = _this$container.scrollLeft, + scrollHeight = _this$container.scrollHeight, + scrollWidth = _this$container.scrollWidth, + clientHeight = _this$container.clientHeight, + clientWidth = _this$container.clientWidth; + var isTop = scrollTop === 0; + var isBottom = scrollHeight - scrollTop - clientHeight === 0; + var isLeft = scrollLeft === 0; + var isRight = scrollWidth - scrollLeft - clientWidth === 0; + + if (translate.y >= maxTranslate.y - height / 2 && !isBottom) { + direction.y = 1; + speed.y = acceleration.y * Math.abs((maxTranslate.y - height / 2 - translate.y) / height); + } else if (translate.x >= maxTranslate.x - width / 2 && !isRight) { + direction.x = 1; + speed.x = acceleration.x * Math.abs((maxTranslate.x - width / 2 - translate.x) / width); + } else if (translate.y <= minTranslate.y + height / 2 && !isTop) { + direction.y = -1; + speed.y = acceleration.y * Math.abs((translate.y - height / 2 - minTranslate.y) / height); + } else if (translate.x <= minTranslate.x + width / 2 && !isLeft) { + direction.x = -1; + speed.x = acceleration.x * Math.abs((translate.x - width / 2 - minTranslate.x) / width); + } + + if (this.interval) { + this.clear(); + this.isAutoScrolling = false; + } + + if (direction.x !== 0 || direction.y !== 0) { + this.interval = setInterval(function () { + _this.isAutoScrolling = true; + var offset = { + left: speed.x * direction.x, + top: speed.y * direction.y + }; + _this.container.scrollTop += offset.top; + _this.container.scrollLeft += offset.left; + + _this.onScrollCallback(offset); + }, 5); + } + } + }]); + + return AutoScroller; + }(); + + function defaultGetHelperDimensions(_ref) { + var node = _ref.node; + return { + height: node.offsetHeight, + width: node.offsetWidth + }; + } + + function defaultShouldCancelStart(event) { + var interactiveElements = [NodeType.Input, NodeType.Textarea, NodeType.Select, NodeType.Option, NodeType.Button]; + + if (interactiveElements.indexOf(event.target.tagName) !== -1) { + return true; + } + + if (closest(event.target, function (el) { + return el.contentEditable === 'true'; + })) { + return true; + } + + return false; + } + + var propTypes = { + axis: PropTypes.oneOf(['x', 'y', 'xy']), + contentWindow: PropTypes.any, + disableAutoscroll: PropTypes.bool, + distance: PropTypes.number, + getContainer: PropTypes.func, + getHelperDimensions: PropTypes.func, + helperClass: PropTypes.string, + helperContainer: PropTypes.oneOfType([PropTypes.func, typeof HTMLElement === 'undefined' ? PropTypes.any : PropTypes.instanceOf(HTMLElement)]), + hideSortableGhost: PropTypes.bool, + keyboardSortingTransitionDuration: PropTypes.number, + lockAxis: PropTypes.string, + lockOffset: PropTypes.oneOfType([PropTypes.number, PropTypes.string, PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.number, PropTypes.string]))]), + lockToContainerEdges: PropTypes.bool, + onSortEnd: PropTypes.func, + onSortMove: PropTypes.func, + onSortOver: PropTypes.func, + onSortStart: PropTypes.func, + pressDelay: PropTypes.number, + pressThreshold: PropTypes.number, + keyCodes: PropTypes.shape({ + lift: PropTypes.arrayOf(PropTypes.number), + drop: PropTypes.arrayOf(PropTypes.number), + cancel: PropTypes.arrayOf(PropTypes.number), + up: PropTypes.arrayOf(PropTypes.number), + down: PropTypes.arrayOf(PropTypes.number) + }), + shouldCancelStart: PropTypes.func, + transitionDuration: PropTypes.number, + updateBeforeSortStart: PropTypes.func, + useDragHandle: PropTypes.bool, + useWindowAsScrollContainer: PropTypes.bool + }; + var defaultKeyCodes = { + lift: [KEYCODE.SPACE], + drop: [KEYCODE.SPACE], + cancel: [KEYCODE.ESC], + up: [KEYCODE.UP, KEYCODE.LEFT], + down: [KEYCODE.DOWN, KEYCODE.RIGHT] + }; + var defaultProps = { + axis: 'y', + disableAutoscroll: false, + distance: 0, + getHelperDimensions: defaultGetHelperDimensions, + hideSortableGhost: true, + lockOffset: '50%', + lockToContainerEdges: false, + pressDelay: 0, + pressThreshold: 5, + keyCodes: defaultKeyCodes, + shouldCancelStart: defaultShouldCancelStart, + transitionDuration: 300, + useWindowAsScrollContainer: false + }; + var omittedProps = Object.keys(propTypes); + function validateProps(props) { + invariant_1(!(props.distance && props.pressDelay), 'Attempted to set both `pressDelay` and `distance` on SortableContainer, you may only use one or the other, not both at the same time.'); + } + + 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 _finallyRethrows(body, finalizer) { + try { + var result = body(); + } catch (e) { + return finalizer(true, e); + } + + if (result && result.then) { + return result.then(finalizer.bind(null, false), finalizer.bind(null, true)); + } + + return finalizer(false, result); + } + + function _createSuper$1(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$1(); 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$1() { 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; } } + function sortableContainer(WrappedComponent) { + var _class, _temp; + + var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + withRef: false + }; + return _temp = _class = function (_React$Component) { + _inherits(WithSortableContainer, _React$Component); + + var _super = _createSuper$1(WithSortableContainer); + + function WithSortableContainer(props) { + var _this; + + _classCallCheck(this, WithSortableContainer); + + _this = _super.call(this, props); + + _defineProperty(_assertThisInitialized(_this), "state", {}); + + _defineProperty(_assertThisInitialized(_this), "handleStart", function (event) { + var _this$props = _this.props, + distance = _this$props.distance, + shouldCancelStart = _this$props.shouldCancelStart; + + if (event.button === 2 || shouldCancelStart(event)) { + return; + } + + _this.touched = true; + _this.position = getPosition(event); + var node = closest(event.target, function (el) { + return el.sortableInfo != null; + }); + + if (node && node.sortableInfo && _this.nodeIsChild(node) && !_this.state.sorting) { + var useDragHandle = _this.props.useDragHandle; + var _node$sortableInfo = node.sortableInfo, + index = _node$sortableInfo.index, + collection = _node$sortableInfo.collection, + disabled = _node$sortableInfo.disabled; + + if (disabled) { + return; + } + + if (useDragHandle && !closest(event.target, isSortableHandle)) { + return; + } + + _this.manager.active = { + collection: collection, + index: index + }; + + if (!isTouchEvent(event) && event.target.tagName === NodeType.Anchor) { + event.preventDefault(); + } + + if (!distance) { + if (_this.props.pressDelay === 0) { + _this.handlePress(event); + } else { + _this.pressTimer = setTimeout(function () { + return _this.handlePress(event); + }, _this.props.pressDelay); + } + } + } + }); + + _defineProperty(_assertThisInitialized(_this), "nodeIsChild", function (node) { + return node.sortableInfo.manager === _this.manager; + }); + + _defineProperty(_assertThisInitialized(_this), "handleMove", function (event) { + var _this$props2 = _this.props, + distance = _this$props2.distance, + pressThreshold = _this$props2.pressThreshold; + + if (!_this.state.sorting && _this.touched && !_this._awaitingUpdateBeforeSortStart) { + var position = getPosition(event); + var delta = { + x: _this.position.x - position.x, + y: _this.position.y - position.y + }; + var combinedDelta = Math.abs(delta.x) + Math.abs(delta.y); + _this.delta = delta; + + if (!distance && (!pressThreshold || combinedDelta >= pressThreshold)) { + clearTimeout(_this.cancelTimer); + _this.cancelTimer = setTimeout(_this.cancel, 0); + } else if (distance && combinedDelta >= distance && _this.manager.isActive()) { + _this.handlePress(event); + } + } + }); + + _defineProperty(_assertThisInitialized(_this), "handleEnd", function () { + _this.touched = false; + + _this.cancel(); + }); + + _defineProperty(_assertThisInitialized(_this), "cancel", function () { + var distance = _this.props.distance; + var sorting = _this.state.sorting; + + if (!sorting) { + if (!distance) { + clearTimeout(_this.pressTimer); + } + + _this.manager.active = null; + } + }); + + _defineProperty(_assertThisInitialized(_this), "handlePress", function (event) { + try { + var active = _this.manager.getActive(); + + var _temp6 = function () { + if (active) { + var _temp7 = function _temp7() { + var index = _node.sortableInfo.index; + var margin = getElementMargin(_node); + var gridGap = getContainerGridGap(_this.container); + + var containerBoundingRect = _this.scrollContainer.getBoundingClientRect(); + + var dimensions = _getHelperDimensions({ + index: index, + node: _node, + collection: _collection + }); + + _this.node = _node; + _this.margin = margin; + _this.gridGap = gridGap; + _this.width = dimensions.width; + _this.height = dimensions.height; + _this.marginOffset = { + x: _this.margin.left + _this.margin.right + _this.gridGap.x, + y: Math.max(_this.margin.top, _this.margin.bottom, _this.gridGap.y) + }; + _this.boundingClientRect = _node.getBoundingClientRect(); + _this.containerBoundingRect = containerBoundingRect; + _this.index = index; + _this.newIndex = index; + _this.axis = { + x: _axis.indexOf('x') >= 0, + y: _axis.indexOf('y') >= 0 + }; + _this.offsetEdge = getEdgeOffset(_node, _this.container); + + if (_isKeySorting) { + _this.initialOffset = getPosition(_objectSpread(_objectSpread({}, event), {}, { + pageX: _this.boundingClientRect.left, + pageY: _this.boundingClientRect.top + })); + } else { + _this.initialOffset = getPosition(event); + } + + _this.initialScroll = { + left: _this.scrollContainer.scrollLeft, + top: _this.scrollContainer.scrollTop + }; + _this.initialWindowScroll = { + left: window.pageXOffset, + top: window.pageYOffset + }; + _this.helper = _this.helperContainer.appendChild(cloneNode(_node)); + setInlineStyles(_this.helper, { + boxSizing: 'border-box', + height: "".concat(_this.height, "px"), + left: "".concat(_this.boundingClientRect.left - margin.left, "px"), + pointerEvents: 'none', + position: 'fixed', + top: "".concat(_this.boundingClientRect.top - margin.top, "px"), + width: "".concat(_this.width, "px") + }); + + if (_isKeySorting) { + _this.helper.focus(); + } + + if (_hideSortableGhost) { + _this.sortableGhost = _node; + setInlineStyles(_node, { + opacity: 0 + }); + } + + _this.minTranslate = {}; + _this.maxTranslate = {}; + + if (_isKeySorting) { + var _ref = _useWindowAsScrollContainer ? { + top: 0, + left: 0, + width: _this.contentWindow.innerWidth, + height: _this.contentWindow.innerHeight + } : _this.containerBoundingRect, + containerTop = _ref.top, + containerLeft = _ref.left, + containerWidth = _ref.width, + containerHeight = _ref.height; + + var containerBottom = containerTop + containerHeight; + var containerRight = containerLeft + containerWidth; + + if (_this.axis.x) { + _this.minTranslate.x = containerLeft - _this.boundingClientRect.left; + _this.maxTranslate.x = containerRight - (_this.boundingClientRect.left + _this.width); + } + + if (_this.axis.y) { + _this.minTranslate.y = containerTop - _this.boundingClientRect.top; + _this.maxTranslate.y = containerBottom - (_this.boundingClientRect.top + _this.height); + } + } else { + if (_this.axis.x) { + _this.minTranslate.x = (_useWindowAsScrollContainer ? 0 : containerBoundingRect.left) - _this.boundingClientRect.left - _this.width / 2; + _this.maxTranslate.x = (_useWindowAsScrollContainer ? _this.contentWindow.innerWidth : containerBoundingRect.left + containerBoundingRect.width) - _this.boundingClientRect.left - _this.width / 2; + } + + if (_this.axis.y) { + _this.minTranslate.y = (_useWindowAsScrollContainer ? 0 : containerBoundingRect.top) - _this.boundingClientRect.top - _this.height / 2; + _this.maxTranslate.y = (_useWindowAsScrollContainer ? _this.contentWindow.innerHeight : containerBoundingRect.top + containerBoundingRect.height) - _this.boundingClientRect.top - _this.height / 2; + } + } + + if (_helperClass) { + _helperClass.split(' ').forEach(function (className) { + return _this.helper.classList.add(className); + }); + } + + _this.listenerNode = event.touches ? _node : _this.contentWindow; + + if (_isKeySorting) { + _this.listenerNode.addEventListener('wheel', _this.handleKeyEnd, true); + + _this.listenerNode.addEventListener('mousedown', _this.handleKeyEnd, true); + + _this.listenerNode.addEventListener('keydown', _this.handleKeyDown); + } else { + events.move.forEach(function (eventName) { + return _this.listenerNode.addEventListener(eventName, _this.handleSortMove, false); + }); + events.end.forEach(function (eventName) { + return _this.listenerNode.addEventListener(eventName, _this.handleSortEnd, false); + }); + } + + _this.setState({ + sorting: true, + sortingIndex: index + }); + + if (_onSortStart) { + _onSortStart({ + node: _node, + index: index, + collection: _collection, + isKeySorting: _isKeySorting, + nodes: _this.manager.getOrderedRefs(), + helper: _this.helper + }, event); + } + + if (_isKeySorting) { + _this.keyMove(0); + } + }; + + var _this$props3 = _this.props, + _axis = _this$props3.axis, + _getHelperDimensions = _this$props3.getHelperDimensions, + _helperClass = _this$props3.helperClass, + _hideSortableGhost = _this$props3.hideSortableGhost, + updateBeforeSortStart = _this$props3.updateBeforeSortStart, + _onSortStart = _this$props3.onSortStart, + _useWindowAsScrollContainer = _this$props3.useWindowAsScrollContainer; + var _node = active.node, + _collection = active.collection; + var _isKeySorting = _this.manager.isKeySorting; + + var _temp8 = function () { + if (typeof updateBeforeSortStart === 'function') { + _this._awaitingUpdateBeforeSortStart = true; + + var _temp9 = _finallyRethrows(function () { + var index = _node.sortableInfo.index; + return Promise.resolve(updateBeforeSortStart({ + collection: _collection, + index: index, + node: _node, + isKeySorting: _isKeySorting + }, event)).then(function () {}); + }, function (_wasThrown, _result) { + _this._awaitingUpdateBeforeSortStart = false; + if (_wasThrown) throw _result; + return _result; + }); + + if (_temp9 && _temp9.then) return _temp9.then(function () {}); + } + }(); + + return _temp8 && _temp8.then ? _temp8.then(_temp7) : _temp7(_temp8); + } + }(); + + return Promise.resolve(_temp6 && _temp6.then ? _temp6.then(function () {}) : void 0); + } catch (e) { + return Promise.reject(e); + } + }); + + _defineProperty(_assertThisInitialized(_this), "handleSortMove", function (event) { + var onSortMove = _this.props.onSortMove; + + if (typeof event.preventDefault === 'function') { + event.preventDefault(); + } + + _this.updateHelperPosition(event); + + _this.animateNodes(); + + _this.autoscroll(); + + if (onSortMove) { + onSortMove(event); + } + }); + + _defineProperty(_assertThisInitialized(_this), "handleSortEnd", function (event) { + var _this$props4 = _this.props, + hideSortableGhost = _this$props4.hideSortableGhost, + onSortEnd = _this$props4.onSortEnd; + var _this$manager = _this.manager, + collection = _this$manager.active.collection, + isKeySorting = _this$manager.isKeySorting; + + var nodes = _this.manager.getOrderedRefs(); + + if (_this.listenerNode) { + if (isKeySorting) { + _this.listenerNode.removeEventListener('wheel', _this.handleKeyEnd, true); + + _this.listenerNode.removeEventListener('mousedown', _this.handleKeyEnd, true); + + _this.listenerNode.removeEventListener('keydown', _this.handleKeyDown); + } else { + events.move.forEach(function (eventName) { + return _this.listenerNode.removeEventListener(eventName, _this.handleSortMove); + }); + events.end.forEach(function (eventName) { + return _this.listenerNode.removeEventListener(eventName, _this.handleSortEnd); + }); + } + } + + _this.helper.parentNode.removeChild(_this.helper); + + if (hideSortableGhost && _this.sortableGhost) { + setInlineStyles(_this.sortableGhost, { + opacity: '' + }); + } + + for (var i = 0, len = nodes.length; i < len; i++) { + var _node2 = nodes[i]; + var el = _node2.node; + _node2.edgeOffset = null; + _node2.boundingClientRect = null; + setTranslate3d(el, null); + setTransitionDuration(el, null); + _node2.translate = null; + } + + _this.autoScroller.clear(); + + _this.manager.active = null; + _this.manager.isKeySorting = false; + + _this.setState({ + sorting: false, + sortingIndex: null + }); + + if (typeof onSortEnd === 'function') { + onSortEnd({ + collection: collection, + newIndex: _this.newIndex, + oldIndex: _this.index, + isKeySorting: isKeySorting, + nodes: nodes + }, event); + } + + _this.touched = false; + }); + + _defineProperty(_assertThisInitialized(_this), "autoscroll", function () { + var disableAutoscroll = _this.props.disableAutoscroll; + var isKeySorting = _this.manager.isKeySorting; + + if (disableAutoscroll) { + _this.autoScroller.clear(); + + return; + } + + if (isKeySorting) { + var translate = _objectSpread({}, _this.translate); + + var scrollX = 0; + var scrollY = 0; + + if (_this.axis.x) { + translate.x = Math.min(_this.maxTranslate.x, Math.max(_this.minTranslate.x, _this.translate.x)); + scrollX = _this.translate.x - translate.x; + } + + if (_this.axis.y) { + translate.y = Math.min(_this.maxTranslate.y, Math.max(_this.minTranslate.y, _this.translate.y)); + scrollY = _this.translate.y - translate.y; + } + + _this.translate = translate; + setTranslate3d(_this.helper, _this.translate); + _this.scrollContainer.scrollLeft += scrollX; + _this.scrollContainer.scrollTop += scrollY; + return; + } + + _this.autoScroller.update({ + height: _this.height, + maxTranslate: _this.maxTranslate, + minTranslate: _this.minTranslate, + translate: _this.translate, + width: _this.width + }); + }); + + _defineProperty(_assertThisInitialized(_this), "onAutoScroll", function (offset) { + _this.translate.x += offset.left; + _this.translate.y += offset.top; + + _this.animateNodes(); + }); + + _defineProperty(_assertThisInitialized(_this), "handleKeyDown", function (event) { + var keyCode = event.keyCode; + var _this$props5 = _this.props, + shouldCancelStart = _this$props5.shouldCancelStart, + _this$props5$keyCodes = _this$props5.keyCodes, + customKeyCodes = _this$props5$keyCodes === void 0 ? {} : _this$props5$keyCodes; + + var keyCodes = _objectSpread(_objectSpread({}, defaultKeyCodes), customKeyCodes); + + if (_this.manager.active && !_this.manager.isKeySorting || !_this.manager.active && (!keyCodes.lift.includes(keyCode) || shouldCancelStart(event) || !_this.isValidSortingTarget(event))) { + return; + } + + event.stopPropagation(); + event.preventDefault(); + + if (keyCodes.lift.includes(keyCode) && !_this.manager.active) { + _this.keyLift(event); + } else if (keyCodes.drop.includes(keyCode) && _this.manager.active) { + _this.keyDrop(event); + } else if (keyCodes.cancel.includes(keyCode)) { + _this.newIndex = _this.manager.active.index; + + _this.keyDrop(event); + } else if (keyCodes.up.includes(keyCode)) { + _this.keyMove(-1); + } else if (keyCodes.down.includes(keyCode)) { + _this.keyMove(1); + } + }); + + _defineProperty(_assertThisInitialized(_this), "keyLift", function (event) { + var target = event.target; + var node = closest(target, function (el) { + return el.sortableInfo != null; + }); + var _node$sortableInfo2 = node.sortableInfo, + index = _node$sortableInfo2.index, + collection = _node$sortableInfo2.collection; + _this.initialFocusedNode = target; + _this.manager.isKeySorting = true; + _this.manager.active = { + index: index, + collection: collection + }; + + _this.handlePress(event); + }); + + _defineProperty(_assertThisInitialized(_this), "keyMove", function (shift) { + var nodes = _this.manager.getOrderedRefs(); + + var lastIndex = nodes[nodes.length - 1].node.sortableInfo.index; + var newIndex = _this.newIndex + shift; + var prevIndex = _this.newIndex; + + if (newIndex < 0 || newIndex > lastIndex) { + return; + } + + _this.prevIndex = prevIndex; + _this.newIndex = newIndex; + var targetIndex = getTargetIndex(_this.newIndex, _this.prevIndex, _this.index); + var target = nodes.find(function (_ref2) { + var node = _ref2.node; + return node.sortableInfo.index === targetIndex; + }); + var targetNode = target.node; + var scrollDelta = _this.containerScrollDelta; + var targetBoundingClientRect = target.boundingClientRect || getScrollAdjustedBoundingClientRect(targetNode, scrollDelta); + var targetTranslate = target.translate || { + x: 0, + y: 0 + }; + var targetPosition = { + top: targetBoundingClientRect.top + targetTranslate.y - scrollDelta.top, + left: targetBoundingClientRect.left + targetTranslate.x - scrollDelta.left + }; + var shouldAdjustForSize = prevIndex < newIndex; + var sizeAdjustment = { + x: shouldAdjustForSize && _this.axis.x ? targetNode.offsetWidth - _this.width : 0, + y: shouldAdjustForSize && _this.axis.y ? targetNode.offsetHeight - _this.height : 0 + }; + + _this.handleSortMove({ + pageX: targetPosition.left + sizeAdjustment.x, + pageY: targetPosition.top + sizeAdjustment.y, + ignoreTransition: shift === 0 + }); + }); + + _defineProperty(_assertThisInitialized(_this), "keyDrop", function (event) { + _this.handleSortEnd(event); + + if (_this.initialFocusedNode) { + _this.initialFocusedNode.focus(); + } + }); + + _defineProperty(_assertThisInitialized(_this), "handleKeyEnd", function (event) { + if (_this.manager.active) { + _this.keyDrop(event); + } + }); + + _defineProperty(_assertThisInitialized(_this), "isValidSortingTarget", function (event) { + var useDragHandle = _this.props.useDragHandle; + var target = event.target; + var node = closest(target, function (el) { + return el.sortableInfo != null; + }); + return node && node.sortableInfo && !node.sortableInfo.disabled && (useDragHandle ? isSortableHandle(target) : target.sortableInfo); + }); + + validateProps(props); + _this.manager = new Manager(); + _this.events = { + end: _this.handleEnd, + move: _this.handleMove, + start: _this.handleStart + }; + return _this; + } + + _createClass(WithSortableContainer, [{ + key: "getChildContext", + value: function getChildContext() { + return { + manager: this.manager + }; + } + }, { + key: "componentDidMount", + value: function componentDidMount() { + var _this2 = this; + + var useWindowAsScrollContainer = this.props.useWindowAsScrollContainer; + var container = this.getContainer(); + Promise.resolve(container).then(function (containerNode) { + _this2.container = containerNode; + _this2.document = _this2.container.ownerDocument || document; + var contentWindow = _this2.props.contentWindow || _this2.document.defaultView || window; + _this2.contentWindow = typeof contentWindow === 'function' ? contentWindow() : contentWindow; + _this2.scrollContainer = useWindowAsScrollContainer ? _this2.document.scrollingElement || _this2.document.documentElement : getScrollingParent(_this2.container, _this2.props.scrollContainer) || _this2.container; + _this2.autoScroller = new AutoScroller(_this2.scrollContainer, _this2.onAutoScroll); + Object.keys(_this2.events).forEach(function (key) { + return events[key].forEach(function (eventName) { + return _this2.container.addEventListener(eventName, _this2.events[key], false); + }); + }); + + _this2.container.addEventListener('keydown', _this2.handleKeyDown); + }); + } + }, { + key: "componentWillUnmount", + value: function componentWillUnmount() { + var _this3 = this; + + if (this.helper && this.helper.parentNode) { + this.helper.parentNode.removeChild(this.helper); + } + + if (!this.container) { + return; + } + + Object.keys(this.events).forEach(function (key) { + return events[key].forEach(function (eventName) { + return _this3.container.removeEventListener(eventName, _this3.events[key]); + }); + }); + this.container.removeEventListener('keydown', this.handleKeyDown); + } + }, { + key: "updateHelperPosition", + value: function updateHelperPosition(event) { + var _this$props6 = this.props, + lockAxis = _this$props6.lockAxis, + lockOffset = _this$props6.lockOffset, + lockToContainerEdges = _this$props6.lockToContainerEdges, + transitionDuration = _this$props6.transitionDuration, + _this$props6$keyboard = _this$props6.keyboardSortingTransitionDuration, + keyboardSortingTransitionDuration = _this$props6$keyboard === void 0 ? transitionDuration : _this$props6$keyboard; + var isKeySorting = this.manager.isKeySorting; + var ignoreTransition = event.ignoreTransition; + var offset = getPosition(event); + var translate = { + x: offset.x - this.initialOffset.x, + y: offset.y - this.initialOffset.y + }; + translate.y -= window.pageYOffset - this.initialWindowScroll.top; + translate.x -= window.pageXOffset - this.initialWindowScroll.left; + this.translate = translate; + + if (lockToContainerEdges) { + var _getLockPixelOffsets = getLockPixelOffsets({ + height: this.height, + lockOffset: lockOffset, + width: this.width + }), + _getLockPixelOffsets2 = _slicedToArray(_getLockPixelOffsets, 2), + minLockOffset = _getLockPixelOffsets2[0], + maxLockOffset = _getLockPixelOffsets2[1]; + + var minOffset = { + x: this.width / 2 - minLockOffset.x, + y: this.height / 2 - minLockOffset.y + }; + var maxOffset = { + x: this.width / 2 - maxLockOffset.x, + y: this.height / 2 - maxLockOffset.y + }; + translate.x = limit(this.minTranslate.x + minOffset.x, this.maxTranslate.x - maxOffset.x, translate.x); + translate.y = limit(this.minTranslate.y + minOffset.y, this.maxTranslate.y - maxOffset.y, translate.y); + } + + if (lockAxis === 'x') { + translate.y = 0; + } else if (lockAxis === 'y') { + translate.x = 0; + } + + if (isKeySorting && keyboardSortingTransitionDuration && !ignoreTransition) { + setTransitionDuration(this.helper, keyboardSortingTransitionDuration); + } + + setTranslate3d(this.helper, translate); + } + }, { + key: "animateNodes", + value: function animateNodes() { + var _this$props7 = this.props, + transitionDuration = _this$props7.transitionDuration, + hideSortableGhost = _this$props7.hideSortableGhost, + onSortOver = _this$props7.onSortOver; + var containerScrollDelta = this.containerScrollDelta, + windowScrollDelta = this.windowScrollDelta; + var nodes = this.manager.getOrderedRefs(); + var sortingOffset = { + left: this.offsetEdge.left + this.translate.x + containerScrollDelta.left, + top: this.offsetEdge.top + this.translate.y + containerScrollDelta.top + }; + var isKeySorting = this.manager.isKeySorting; + var prevIndex = this.newIndex; + this.newIndex = null; + + for (var i = 0, len = nodes.length; i < len; i++) { + var _node3 = nodes[i].node; + var index = _node3.sortableInfo.index; + var width = _node3.offsetWidth; + var height = _node3.offsetHeight; + var offset = { + height: this.height > height ? height / 2 : this.height / 2, + width: this.width > width ? width / 2 : this.width / 2 + }; + var mustShiftBackward = isKeySorting && index > this.index && index <= prevIndex; + var mustShiftForward = isKeySorting && index < this.index && index >= prevIndex; + var translate = { + x: 0, + y: 0 + }; + var edgeOffset = nodes[i].edgeOffset; + + if (!edgeOffset) { + edgeOffset = getEdgeOffset(_node3, this.container); + nodes[i].edgeOffset = edgeOffset; + + if (isKeySorting) { + nodes[i].boundingClientRect = getScrollAdjustedBoundingClientRect(_node3, containerScrollDelta); + } + } + + var nextNode = i < nodes.length - 1 && nodes[i + 1]; + var prevNode = i > 0 && nodes[i - 1]; + + if (nextNode && !nextNode.edgeOffset) { + nextNode.edgeOffset = getEdgeOffset(nextNode.node, this.container); + + if (isKeySorting) { + nextNode.boundingClientRect = getScrollAdjustedBoundingClientRect(nextNode.node, containerScrollDelta); + } + } + + if (index === this.index) { + if (hideSortableGhost) { + this.sortableGhost = _node3; + setInlineStyles(_node3, { + opacity: 0 + }); + } + + continue; + } + + if (transitionDuration) { + setTransitionDuration(_node3, transitionDuration); + } + + if (this.axis.x) { + if (this.axis.y) { + if (mustShiftForward || index < this.index && (sortingOffset.left + windowScrollDelta.left - offset.width <= edgeOffset.left && sortingOffset.top + windowScrollDelta.top <= edgeOffset.top + offset.height || sortingOffset.top + windowScrollDelta.top + offset.height <= edgeOffset.top)) { + translate.x = this.width + this.marginOffset.x; + + if (edgeOffset.left + translate.x > this.containerBoundingRect.width - offset.width) { + if (nextNode) { + translate.x = nextNode.edgeOffset.left - edgeOffset.left; + translate.y = nextNode.edgeOffset.top - edgeOffset.top; + } + } + + if (this.newIndex === null) { + this.newIndex = index; + } + } else if (mustShiftBackward || index > this.index && (sortingOffset.left + windowScrollDelta.left + offset.width >= edgeOffset.left && sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top || sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top + height)) { + translate.x = -(this.width + this.marginOffset.x); + + if (edgeOffset.left + translate.x < this.containerBoundingRect.left + offset.width) { + if (prevNode) { + translate.x = prevNode.edgeOffset.left - edgeOffset.left; + translate.y = prevNode.edgeOffset.top - edgeOffset.top; + } + } + + this.newIndex = index; + } + } else { + if (mustShiftBackward || index > this.index && sortingOffset.left + windowScrollDelta.left + offset.width >= edgeOffset.left) { + translate.x = -(this.width + this.marginOffset.x); + this.newIndex = index; + } else if (mustShiftForward || index < this.index && sortingOffset.left + windowScrollDelta.left <= edgeOffset.left + offset.width) { + translate.x = this.width + this.marginOffset.x; + + if (this.newIndex == null) { + this.newIndex = index; + } + } + } + } else if (this.axis.y) { + if (mustShiftBackward || index > this.index && sortingOffset.top + windowScrollDelta.top + offset.height >= edgeOffset.top) { + translate.y = -(this.height + this.marginOffset.y); + this.newIndex = index; + } else if (mustShiftForward || index < this.index && sortingOffset.top + windowScrollDelta.top <= edgeOffset.top + offset.height) { + translate.y = this.height + this.marginOffset.y; + + if (this.newIndex == null) { + this.newIndex = index; + } + } + } + + setTranslate3d(_node3, translate); + nodes[i].translate = translate; + } + + if (this.newIndex == null) { + this.newIndex = this.index; + } + + if (isKeySorting) { + this.newIndex = prevIndex; + } + + var oldIndex = isKeySorting ? this.prevIndex : prevIndex; + + if (onSortOver && this.newIndex !== oldIndex) { + onSortOver({ + collection: this.manager.active.collection, + index: this.index, + newIndex: this.newIndex, + oldIndex: oldIndex, + isKeySorting: isKeySorting, + nodes: nodes, + helper: this.helper + }); + } + } + }, { + key: "getWrappedInstance", + value: function getWrappedInstance() { + invariant_1(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableContainer() call'); + return this.refs.wrappedInstance; + } + }, { + key: "getContainer", + value: function getContainer() { + var getContainer = this.props.getContainer; + + if (typeof getContainer !== 'function') { + return reactDom.findDOMNode(this); + } + + return getContainer(config.withRef ? this.getWrappedInstance() : undefined); + } + }, { + key: "render", + value: function render() { + var ref = config.withRef ? 'wrappedInstance' : null; + return React.createElement(WrappedComponent, _extends({ + ref: ref + }, omit(this.props, omittedProps))); + } + }, { + key: "helperContainer", + get: function get() { + var helperContainer = this.props.helperContainer; + + if (typeof helperContainer === 'function') { + return helperContainer(); + } + + return this.props.helperContainer || this.document.body; + } + }, { + key: "containerScrollDelta", + get: function get() { + var useWindowAsScrollContainer = this.props.useWindowAsScrollContainer; + + if (useWindowAsScrollContainer) { + return { + left: 0, + top: 0 + }; + } + + return { + left: this.scrollContainer.scrollLeft - this.initialScroll.left, + top: this.scrollContainer.scrollTop - this.initialScroll.top + }; + } + }, { + key: "windowScrollDelta", + get: function get() { + return { + left: this.contentWindow.pageXOffset - this.initialWindowScroll.left, + top: this.contentWindow.pageYOffset - this.initialWindowScroll.top + }; + } + }]); + + return WithSortableContainer; + }(React.Component), _defineProperty(_class, "displayName", provideDisplayName('sortableList', WrappedComponent)), _defineProperty(_class, "defaultProps", defaultProps), _defineProperty(_class, "propTypes", propTypes), _defineProperty(_class, "childContextTypes", { + manager: PropTypes.object.isRequired + }), _temp; + } + + function _createSuper$2(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct$2(); 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$2() { 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; } } + var propTypes$1 = { + index: PropTypes.number.isRequired, + collection: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), + disabled: PropTypes.bool + }; + var omittedProps$1 = Object.keys(propTypes$1); + function sortableElement(WrappedComponent) { + var _class, _temp; + + var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { + withRef: false + }; + return _temp = _class = function (_React$Component) { + _inherits(WithSortableElement, _React$Component); + + var _super = _createSuper$2(WithSortableElement); + + function WithSortableElement() { + _classCallCheck(this, WithSortableElement); + + return _super.apply(this, arguments); + } + + _createClass(WithSortableElement, [{ + key: "componentDidMount", + value: function componentDidMount() { + this.register(); + } + }, { + key: "componentDidUpdate", + value: function componentDidUpdate(prevProps) { + if (this.node) { + if (prevProps.index !== this.props.index) { + this.node.sortableInfo.index = this.props.index; + } + + if (prevProps.disabled !== this.props.disabled) { + this.node.sortableInfo.disabled = this.props.disabled; + } + } + + if (prevProps.collection !== this.props.collection) { + this.unregister(prevProps.collection); + this.register(); + } + } + }, { + key: "componentWillUnmount", + value: function componentWillUnmount() { + this.unregister(); + } + }, { + key: "register", + value: function register() { + var _this$props = this.props, + collection = _this$props.collection, + disabled = _this$props.disabled, + index = _this$props.index; + var node = reactDom.findDOMNode(this); + node.sortableInfo = { + collection: collection, + disabled: disabled, + index: index, + manager: this.context.manager + }; + this.node = node; + this.ref = { + node: node + }; + this.context.manager.add(collection, this.ref); + } + }, { + key: "unregister", + value: function unregister() { + var collection = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : this.props.collection; + this.context.manager.remove(collection, this.ref); + } + }, { + key: "getWrappedInstance", + value: function getWrappedInstance() { + invariant_1(config.withRef, 'To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableElement() call'); + return this.refs.wrappedInstance; + } + }, { + key: "render", + value: function render() { + var ref = config.withRef ? 'wrappedInstance' : null; + return React.createElement(WrappedComponent, _extends({ + ref: ref + }, omit(this.props, omittedProps$1))); + } + }]); + + return WithSortableElement; + }(React.Component), _defineProperty(_class, "displayName", provideDisplayName('sortableElement', WrappedComponent)), _defineProperty(_class, "contextTypes", { + manager: PropTypes.object.isRequired + }), _defineProperty(_class, "propTypes", propTypes$1), _defineProperty(_class, "defaultProps", { + collection: 0 + }), _temp; + } + + exports.SortableContainer = sortableContainer; + exports.SortableElement = sortableElement; + exports.SortableHandle = sortableHandle; + exports.arrayMove = arrayMove; + exports.sortableContainer = sortableContainer; + exports.sortableElement = sortableElement; + exports.sortableHandle = sortableHandle; + + Object.defineProperty(exports, '__esModule', { value: true }); + +}))); diff --git a/dist/react-sortable-hoc.umd.min.js b/dist/react-sortable-hoc.umd.min.js new file mode 100644 index 000000000..04d1c2006 --- /dev/null +++ b/dist/react-sortable-hoc.umd.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("prop-types"),require("react-dom")):"function"==typeof define&&define.amd?define(["exports","react","prop-types","react-dom"],t):t((e=e||self).SortableHOC={},e.React,e.PropTypes,e.ReactDOM)}(this,function(e,i,a,s){"use strict";function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function n(e,t){return e(t={exports:{}},t.exports),t.exports}a=a&&Object.prototype.hasOwnProperty.call(a,"default")?a.default:a;var l=t(n(function(e){function t(){return e.exports=t=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},e.exports.default=e.exports,e.exports.__esModule=!0,t.apply(this,arguments)}e.exports=t,e.exports.default=e.exports,e.exports.__esModule=!0})),o=n(function(e){e.exports=function(e){if(Array.isArray(e))return e},e.exports.default=e.exports,e.exports.__esModule=!0});t(o);var r=n(function(e){e.exports=function(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var n=[],o=!0,r=!1,i=void 0;try{for(var a,s=e[Symbol.iterator]();!(o=(a=s.next()).done)&&(n.push(a.value),!t||n.length!==t);o=!0);}catch(e){r=!0,i=e}finally{try{o||null==s.return||s.return()}finally{if(r)throw i}}return n}},e.exports.default=e.exports,e.exports.__esModule=!0});t(r);var c=n(function(e){e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,o=new Array(t);n<t;n++)o[n]=e[n];return o},e.exports.default=e.exports,e.exports.__esModule=!0});t(c);var u=n(function(e){e.exports=function(e,t){if(e){if("string"==typeof e)return c(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?c(e,t):void 0}},e.exports.default=e.exports,e.exports.__esModule=!0});t(u);var f=n(function(e){e.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.default=e.exports,e.exports.__esModule=!0});t(f);var b=t(n(function(e){e.exports=function(e,t){return o(e)||r(e,t)||u(e,t)||f()},e.exports.default=e.exports,e.exports.__esModule=!0})),d=t(n(function(e){e.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},e.exports.default=e.exports,e.exports.__esModule=!0})),p=t(n(function(e){function o(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}e.exports=function(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),e},e.exports.default=e.exports,e.exports.__esModule=!0})),h=n(function(e){e.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e},e.exports.default=e.exports,e.exports.__esModule=!0}),x=t(h),y=n(function(n){function o(e,t){return n.exports=o=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},n.exports.default=n.exports,n.exports.__esModule=!0,o(e,t)}n.exports=o,n.exports.default=n.exports,n.exports.__esModule=!0});t(y);var g=t(n(function(e){e.exports=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&y(e,t)},e.exports.default=e.exports,e.exports.__esModule=!0})),v=n(function(t){function n(e){return"function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?t.exports=n=function(e){return typeof e}:t.exports=n=function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},t.exports.default=t.exports,t.exports.__esModule=!0,n(e)}t.exports=n,t.exports.default=t.exports,t.exports.__esModule=!0});t(v);var m=t(n(function(e){var n=v.default;e.exports=function(e,t){return!t||"object"!==n(t)&&"function"!=typeof t?h(e):t},e.exports.default=e.exports,e.exports.__esModule=!0})),w=t(n(function(t){function n(e){return t.exports=n=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},t.exports.default=t.exports,t.exports.__esModule=!0,n(e)}t.exports=n,t.exports.default=t.exports,t.exports.__esModule=!0})),S=t(n(function(e){e.exports=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},e.exports.default=e.exports,e.exports.__esModule=!0})),O=function(e,t,n,o,r,i,a,s){if(!e){var l;if(void 0===t)l=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,o,r,i,a,s],u=0;(l=new Error(t.replace(/%s/g,function(){return c[u++]}))).name="Invariant Violation"}throw l.framesToPop=1,l}},C=function(){function e(){d(this,e),S(this,"refs",{})}return p(e,[{key:"add",value:function(e,t){this.refs[e]||(this.refs[e]=[]),this.refs[e].push(t)}},{key:"remove",value:function(e,t){var n=this.getIndex(e,t);-1!==n&&this.refs[e].splice(n,1)}},{key:"isActive",value:function(){return this.active}},{key:"getActive",value:function(){var t=this;return this.refs[this.active.collection].find(function(e){return e.node.sortableInfo.index==t.active.index})}},{key:"getIndex",value:function(e,t){return this.refs[e].indexOf(t)}},{key:"getOrderedRefs",value:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:this.active.collection;return this.refs[e].sort(T)}}]),e}();function T(e,t){return e.node.sortableInfo.index-t.node.sortableInfo.index}var I=n(function(e){e.exports=function(e){if(Array.isArray(e))return c(e)},e.exports.default=e.exports,e.exports.__esModule=!0});t(I);var k=n(function(e){e.exports=function(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)},e.exports.default=e.exports,e.exports.__esModule=!0});t(k);var E=n(function(e){e.exports=function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.default=e.exports,e.exports.__esModule=!0});t(E);var R=t(n(function(e){e.exports=function(e){return I(e)||k(e)||u(e)||E()},e.exports.default=e.exports,e.exports.__esModule=!0}));function _(n,o){return Object.keys(n).reduce(function(e,t){return-1===o.indexOf(t)&&(e[t]=n[t]),e},{})}var M={end:["touchend","touchcancel","mouseup"],move:["touchmove","mousemove"],start:["touchstart","mousedown"]},D=function(){if("undefined"==typeof window||"undefined"==typeof document)return"";var e=window.getComputedStyle(document.documentElement,"")||["-moz-hidden-iframe"],t=(Array.prototype.slice.call(e).join("").match(/-(moz|webkit|ms)-/)||""===e.OLink&&["","o"])[1];switch(t){case"ms":return"ms";default:return t&&t.length?t[0].toUpperCase()+t.substr(1):""}}();function j(t,n){Object.keys(n).forEach(function(e){t.style[e]=n[e]})}function A(e,t){e.style["".concat(D,"Transform")]=null==t?"":"translate3d(".concat(t.x,"px,").concat(t.y,"px,0)")}function N(e,t){e.style["".concat(D,"TransitionDuration")]=null==t?"":"".concat(t,"ms")}function P(e,t){for(;e;){if(t(e))return e;e=e.parentNode}return null}function W(e,t,n){return Math.max(e,Math.min(n,t))}function L(e){return"px"===e.substr(-2)?parseFloat(e):0}function H(e,t){var n=t.displayName||t.name;return n?"".concat(e,"(").concat(n,")"):e}function B(e,t){var n=e.getBoundingClientRect();return{top:n.top+t.top,left:n.left+t.left}}function K(e){return e.touches&&e.touches.length?{x:e.touches[0].pageX,y:e.touches[0].pageY}:e.changedTouches&&e.changedTouches.length?{x:e.changedTouches[0].pageX,y:e.changedTouches[0].pageY}:{x:e.pageX,y:e.pageY}}function G(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{left:0,top:0};if(e){var o={left:n.left+e.offsetLeft,top:n.top+e.offsetTop};return e.parentNode===t?o:G(e.parentNode,t,o)}}function U(e){var t=e.lockOffset,n=e.width,o=e.height,r=t,i=t,a="px";if("string"==typeof t){var s=/^[+-]?\d*(?:\.\d*)?(px|%)$/.exec(t);O(null!==s,'lockOffset value should be a number or a string of a number followed by "px" or "%". Given %s',t),r=parseFloat(t),i=parseFloat(t),a=s[1]}return O(isFinite(r)&&isFinite(i),"lockOffset value should be a finite. Given %s",t),"%"===a&&(r=r*n/100,i=i*o/100),{x:r,y:i}}function X(e){var t,n,o,r=1<arguments.length&&void 0!==arguments[1]&&arguments[1];return r?document.querySelector(r):e instanceof HTMLElement?(t=e,n=window.getComputedStyle(t),o=/(auto|scroll)/,["overflow","overflowX","overflowY"].find(function(e){return o.test(n[e])})?e:X(e.parentNode)):null}var q=27,Y=32,F=37,V=38,z=39,$=40,J={Anchor:"A",Button:"BUTTON",Canvas:"CANVAS",Input:"INPUT",Option:"OPTION",Textarea:"TEXTAREA",Select:"SELECT"};function Q(o){var r=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=w(o);if(r){var n=w(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return m(this,e)}}function Z(o){var e,t,r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{withRef:!1};return t=e=function(e){g(n,e);var t=Q(n);function n(){return d(this,n),t.apply(this,arguments)}return p(n,[{key:"componentDidMount",value:function(){s.findDOMNode(this).sortableHandle=!0}},{key:"getWrappedInstance",value:function(){return O(r.withRef,"To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableHandle() call"),this.refs.wrappedInstance}},{key:"render",value:function(){var e=r.withRef?"wrappedInstance":null;return i.createElement(o,l({ref:e},this.props))}}]),n}(i.Component),S(e,"displayName",H("sortableHandle",o)),t}function ee(e){return null!=e.sortableHandle}var te=function(){function n(e,t){d(this,n),this.container=e,this.onScrollCallback=t}return p(n,[{key:"clear",value:function(){null!=this.interval&&(clearInterval(this.interval),this.interval=null)}},{key:"update",value:function(e){var t=this,n=e.translate,o=e.minTranslate,r=e.maxTranslate,i=e.width,a=e.height,s={x:0,y:0},l={x:1,y:1},c=10,u=10,f=this.container,d=f.scrollTop,p=f.scrollLeft,h=f.scrollHeight,x=f.scrollWidth,y=0===d,g=h-d-f.clientHeight==0,v=0===p,m=x-p-f.clientWidth==0;n.y>=r.y-a/2&&!g?(s.y=1,l.y=u*Math.abs((r.y-a/2-n.y)/a)):n.x>=r.x-i/2&&!m?(s.x=1,l.x=c*Math.abs((r.x-i/2-n.x)/i)):n.y<=o.y+a/2&&!y?(s.y=-1,l.y=u*Math.abs((n.y-a/2-o.y)/a)):n.x<=o.x+i/2&&!v&&(s.x=-1,l.x=c*Math.abs((n.x-i/2-o.x)/i)),this.interval&&(this.clear(),this.isAutoScrolling=!1),0===s.x&&0===s.y||(this.interval=setInterval(function(){t.isAutoScrolling=!0;var e={left:l.x*s.x,top:l.y*s.y};t.container.scrollTop+=e.top,t.container.scrollLeft+=e.left,t.onScrollCallback(e)},5))}}]),n}();var ne={axis:a.oneOf(["x","y","xy"]),contentWindow:a.any,disableAutoscroll:a.bool,distance:a.number,getContainer:a.func,getHelperDimensions:a.func,helperClass:a.string,helperContainer:a.oneOfType([a.func,"undefined"==typeof HTMLElement?a.any:a.instanceOf(HTMLElement)]),hideSortableGhost:a.bool,keyboardSortingTransitionDuration:a.number,lockAxis:a.string,lockOffset:a.oneOfType([a.number,a.string,a.arrayOf(a.oneOfType([a.number,a.string]))]),lockToContainerEdges:a.bool,onSortEnd:a.func,onSortMove:a.func,onSortOver:a.func,onSortStart:a.func,pressDelay:a.number,pressThreshold:a.number,keyCodes:a.shape({lift:a.arrayOf(a.number),drop:a.arrayOf(a.number),cancel:a.arrayOf(a.number),up:a.arrayOf(a.number),down:a.arrayOf(a.number)}),shouldCancelStart:a.func,transitionDuration:a.number,updateBeforeSortStart:a.func,useDragHandle:a.bool,useWindowAsScrollContainer:a.bool},oe={lift:[Y],drop:[Y],cancel:[q],up:[V,F],down:[$,z]},re={axis:"y",disableAutoscroll:!1,distance:0,getHelperDimensions:function(e){var t=e.node;return{height:t.offsetHeight,width:t.offsetWidth}},hideSortableGhost:!0,lockOffset:"50%",lockToContainerEdges:!1,pressDelay:0,pressThreshold:5,keyCodes:oe,shouldCancelStart:function(e){return-1!==[J.Input,J.Textarea,J.Select,J.Option,J.Button].indexOf(e.target.tagName)||!!P(e.target,function(e){return"true"===e.contentEditable})},transitionDuration:300,useWindowAsScrollContainer:!1},ie=Object.keys(ne);function ae(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),n.push.apply(n,o)}return n}function se(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{};e%2?ae(Object(n),!0).forEach(function(e){S(t,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):ae(Object(n)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(n,e))})}return t}function le(o){var r=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=w(o);if(r){var n=w(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return m(this,e)}}function ce(t){var e,n,r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{withRef:!1};return n=e=function(e){g(o,e);var n=le(o);function o(e){var _,t;return d(this,o),_=n.call(this,e),S(x(_),"state",{}),S(x(_),"handleStart",function(e){var t=_.props,n=t.distance,o=t.shouldCancelStart;if(2!==e.button&&!o(e)){_.touched=!0,_.position=K(e);var r,i=P(e.target,function(e){return null!=e.sortableInfo});if(i&&i.sortableInfo&&_.nodeIsChild(i)&&!_.state.sorting){var a=_.props.useDragHandle,s=i.sortableInfo,l=s.index,c=s.collection;if(s.disabled)return;if(a&&!P(e.target,ee))return;_.manager.active={collection:c,index:l},(r=e).touches&&r.touches.length||r.changedTouches&&r.changedTouches.length||e.target.tagName!==J.Anchor||e.preventDefault(),n||(0===_.props.pressDelay?_.handlePress(e):_.pressTimer=setTimeout(function(){return _.handlePress(e)},_.props.pressDelay))}}}),S(x(_),"nodeIsChild",function(e){return e.sortableInfo.manager===_.manager}),S(x(_),"handleMove",function(e){var t=_.props,n=t.distance,o=t.pressThreshold;if(!_.state.sorting&&_.touched&&!_._awaitingUpdateBeforeSortStart){var r=K(e),i={x:_.position.x-r.x,y:_.position.y-r.y},a=Math.abs(i.x)+Math.abs(i.y);_.delta=i,n||o&&!(o<=a)?n&&n<=a&&_.manager.isActive()&&_.handlePress(e):(clearTimeout(_.cancelTimer),_.cancelTimer=setTimeout(_.cancel,0))}}),S(x(_),"handleEnd",function(){_.touched=!1,_.cancel()}),S(x(_),"cancel",function(){var e=_.props.distance;_.state.sorting||(e||clearTimeout(_.pressTimer),_.manager.active=null)}),S(x(_),"handlePress",function(E){try{var r=_.manager.getActive(),e=function(){if(r){var e=function(){var e,t,n,o,r,i,a,s,l=T.sortableInfo.index,c=(e=T,{bottom:L((t=window.getComputedStyle(e)).marginBottom),left:L(t.marginLeft),right:L(t.marginRight),top:L(t.marginTop)}),u=(n=_.container,"grid"===(o=window.getComputedStyle(n)).display?{x:L(o.gridColumnGap),y:L(o.gridRowGap)}:{x:0,y:0}),f=_.scrollContainer.getBoundingClientRect(),d=b({index:l,node:T,collection:I});if(_.node=T,_.margin=c,_.gridGap=u,_.width=d.width,_.height=d.height,_.marginOffset={x:_.margin.left+_.margin.right+_.gridGap.x,y:Math.max(_.margin.top,_.margin.bottom,_.gridGap.y)},_.boundingClientRect=T.getBoundingClientRect(),_.containerBoundingRect=f,_.index=l,_.newIndex=l,_.axis={x:0<=m.indexOf("x"),y:0<=m.indexOf("y")},_.offsetEdge=G(T,_.container),_.initialOffset=K(k?se(se({},E),{},{pageX:_.boundingClientRect.left,pageY:_.boundingClientRect.top}):E),_.initialScroll={left:_.scrollContainer.scrollLeft,top:_.scrollContainer.scrollTop},_.initialWindowScroll={left:window.pageXOffset,top:window.pageYOffset},_.helper=_.helperContainer.appendChild((i="input, textarea, select, canvas, [contenteditable]",a=(r=T).querySelectorAll(i),s=r.cloneNode(!0),R(s.querySelectorAll(i)).forEach(function(e,t){"file"!==e.type&&(e.value=a[t].value),"radio"===e.type&&e.name&&(e.name="__sortableClone__".concat(e.name)),e.tagName===J.Canvas&&0<a[t].width&&0<a[t].height&&e.getContext("2d").drawImage(a[t],0,0)}),s)),j(_.helper,{boxSizing:"border-box",height:"".concat(_.height,"px"),left:"".concat(_.boundingClientRect.left-c.left,"px"),pointerEvents:"none",position:"fixed",top:"".concat(_.boundingClientRect.top-c.top,"px"),width:"".concat(_.width,"px")}),k&&_.helper.focus(),S&&j(_.sortableGhost=T,{opacity:0}),_.minTranslate={},_.maxTranslate={},k){var p=C?{top:0,left:0,width:_.contentWindow.innerWidth,height:_.contentWindow.innerHeight}:_.containerBoundingRect,h=p.top,x=p.left,y=p.width,g=h+p.height,v=x+y;_.axis.x&&(_.minTranslate.x=x-_.boundingClientRect.left,_.maxTranslate.x=v-(_.boundingClientRect.left+_.width)),_.axis.y&&(_.minTranslate.y=h-_.boundingClientRect.top,_.maxTranslate.y=g-(_.boundingClientRect.top+_.height))}else _.axis.x&&(_.minTranslate.x=(C?0:f.left)-_.boundingClientRect.left-_.width/2,_.maxTranslate.x=(C?_.contentWindow.innerWidth:f.left+f.width)-_.boundingClientRect.left-_.width/2),_.axis.y&&(_.minTranslate.y=(C?0:f.top)-_.boundingClientRect.top-_.height/2,_.maxTranslate.y=(C?_.contentWindow.innerHeight:f.top+f.height)-_.boundingClientRect.top-_.height/2);w&&w.split(" ").forEach(function(e){return _.helper.classList.add(e)}),_.listenerNode=E.touches?T:_.contentWindow,k?(_.listenerNode.addEventListener("wheel",_.handleKeyEnd,!0),_.listenerNode.addEventListener("mousedown",_.handleKeyEnd,!0),_.listenerNode.addEventListener("keydown",_.handleKeyDown)):(M.move.forEach(function(e){return _.listenerNode.addEventListener(e,_.handleSortMove,!1)}),M.end.forEach(function(e){return _.listenerNode.addEventListener(e,_.handleSortEnd,!1)})),_.setState({sorting:!0,sortingIndex:l}),O&&O({node:T,index:l,collection:I,isKeySorting:k,nodes:_.manager.getOrderedRefs(),helper:_.helper},E),k&&_.keyMove(0)},t=_.props,m=t.axis,b=t.getHelperDimensions,w=t.helperClass,S=t.hideSortableGhost,n=t.updateBeforeSortStart,O=t.onSortStart,C=t.useWindowAsScrollContainer,T=r.node,I=r.collection,k=_.manager.isKeySorting,o=function(){if("function"==typeof n){_._awaitingUpdateBeforeSortStart=!0;var e=function(e,t){try{var n=e()}catch(e){return t(!0,e)}return n&&n.then?n.then(t.bind(null,!1),t.bind(null,!0)):t(!1,n)}(function(){var e=T.sortableInfo.index;return Promise.resolve(n({collection:I,index:e,node:T,isKeySorting:k},E)).then(function(){})},function(e,t){if(_._awaitingUpdateBeforeSortStart=!1,e)throw t;return t});if(e&&e.then)return e.then(function(){})}}();return o&&o.then?o.then(e):e()}}();return Promise.resolve(e&&e.then?e.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),S(x(_),"handleSortMove",function(e){var t=_.props.onSortMove;"function"==typeof e.preventDefault&&e.preventDefault(),_.updateHelperPosition(e),_.animateNodes(),_.autoscroll(),t&&t(e)}),S(x(_),"handleSortEnd",function(e){var t=_.props,n=t.hideSortableGhost,o=t.onSortEnd,r=_.manager,i=r.active.collection,a=r.isKeySorting,s=_.manager.getOrderedRefs();_.listenerNode&&(a?(_.listenerNode.removeEventListener("wheel",_.handleKeyEnd,!0),_.listenerNode.removeEventListener("mousedown",_.handleKeyEnd,!0),_.listenerNode.removeEventListener("keydown",_.handleKeyDown)):(M.move.forEach(function(e){return _.listenerNode.removeEventListener(e,_.handleSortMove)}),M.end.forEach(function(e){return _.listenerNode.removeEventListener(e,_.handleSortEnd)}))),_.helper.parentNode.removeChild(_.helper),n&&_.sortableGhost&&j(_.sortableGhost,{opacity:""});for(var l=0,c=s.length;l<c;l++){var u=s[l],f=u.node;u.edgeOffset=null,A(f,u.boundingClientRect=null),N(f,null),u.translate=null}_.autoScroller.clear(),_.manager.active=null,_.manager.isKeySorting=!1,_.setState({sorting:!1,sortingIndex:null}),"function"==typeof o&&o({collection:i,newIndex:_.newIndex,oldIndex:_.index,isKeySorting:a,nodes:s},e),_.touched=!1}),S(x(_),"autoscroll",function(){var e=_.props.disableAutoscroll,t=_.manager.isKeySorting;if(e)_.autoScroller.clear();else{if(t){var n=se({},_.translate),o=0,r=0;return _.axis.x&&(n.x=Math.min(_.maxTranslate.x,Math.max(_.minTranslate.x,_.translate.x)),o=_.translate.x-n.x),_.axis.y&&(n.y=Math.min(_.maxTranslate.y,Math.max(_.minTranslate.y,_.translate.y)),r=_.translate.y-n.y),_.translate=n,A(_.helper,_.translate),_.scrollContainer.scrollLeft+=o,void(_.scrollContainer.scrollTop+=r)}_.autoScroller.update({height:_.height,maxTranslate:_.maxTranslate,minTranslate:_.minTranslate,translate:_.translate,width:_.width})}}),S(x(_),"onAutoScroll",function(e){_.translate.x+=e.left,_.translate.y+=e.top,_.animateNodes()}),S(x(_),"handleKeyDown",function(e){var t=e.keyCode,n=_.props,o=n.shouldCancelStart,r=n.keyCodes,i=void 0===r?{}:r,a=se(se({},oe),i);_.manager.active&&!_.manager.isKeySorting||!(_.manager.active||a.lift.includes(t)&&!o(e)&&_.isValidSortingTarget(e))||(e.stopPropagation(),e.preventDefault(),a.lift.includes(t)&&!_.manager.active?_.keyLift(e):a.drop.includes(t)&&_.manager.active?_.keyDrop(e):a.cancel.includes(t)?(_.newIndex=_.manager.active.index,_.keyDrop(e)):a.up.includes(t)?_.keyMove(-1):a.down.includes(t)&&_.keyMove(1))}),S(x(_),"keyLift",function(e){var t=e.target,n=P(t,function(e){return null!=e.sortableInfo}).sortableInfo,o=n.index,r=n.collection;_.initialFocusedNode=t,_.manager.isKeySorting=!0,_.manager.active={index:o,collection:r},_.handlePress(e)}),S(x(_),"keyMove",function(e){var t=_.manager.getOrderedRefs(),n=t[t.length-1].node.sortableInfo.index,o=_.newIndex+e,r=_.newIndex;if(!(o<0||n<o)){_.prevIndex=r,_.newIndex=o;var i,a,s,l=(i=_.newIndex,a=_.prevIndex,s=_.index,i<s&&a<i?i-1:s<i&&i<a?i+1:i),c=t.find(function(e){return e.node.sortableInfo.index===l}),u=c.node,f=_.containerScrollDelta,d=c.boundingClientRect||B(u,f),p=c.translate||{x:0,y:0},h=d.top+p.y-f.top,x=d.left+p.x-f.left,y=r<o,g=y&&_.axis.x?u.offsetWidth-_.width:0,v=y&&_.axis.y?u.offsetHeight-_.height:0;_.handleSortMove({pageX:x+g,pageY:h+v,ignoreTransition:0===e})}}),S(x(_),"keyDrop",function(e){_.handleSortEnd(e),_.initialFocusedNode&&_.initialFocusedNode.focus()}),S(x(_),"handleKeyEnd",function(e){_.manager.active&&_.keyDrop(e)}),S(x(_),"isValidSortingTarget",function(e){var t=_.props.useDragHandle,n=e.target,o=P(n,function(e){return null!=e.sortableInfo});return o&&o.sortableInfo&&!o.sortableInfo.disabled&&(t?ee(n):n.sortableInfo)}),O(!((t=e).distance&&t.pressDelay),"Attempted to set both `pressDelay` and `distance` on SortableContainer, you may only use one or the other, not both at the same time."),_.manager=new C,_.events={end:_.handleEnd,move:_.handleMove,start:_.handleStart},_}return p(o,[{key:"getChildContext",value:function(){return{manager:this.manager}}},{key:"componentDidMount",value:function(){var n=this,o=this.props.useWindowAsScrollContainer,e=this.getContainer();Promise.resolve(e).then(function(e){n.container=e,n.document=n.container.ownerDocument||document;var t=n.props.contentWindow||n.document.defaultView||window;n.contentWindow="function"==typeof t?t():t,n.scrollContainer=o?n.document.scrollingElement||n.document.documentElement:X(n.container,n.props.scrollContainer)||n.container,n.autoScroller=new te(n.scrollContainer,n.onAutoScroll),Object.keys(n.events).forEach(function(t){return M[t].forEach(function(e){return n.container.addEventListener(e,n.events[t],!1)})}),n.container.addEventListener("keydown",n.handleKeyDown)})}},{key:"componentWillUnmount",value:function(){var n=this;this.helper&&this.helper.parentNode&&this.helper.parentNode.removeChild(this.helper),this.container&&(Object.keys(this.events).forEach(function(t){return M[t].forEach(function(e){return n.container.removeEventListener(e,n.events[t])})}),this.container.removeEventListener("keydown",this.handleKeyDown))}},{key:"updateHelperPosition",value:function(e){var t=this.props,n=t.lockAxis,o=t.lockOffset,r=t.lockToContainerEdges,i=t.transitionDuration,a=t.keyboardSortingTransitionDuration,s=void 0===a?i:a,l=this.manager.isKeySorting,c=e.ignoreTransition,u=K(e),f={x:u.x-this.initialOffset.x,y:u.y-this.initialOffset.y};if(f.y-=window.pageYOffset-this.initialWindowScroll.top,f.x-=window.pageXOffset-this.initialWindowScroll.left,this.translate=f,r){var d=function(e){var t=e.height,n=e.width,o=e.lockOffset,r=Array.isArray(o)?o:[o,o];O(2===r.length,"lockOffset prop of SortableContainer should be a single value or an array of exactly two values. Given %s",o);var i=b(r,2),a=i[0],s=i[1];return[U({height:t,lockOffset:a,width:n}),U({height:t,lockOffset:s,width:n})]}({height:this.height,lockOffset:o,width:this.width}),p=b(d,2),h=p[0],x=p[1],y=this.width/2-h.x,g=this.height/2-h.y,v=this.width/2-x.x,m=this.height/2-x.y;f.x=W(this.minTranslate.x+y,this.maxTranslate.x-v,f.x),f.y=W(this.minTranslate.y+g,this.maxTranslate.y-m,f.y)}"x"===n?f.y=0:"y"===n&&(f.x=0),l&&s&&!c&&N(this.helper,s),A(this.helper,f)}},{key:"animateNodes",value:function(){var e=this.props,t=e.transitionDuration,n=e.hideSortableGhost,o=e.onSortOver,r=this.containerScrollDelta,i=this.windowScrollDelta,a=this.manager.getOrderedRefs(),s=this.offsetEdge.left+this.translate.x+r.left,l=this.offsetEdge.top+this.translate.y+r.top,c=this.manager.isKeySorting,u=this.newIndex;this.newIndex=null;for(var f=0,d=a.length;f<d;f++){var p=a[f].node,h=p.sortableInfo.index,x=p.offsetWidth,y=p.offsetHeight,g=this.height>y?y/2:this.height/2,v=this.width>x?x/2:this.width/2,m=c&&h>this.index&&h<=u,b=c&&h<this.index&&u<=h,w={x:0,y:0},S=a[f].edgeOffset;S||(S=G(p,this.container),a[f].edgeOffset=S,c&&(a[f].boundingClientRect=B(p,r)));var O=f<a.length-1&&a[f+1],C=0<f&&a[f-1];O&&!O.edgeOffset&&(O.edgeOffset=G(O.node,this.container),c&&(O.boundingClientRect=B(O.node,r))),h!==this.index?(t&&N(p,t),this.axis.x?this.axis.y?b||h<this.index&&(s+i.left-v<=S.left&&l+i.top<=S.top+g||l+i.top+g<=S.top)?(w.x=this.width+this.marginOffset.x,S.left+w.x>this.containerBoundingRect.width-v&&O&&(w.x=O.edgeOffset.left-S.left,w.y=O.edgeOffset.top-S.top),null===this.newIndex&&(this.newIndex=h)):(m||h>this.index&&(s+i.left+v>=S.left&&l+i.top+g>=S.top||l+i.top+g>=S.top+y))&&(w.x=-(this.width+this.marginOffset.x),S.left+w.x<this.containerBoundingRect.left+v&&C&&(w.x=C.edgeOffset.left-S.left,w.y=C.edgeOffset.top-S.top),this.newIndex=h):m||h>this.index&&s+i.left+v>=S.left?(w.x=-(this.width+this.marginOffset.x),this.newIndex=h):(b||h<this.index&&s+i.left<=S.left+v)&&(w.x=this.width+this.marginOffset.x,null==this.newIndex&&(this.newIndex=h)):this.axis.y&&(m||h>this.index&&l+i.top+g>=S.top?(w.y=-(this.height+this.marginOffset.y),this.newIndex=h):(b||h<this.index&&l+i.top<=S.top+g)&&(w.y=this.height+this.marginOffset.y,null==this.newIndex&&(this.newIndex=h))),A(p,w),a[f].translate=w):n&&j(this.sortableGhost=p,{opacity:0})}null==this.newIndex&&(this.newIndex=this.index),c&&(this.newIndex=u);var T=c?this.prevIndex:u;o&&this.newIndex!==T&&o({collection:this.manager.active.collection,index:this.index,newIndex:this.newIndex,oldIndex:T,isKeySorting:c,nodes:a,helper:this.helper})}},{key:"getWrappedInstance",value:function(){return O(r.withRef,"To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableContainer() call"),this.refs.wrappedInstance}},{key:"getContainer",value:function(){var e=this.props.getContainer;return"function"!=typeof e?s.findDOMNode(this):e(r.withRef?this.getWrappedInstance():void 0)}},{key:"render",value:function(){var e=r.withRef?"wrappedInstance":null;return i.createElement(t,l({ref:e},_(this.props,ie)))}},{key:"helperContainer",get:function(){var e=this.props.helperContainer;return"function"==typeof e?e():this.props.helperContainer||this.document.body}},{key:"containerScrollDelta",get:function(){return this.props.useWindowAsScrollContainer?{left:0,top:0}:{left:this.scrollContainer.scrollLeft-this.initialScroll.left,top:this.scrollContainer.scrollTop-this.initialScroll.top}}},{key:"windowScrollDelta",get:function(){return{left:this.contentWindow.pageXOffset-this.initialWindowScroll.left,top:this.contentWindow.pageYOffset-this.initialWindowScroll.top}}}]),o}(i.Component),S(e,"displayName",H("sortableList",t)),S(e,"defaultProps",re),S(e,"propTypes",ne),S(e,"childContextTypes",{manager:a.object.isRequired}),n}function ue(o){var r=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=w(o);if(r){var n=w(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return m(this,e)}}var fe={index:a.number.isRequired,collection:a.oneOfType([a.number,a.string]),disabled:a.bool},de=Object.keys(fe);function pe(o){var e,t,r=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{withRef:!1};return t=e=function(e){g(n,e);var t=ue(n);function n(){return d(this,n),t.apply(this,arguments)}return p(n,[{key:"componentDidMount",value:function(){this.register()}},{key:"componentDidUpdate",value:function(e){this.node&&(e.index!==this.props.index&&(this.node.sortableInfo.index=this.props.index),e.disabled!==this.props.disabled&&(this.node.sortableInfo.disabled=this.props.disabled)),e.collection!==this.props.collection&&(this.unregister(e.collection),this.register())}},{key:"componentWillUnmount",value:function(){this.unregister()}},{key:"register",value:function(){var e=this.props,t=e.collection,n=e.disabled,o=e.index,r=s.findDOMNode(this);r.sortableInfo={collection:t,disabled:n,index:o,manager:this.context.manager},this.node=r,this.ref={node:r},this.context.manager.add(t,this.ref)}},{key:"unregister",value:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:this.props.collection;this.context.manager.remove(e,this.ref)}},{key:"getWrappedInstance",value:function(){return O(r.withRef,"To access the wrapped instance, you need to pass in {withRef: true} as the second argument of the SortableElement() call"),this.refs.wrappedInstance}},{key:"render",value:function(){var e=r.withRef?"wrappedInstance":null;return i.createElement(o,l({ref:e},_(this.props,de)))}}]),n}(i.Component),S(e,"displayName",H("sortableElement",o)),S(e,"contextTypes",{manager:a.object.isRequired}),S(e,"propTypes",fe),S(e,"defaultProps",{collection:0}),t}e.SortableContainer=ce,e.SortableElement=pe,e.SortableHandle=Z,e.arrayMove=function(e,t,n){return(e=e.slice()).splice(n<0?e.length+n:n,0,e.splice(t,1)[0]),e},e.sortableContainer=ce,e.sortableElement=pe,e.sortableHandle=Z,Object.defineProperty(e,"__esModule",{value:!0})}); diff --git a/package.json b/package.json index b0f2d7e75..816dd9856 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "react-sortable-hoc", - "version": "1.11.0", + "version": "1.12.1", "description": "Set of higher-order components to turn any list into a sortable, touch-friendly, animated list", "author": { "name": "Clauderic Demers", diff --git a/src/SortableContainer/index.js b/src/SortableContainer/index.js index e555d8433..da5730805 100644 --- a/src/SortableContainer/index.js +++ b/src/SortableContainer/index.js @@ -91,7 +91,8 @@ export default function sortableContainer( this.scrollContainer = useWindowAsScrollContainer ? this.document.scrollingElement || this.document.documentElement - : getScrollingParent(this.container) || this.container; + : getScrollingParent(this.container, this.props.scrollContainer) || + this.container; this.autoScroller = new AutoScroller( this.scrollContainer, @@ -326,7 +327,7 @@ export default function sortableContainer( setInlineStyles(node, { opacity: 0, - visibility: 'hidden', + // visibility: 'hidden', }); } @@ -509,7 +510,7 @@ export default function sortableContainer( if (hideSortableGhost && this.sortableGhost) { setInlineStyles(this.sortableGhost, { opacity: '', - visibility: '', + // visibility: '', }); } @@ -639,8 +640,8 @@ export default function sortableContainer( for (let i = 0, len = nodes.length; i < len; i++) { const {node} = nodes[i]; const {index} = node.sortableInfo; - const width = node.offsetWidth; - const height = node.offsetHeight; + const width = node.getBoundingClientRect().width; + const height = node.getBoundingClientRect().height; const offset = { height: this.height > height ? height / 2 : this.height / 2, width: this.width > width ? width / 2 : this.width / 2, @@ -699,7 +700,7 @@ export default function sortableContainer( setInlineStyles(node, { opacity: 0, - visibility: 'hidden', + // visibility: 'hidden', }); } continue; @@ -792,9 +793,7 @@ export default function sortableContainer( } else if (this.axis.y) { if ( mustShiftBackward || - (index > this.index && - sortingOffset.top + windowScrollDelta.top + offset.height >= - edgeOffset.top) + (index > this.index && sortingOffset.top + windowScrollDelta.top + this.boundingClientRect.height >= edgeOffset.top + offset.height) ) { translate.y = -(this.height + this.marginOffset.y); this.newIndex = index; diff --git a/src/utils.js b/src/utils.js index b62704ea4..0afd149eb 100644 --- a/src/utils.js +++ b/src/utils.js @@ -161,8 +161,8 @@ export function getEdgeOffset(node, parent, offset = {left: 0, top: 0}) { // Get the actual offsetTop / offsetLeft value, no matter how deep the node is nested const nodeOffset = { - left: offset.left + node.offsetLeft, - top: offset.top + node.offsetTop, + left: offset.left + node.getBoundingClientRect().left, + top: offset.top + node.getBoundingClientRect().top, }; if (node.parentNode === parent) { @@ -249,7 +249,10 @@ function isScrollable(el) { ); } -export function getScrollingParent(el) { +export function getScrollingParent(el, container = false) { + if (container) { + return document.querySelector(container); + } if (!(el instanceof HTMLElement)) { return null; } else if (isScrollable(el)) {