Sortable JS

Adds sortable js to greasyfork

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/482500/1297545/Sortable%20JS.js

  1. /**!
  2. * Sortable 1.15.1
  3. * @author RubaXa <trash@rubaxa.org>
  4. * @author owenm <owen23355@gmail.com>
  5. * @license MIT
  6. */
  7. (function (global, factory) {
  8. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  9. typeof define === 'function' && define.amd ? define(factory) :
  10. (global = global || self, global.Sortable = factory());
  11. }(this, (function () { 'use strict';
  12.  
  13. function ownKeys(object, enumerableOnly) {
  14. var keys = Object.keys(object);
  15. if (Object.getOwnPropertySymbols) {
  16. var symbols = Object.getOwnPropertySymbols(object);
  17. if (enumerableOnly) {
  18. symbols = symbols.filter(function (sym) {
  19. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  20. });
  21. }
  22. keys.push.apply(keys, symbols);
  23. }
  24. return keys;
  25. }
  26. function _objectSpread2(target) {
  27. for (var i = 1; i < arguments.length; i++) {
  28. var source = arguments[i] != null ? arguments[i] : {};
  29. if (i % 2) {
  30. ownKeys(Object(source), true).forEach(function (key) {
  31. _defineProperty(target, key, source[key]);
  32. });
  33. } else if (Object.getOwnPropertyDescriptors) {
  34. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  35. } else {
  36. ownKeys(Object(source)).forEach(function (key) {
  37. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  38. });
  39. }
  40. }
  41. return target;
  42. }
  43. function _typeof(obj) {
  44. "@babel/helpers - typeof";
  45.  
  46. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  47. _typeof = function (obj) {
  48. return typeof obj;
  49. };
  50. } else {
  51. _typeof = function (obj) {
  52. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  53. };
  54. }
  55. return _typeof(obj);
  56. }
  57. function _defineProperty(obj, key, value) {
  58. if (key in obj) {
  59. Object.defineProperty(obj, key, {
  60. value: value,
  61. enumerable: true,
  62. configurable: true,
  63. writable: true
  64. });
  65. } else {
  66. obj[key] = value;
  67. }
  68. return obj;
  69. }
  70. function _extends() {
  71. _extends = Object.assign || function (target) {
  72. for (var i = 1; i < arguments.length; i++) {
  73. var source = arguments[i];
  74. for (var key in source) {
  75. if (Object.prototype.hasOwnProperty.call(source, key)) {
  76. target[key] = source[key];
  77. }
  78. }
  79. }
  80. return target;
  81. };
  82. return _extends.apply(this, arguments);
  83. }
  84. function _objectWithoutPropertiesLoose(source, excluded) {
  85. if (source == null) return {};
  86. var target = {};
  87. var sourceKeys = Object.keys(source);
  88. var key, i;
  89. for (i = 0; i < sourceKeys.length; i++) {
  90. key = sourceKeys[i];
  91. if (excluded.indexOf(key) >= 0) continue;
  92. target[key] = source[key];
  93. }
  94. return target;
  95. }
  96. function _objectWithoutProperties(source, excluded) {
  97. if (source == null) return {};
  98. var target = _objectWithoutPropertiesLoose(source, excluded);
  99. var key, i;
  100. if (Object.getOwnPropertySymbols) {
  101. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  102. for (i = 0; i < sourceSymbolKeys.length; i++) {
  103. key = sourceSymbolKeys[i];
  104. if (excluded.indexOf(key) >= 0) continue;
  105. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  106. target[key] = source[key];
  107. }
  108. }
  109. return target;
  110. }
  111. function _toConsumableArray(arr) {
  112. return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
  113. }
  114. function _arrayWithoutHoles(arr) {
  115. if (Array.isArray(arr)) return _arrayLikeToArray(arr);
  116. }
  117. function _iterableToArray(iter) {
  118. if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
  119. }
  120. function _unsupportedIterableToArray(o, minLen) {
  121. if (!o) return;
  122. if (typeof o === "string") return _arrayLikeToArray(o, minLen);
  123. var n = Object.prototype.toString.call(o).slice(8, -1);
  124. if (n === "Object" && o.constructor) n = o.constructor.name;
  125. if (n === "Map" || n === "Set") return Array.from(o);
  126. if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
  127. }
  128. function _arrayLikeToArray(arr, len) {
  129. if (len == null || len > arr.length) len = arr.length;
  130. for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
  131. return arr2;
  132. }
  133. function _nonIterableSpread() {
  134. throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
  135. }
  136.  
  137. var version = "1.15.1";
  138.  
  139. function userAgent(pattern) {
  140. if (typeof window !== 'undefined' && window.navigator) {
  141. return !! /*@__PURE__*/navigator.userAgent.match(pattern);
  142. }
  143. }
  144. var IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i);
  145. var Edge = userAgent(/Edge/i);
  146. var FireFox = userAgent(/firefox/i);
  147. var Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i);
  148. var IOS = userAgent(/iP(ad|od|hone)/i);
  149. var ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i);
  150.  
  151. var captureMode = {
  152. capture: false,
  153. passive: false
  154. };
  155. function on(el, event, fn) {
  156. el.addEventListener(event, fn, !IE11OrLess && captureMode);
  157. }
  158. function off(el, event, fn) {
  159. el.removeEventListener(event, fn, !IE11OrLess && captureMode);
  160. }
  161. function matches( /**HTMLElement*/el, /**String*/selector) {
  162. if (!selector) return;
  163. selector[0] === '>' && (selector = selector.substring(1));
  164. if (el) {
  165. try {
  166. if (el.matches) {
  167. return el.matches(selector);
  168. } else if (el.msMatchesSelector) {
  169. return el.msMatchesSelector(selector);
  170. } else if (el.webkitMatchesSelector) {
  171. return el.webkitMatchesSelector(selector);
  172. }
  173. } catch (_) {
  174. return false;
  175. }
  176. }
  177. return false;
  178. }
  179. function getParentOrHost(el) {
  180. return el.host && el !== document && el.host.nodeType ? el.host : el.parentNode;
  181. }
  182. function closest( /**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) {
  183. if (el) {
  184. ctx = ctx || document;
  185. do {
  186. if (selector != null && (selector[0] === '>' ? el.parentNode === ctx && matches(el, selector) : matches(el, selector)) || includeCTX && el === ctx) {
  187. return el;
  188. }
  189. if (el === ctx) break;
  190. /* jshint boss:true */
  191. } while (el = getParentOrHost(el));
  192. }
  193. return null;
  194. }
  195. var R_SPACE = /\s+/g;
  196. function toggleClass(el, name, state) {
  197. if (el && name) {
  198. if (el.classList) {
  199. el.classList[state ? 'add' : 'remove'](name);
  200. } else {
  201. var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');
  202. el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');
  203. }
  204. }
  205. }
  206. function css(el, prop, val) {
  207. var style = el && el.style;
  208. if (style) {
  209. if (val === void 0) {
  210. if (document.defaultView && document.defaultView.getComputedStyle) {
  211. val = document.defaultView.getComputedStyle(el, '');
  212. } else if (el.currentStyle) {
  213. val = el.currentStyle;
  214. }
  215. return prop === void 0 ? val : val[prop];
  216. } else {
  217. if (!(prop in style) && prop.indexOf('webkit') === -1) {
  218. prop = '-webkit-' + prop;
  219. }
  220. style[prop] = val + (typeof val === 'string' ? '' : 'px');
  221. }
  222. }
  223. }
  224. function matrix(el, selfOnly) {
  225. var appliedTransforms = '';
  226. if (typeof el === 'string') {
  227. appliedTransforms = el;
  228. } else {
  229. do {
  230. var transform = css(el, 'transform');
  231. if (transform && transform !== 'none') {
  232. appliedTransforms = transform + ' ' + appliedTransforms;
  233. }
  234. /* jshint boss:true */
  235. } while (!selfOnly && (el = el.parentNode));
  236. }
  237. var matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || window.CSSMatrix || window.MSCSSMatrix;
  238. /*jshint -W056 */
  239. return matrixFn && new matrixFn(appliedTransforms);
  240. }
  241. function find(ctx, tagName, iterator) {
  242. if (ctx) {
  243. var list = ctx.getElementsByTagName(tagName),
  244. i = 0,
  245. n = list.length;
  246. if (iterator) {
  247. for (; i < n; i++) {
  248. iterator(list[i], i);
  249. }
  250. }
  251. return list;
  252. }
  253. return [];
  254. }
  255. function getWindowScrollingElement() {
  256. var scrollingElement = document.scrollingElement;
  257. if (scrollingElement) {
  258. return scrollingElement;
  259. } else {
  260. return document.documentElement;
  261. }
  262. }
  263.  
  264. /**
  265. * Returns the "bounding client rect" of given element
  266. * @param {HTMLElement} el The element whose boundingClientRect is wanted
  267. * @param {[Boolean]} relativeToContainingBlock Whether the rect should be relative to the containing block of (including) the container
  268. * @param {[Boolean]} relativeToNonStaticParent Whether the rect should be relative to the relative parent of (including) the contaienr
  269. * @param {[Boolean]} undoScale Whether the container's scale() should be undone
  270. * @param {[HTMLElement]} container The parent the element will be placed in
  271. * @return {Object} The boundingClientRect of el, with specified adjustments
  272. */
  273. function getRect(el, relativeToContainingBlock, relativeToNonStaticParent, undoScale, container) {
  274. if (!el.getBoundingClientRect && el !== window) return;
  275. var elRect, top, left, bottom, right, height, width;
  276. if (el !== window && el.parentNode && el !== getWindowScrollingElement()) {
  277. elRect = el.getBoundingClientRect();
  278. top = elRect.top;
  279. left = elRect.left;
  280. bottom = elRect.bottom;
  281. right = elRect.right;
  282. height = elRect.height;
  283. width = elRect.width;
  284. } else {
  285. top = 0;
  286. left = 0;
  287. bottom = window.innerHeight;
  288. right = window.innerWidth;
  289. height = window.innerHeight;
  290. width = window.innerWidth;
  291. }
  292. if ((relativeToContainingBlock || relativeToNonStaticParent) && el !== window) {
  293. // Adjust for translate()
  294. container = container || el.parentNode;
  295.  
  296. // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312)
  297. // Not needed on <= IE11
  298. if (!IE11OrLess) {
  299. do {
  300. if (container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || relativeToNonStaticParent && css(container, 'position') !== 'static')) {
  301. var containerRect = container.getBoundingClientRect();
  302.  
  303. // Set relative to edges of padding box of container
  304. top -= containerRect.top + parseInt(css(container, 'border-top-width'));
  305. left -= containerRect.left + parseInt(css(container, 'border-left-width'));
  306. bottom = top + elRect.height;
  307. right = left + elRect.width;
  308. break;
  309. }
  310. /* jshint boss:true */
  311. } while (container = container.parentNode);
  312. }
  313. }
  314. if (undoScale && el !== window) {
  315. // Adjust for scale()
  316. var elMatrix = matrix(container || el),
  317. scaleX = elMatrix && elMatrix.a,
  318. scaleY = elMatrix && elMatrix.d;
  319. if (elMatrix) {
  320. top /= scaleY;
  321. left /= scaleX;
  322. width /= scaleX;
  323. height /= scaleY;
  324. bottom = top + height;
  325. right = left + width;
  326. }
  327. }
  328. return {
  329. top: top,
  330. left: left,
  331. bottom: bottom,
  332. right: right,
  333. width: width,
  334. height: height
  335. };
  336. }
  337.  
  338. /**
  339. * Returns the content rect of the element (bounding rect minus border and padding)
  340. * @param {HTMLElement} el
  341. */
  342. function getContentRect(el) {
  343. var rect = getRect(el);
  344. var paddingLeft = parseInt(css(el, 'padding-left')),
  345. paddingTop = parseInt(css(el, 'padding-top')),
  346. paddingRight = parseInt(css(el, 'padding-right')),
  347. paddingBottom = parseInt(css(el, 'padding-bottom'));
  348. rect.top += paddingTop + parseInt(css(el, 'border-top-width'));
  349. rect.left += paddingLeft + parseInt(css(el, 'border-left-width'));
  350. // Client Width/Height includes padding only
  351. rect.width = el.clientWidth - paddingLeft - paddingRight;
  352. rect.height = el.clientHeight - paddingTop - paddingBottom;
  353. rect.bottom = rect.top + rect.height;
  354. rect.right = rect.left + rect.width;
  355. return rect;
  356. }
  357.  
  358. /**
  359. * Checks if a side of an element is scrolled past a side of its parents
  360. * @param {HTMLElement} el The element who's side being scrolled out of view is in question
  361. * @param {String} elSide Side of the element in question ('top', 'left', 'right', 'bottom')
  362. * @param {String} parentSide Side of the parent in question ('top', 'left', 'right', 'bottom')
  363. * @return {HTMLElement} The parent scroll element that the el's side is scrolled past, or null if there is no such element
  364. */
  365. function isScrolledPast(el, elSide, parentSide) {
  366. var parent = getParentAutoScrollElement(el, true),
  367. elSideVal = getRect(el)[elSide];
  368.  
  369. /* jshint boss:true */
  370. while (parent) {
  371. var parentSideVal = getRect(parent)[parentSide],
  372. visible = void 0;
  373. if (parentSide === 'top' || parentSide === 'left') {
  374. visible = elSideVal >= parentSideVal;
  375. } else {
  376. visible = elSideVal <= parentSideVal;
  377. }
  378. if (!visible) return parent;
  379. if (parent === getWindowScrollingElement()) break;
  380. parent = getParentAutoScrollElement(parent, false);
  381. }
  382. return false;
  383. }
  384.  
  385. /**
  386. * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible)
  387. * and non-draggable elements
  388. * @param {HTMLElement} el The parent element
  389. * @param {Number} childNum The index of the child
  390. * @param {Object} options Parent Sortable's options
  391. * @return {HTMLElement} The child at index childNum, or null if not found
  392. */
  393. function getChild(el, childNum, options, includeDragEl) {
  394. var currentChild = 0,
  395. i = 0,
  396. children = el.children;
  397. while (i < children.length) {
  398. if (children[i].style.display !== 'none' && children[i] !== Sortable.ghost && (includeDragEl || children[i] !== Sortable.dragged) && closest(children[i], options.draggable, el, false)) {
  399. if (currentChild === childNum) {
  400. return children[i];
  401. }
  402. currentChild++;
  403. }
  404. i++;
  405. }
  406. return null;
  407. }
  408.  
  409. /**
  410. * Gets the last child in the el, ignoring ghostEl or invisible elements (clones)
  411. * @param {HTMLElement} el Parent element
  412. * @param {selector} selector Any other elements that should be ignored
  413. * @return {HTMLElement} The last child, ignoring ghostEl
  414. */
  415. function lastChild(el, selector) {
  416. var last = el.lastElementChild;
  417. while (last && (last === Sortable.ghost || css(last, 'display') === 'none' || selector && !matches(last, selector))) {
  418. last = last.previousElementSibling;
  419. }
  420. return last || null;
  421. }
  422.  
  423. /**
  424. * Returns the index of an element within its parent for a selected set of
  425. * elements
  426. * @param {HTMLElement} el
  427. * @param {selector} selector
  428. * @return {number}
  429. */
  430. function index(el, selector) {
  431. var index = 0;
  432. if (!el || !el.parentNode) {
  433. return -1;
  434. }
  435.  
  436. /* jshint boss:true */
  437. while (el = el.previousElementSibling) {
  438. if (el.nodeName.toUpperCase() !== 'TEMPLATE' && el !== Sortable.clone && (!selector || matches(el, selector))) {
  439. index++;
  440. }
  441. }
  442. return index;
  443. }
  444.  
  445. /**
  446. * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements.
  447. * The value is returned in real pixels.
  448. * @param {HTMLElement} el
  449. * @return {Array} Offsets in the format of [left, top]
  450. */
  451. function getRelativeScrollOffset(el) {
  452. var offsetLeft = 0,
  453. offsetTop = 0,
  454. winScroller = getWindowScrollingElement();
  455. if (el) {
  456. do {
  457. var elMatrix = matrix(el),
  458. scaleX = elMatrix.a,
  459. scaleY = elMatrix.d;
  460. offsetLeft += el.scrollLeft * scaleX;
  461. offsetTop += el.scrollTop * scaleY;
  462. } while (el !== winScroller && (el = el.parentNode));
  463. }
  464. return [offsetLeft, offsetTop];
  465. }
  466.  
  467. /**
  468. * Returns the index of the object within the given array
  469. * @param {Array} arr Array that may or may not hold the object
  470. * @param {Object} obj An object that has a key-value pair unique to and identical to a key-value pair in the object you want to find
  471. * @return {Number} The index of the object in the array, or -1
  472. */
  473. function indexOfObject(arr, obj) {
  474. for (var i in arr) {
  475. if (!arr.hasOwnProperty(i)) continue;
  476. for (var key in obj) {
  477. if (obj.hasOwnProperty(key) && obj[key] === arr[i][key]) return Number(i);
  478. }
  479. }
  480. return -1;
  481. }
  482. function getParentAutoScrollElement(el, includeSelf) {
  483. // skip to window
  484. if (!el || !el.getBoundingClientRect) return getWindowScrollingElement();
  485. var elem = el;
  486. var gotSelf = false;
  487. do {
  488. // we don't need to get elem css if it isn't even overflowing in the first place (performance)
  489. if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) {
  490. var elemCSS = css(elem);
  491. if (elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')) {
  492. if (!elem.getBoundingClientRect || elem === document.body) return getWindowScrollingElement();
  493. if (gotSelf || includeSelf) return elem;
  494. gotSelf = true;
  495. }
  496. }
  497. /* jshint boss:true */
  498. } while (elem = elem.parentNode);
  499. return getWindowScrollingElement();
  500. }
  501. function extend(dst, src) {
  502. if (dst && src) {
  503. for (var key in src) {
  504. if (src.hasOwnProperty(key)) {
  505. dst[key] = src[key];
  506. }
  507. }
  508. }
  509. return dst;
  510. }
  511. function isRectEqual(rect1, rect2) {
  512. return Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width);
  513. }
  514. var _throttleTimeout;
  515. function throttle(callback, ms) {
  516. return function () {
  517. if (!_throttleTimeout) {
  518. var args = arguments,
  519. _this = this;
  520. if (args.length === 1) {
  521. callback.call(_this, args[0]);
  522. } else {
  523. callback.apply(_this, args);
  524. }
  525. _throttleTimeout = setTimeout(function () {
  526. _throttleTimeout = void 0;
  527. }, ms);
  528. }
  529. };
  530. }
  531. function cancelThrottle() {
  532. clearTimeout(_throttleTimeout);
  533. _throttleTimeout = void 0;
  534. }
  535. function scrollBy(el, x, y) {
  536. el.scrollLeft += x;
  537. el.scrollTop += y;
  538. }
  539. function clone(el) {
  540. var Polymer = window.Polymer;
  541. var $ = window.jQuery || window.Zepto;
  542. if (Polymer && Polymer.dom) {
  543. return Polymer.dom(el).cloneNode(true);
  544. } else if ($) {
  545. return $(el).clone(true)[0];
  546. } else {
  547. return el.cloneNode(true);
  548. }
  549. }
  550. function setRect(el, rect) {
  551. css(el, 'position', 'absolute');
  552. css(el, 'top', rect.top);
  553. css(el, 'left', rect.left);
  554. css(el, 'width', rect.width);
  555. css(el, 'height', rect.height);
  556. }
  557. function unsetRect(el) {
  558. css(el, 'position', '');
  559. css(el, 'top', '');
  560. css(el, 'left', '');
  561. css(el, 'width', '');
  562. css(el, 'height', '');
  563. }
  564. var expando = 'Sortable' + new Date().getTime();
  565.  
  566. function AnimationStateManager() {
  567. var animationStates = [],
  568. animationCallbackId;
  569. return {
  570. captureAnimationState: function captureAnimationState() {
  571. animationStates = [];
  572. if (!this.options.animation) return;
  573. var children = [].slice.call(this.el.children);
  574. children.forEach(function (child) {
  575. if (css(child, 'display') === 'none' || child === Sortable.ghost) return;
  576. animationStates.push({
  577. target: child,
  578. rect: getRect(child)
  579. });
  580. var fromRect = _objectSpread2({}, animationStates[animationStates.length - 1].rect);
  581.  
  582. // If animating: compensate for current animation
  583. if (child.thisAnimationDuration) {
  584. var childMatrix = matrix(child, true);
  585. if (childMatrix) {
  586. fromRect.top -= childMatrix.f;
  587. fromRect.left -= childMatrix.e;
  588. }
  589. }
  590. child.fromRect = fromRect;
  591. });
  592. },
  593. addAnimationState: function addAnimationState(state) {
  594. animationStates.push(state);
  595. },
  596. removeAnimationState: function removeAnimationState(target) {
  597. animationStates.splice(indexOfObject(animationStates, {
  598. target: target
  599. }), 1);
  600. },
  601. animateAll: function animateAll(callback) {
  602. var _this = this;
  603. if (!this.options.animation) {
  604. clearTimeout(animationCallbackId);
  605. if (typeof callback === 'function') callback();
  606. return;
  607. }
  608. var animating = false,
  609. animationTime = 0;
  610. animationStates.forEach(function (state) {
  611. var time = 0,
  612. target = state.target,
  613. fromRect = target.fromRect,
  614. toRect = getRect(target),
  615. prevFromRect = target.prevFromRect,
  616. prevToRect = target.prevToRect,
  617. animatingRect = state.rect,
  618. targetMatrix = matrix(target, true);
  619. if (targetMatrix) {
  620. // Compensate for current animation
  621. toRect.top -= targetMatrix.f;
  622. toRect.left -= targetMatrix.e;
  623. }
  624. target.toRect = toRect;
  625. if (target.thisAnimationDuration) {
  626. // Could also check if animatingRect is between fromRect and toRect
  627. if (isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) &&
  628. // Make sure animatingRect is on line between toRect & fromRect
  629. (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left)) {
  630. // If returning to same place as started from animation and on same axis
  631. time = calculateRealTime(animatingRect, prevFromRect, prevToRect, _this.options);
  632. }
  633. }
  634.  
  635. // if fromRect != toRect: animate
  636. if (!isRectEqual(toRect, fromRect)) {
  637. target.prevFromRect = fromRect;
  638. target.prevToRect = toRect;
  639. if (!time) {
  640. time = _this.options.animation;
  641. }
  642. _this.animate(target, animatingRect, toRect, time);
  643. }
  644. if (time) {
  645. animating = true;
  646. animationTime = Math.max(animationTime, time);
  647. clearTimeout(target.animationResetTimer);
  648. target.animationResetTimer = setTimeout(function () {
  649. target.animationTime = 0;
  650. target.prevFromRect = null;
  651. target.fromRect = null;
  652. target.prevToRect = null;
  653. target.thisAnimationDuration = null;
  654. }, time);
  655. target.thisAnimationDuration = time;
  656. }
  657. });
  658. clearTimeout(animationCallbackId);
  659. if (!animating) {
  660. if (typeof callback === 'function') callback();
  661. } else {
  662. animationCallbackId = setTimeout(function () {
  663. if (typeof callback === 'function') callback();
  664. }, animationTime);
  665. }
  666. animationStates = [];
  667. },
  668. animate: function animate(target, currentRect, toRect, duration) {
  669. if (duration) {
  670. css(target, 'transition', '');
  671. css(target, 'transform', '');
  672. var elMatrix = matrix(this.el),
  673. scaleX = elMatrix && elMatrix.a,
  674. scaleY = elMatrix && elMatrix.d,
  675. translateX = (currentRect.left - toRect.left) / (scaleX || 1),
  676. translateY = (currentRect.top - toRect.top) / (scaleY || 1);
  677. target.animatingX = !!translateX;
  678. target.animatingY = !!translateY;
  679. css(target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)');
  680. this.forRepaintDummy = repaint(target); // repaint
  681.  
  682. css(target, 'transition', 'transform ' + duration + 'ms' + (this.options.easing ? ' ' + this.options.easing : ''));
  683. css(target, 'transform', 'translate3d(0,0,0)');
  684. typeof target.animated === 'number' && clearTimeout(target.animated);
  685. target.animated = setTimeout(function () {
  686. css(target, 'transition', '');
  687. css(target, 'transform', '');
  688. target.animated = false;
  689. target.animatingX = false;
  690. target.animatingY = false;
  691. }, duration);
  692. }
  693. }
  694. };
  695. }
  696. function repaint(target) {
  697. return target.offsetWidth;
  698. }
  699. function calculateRealTime(animatingRect, fromRect, toRect, options) {
  700. return Math.sqrt(Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2)) / Math.sqrt(Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2)) * options.animation;
  701. }
  702.  
  703. var plugins = [];
  704. var defaults = {
  705. initializeByDefault: true
  706. };
  707. var PluginManager = {
  708. mount: function mount(plugin) {
  709. // Set default static properties
  710. for (var option in defaults) {
  711. if (defaults.hasOwnProperty(option) && !(option in plugin)) {
  712. plugin[option] = defaults[option];
  713. }
  714. }
  715. plugins.forEach(function (p) {
  716. if (p.pluginName === plugin.pluginName) {
  717. throw "Sortable: Cannot mount plugin ".concat(plugin.pluginName, " more than once");
  718. }
  719. });
  720. plugins.push(plugin);
  721. },
  722. pluginEvent: function pluginEvent(eventName, sortable, evt) {
  723. var _this = this;
  724. this.eventCanceled = false;
  725. evt.cancel = function () {
  726. _this.eventCanceled = true;
  727. };
  728. var eventNameGlobal = eventName + 'Global';
  729. plugins.forEach(function (plugin) {
  730. if (!sortable[plugin.pluginName]) return;
  731. // Fire global events if it exists in this sortable
  732. if (sortable[plugin.pluginName][eventNameGlobal]) {
  733. sortable[plugin.pluginName][eventNameGlobal](_objectSpread2({
  734. sortable: sortable
  735. }, evt));
  736. }
  737.  
  738. // Only fire plugin event if plugin is enabled in this sortable,
  739. // and plugin has event defined
  740. if (sortable.options[plugin.pluginName] && sortable[plugin.pluginName][eventName]) {
  741. sortable[plugin.pluginName][eventName](_objectSpread2({
  742. sortable: sortable
  743. }, evt));
  744. }
  745. });
  746. },
  747. initializePlugins: function initializePlugins(sortable, el, defaults, options) {
  748. plugins.forEach(function (plugin) {
  749. var pluginName = plugin.pluginName;
  750. if (!sortable.options[pluginName] && !plugin.initializeByDefault) return;
  751. var initialized = new plugin(sortable, el, sortable.options);
  752. initialized.sortable = sortable;
  753. initialized.options = sortable.options;
  754. sortable[pluginName] = initialized;
  755.  
  756. // Add default options from plugin
  757. _extends(defaults, initialized.defaults);
  758. });
  759. for (var option in sortable.options) {
  760. if (!sortable.options.hasOwnProperty(option)) continue;
  761. var modified = this.modifyOption(sortable, option, sortable.options[option]);
  762. if (typeof modified !== 'undefined') {
  763. sortable.options[option] = modified;
  764. }
  765. }
  766. },
  767. getEventProperties: function getEventProperties(name, sortable) {
  768. var eventProperties = {};
  769. plugins.forEach(function (plugin) {
  770. if (typeof plugin.eventProperties !== 'function') return;
  771. _extends(eventProperties, plugin.eventProperties.call(sortable[plugin.pluginName], name));
  772. });
  773. return eventProperties;
  774. },
  775. modifyOption: function modifyOption(sortable, name, value) {
  776. var modifiedValue;
  777. plugins.forEach(function (plugin) {
  778. // Plugin must exist on the Sortable
  779. if (!sortable[plugin.pluginName]) return;
  780.  
  781. // If static option listener exists for this option, call in the context of the Sortable's instance of this plugin
  782. if (plugin.optionListeners && typeof plugin.optionListeners[name] === 'function') {
  783. modifiedValue = plugin.optionListeners[name].call(sortable[plugin.pluginName], value);
  784. }
  785. });
  786. return modifiedValue;
  787. }
  788. };
  789.  
  790. function dispatchEvent(_ref) {
  791. var sortable = _ref.sortable,
  792. rootEl = _ref.rootEl,
  793. name = _ref.name,
  794. targetEl = _ref.targetEl,
  795. cloneEl = _ref.cloneEl,
  796. toEl = _ref.toEl,
  797. fromEl = _ref.fromEl,
  798. oldIndex = _ref.oldIndex,
  799. newIndex = _ref.newIndex,
  800. oldDraggableIndex = _ref.oldDraggableIndex,
  801. newDraggableIndex = _ref.newDraggableIndex,
  802. originalEvent = _ref.originalEvent,
  803. putSortable = _ref.putSortable,
  804. extraEventProperties = _ref.extraEventProperties;
  805. sortable = sortable || rootEl && rootEl[expando];
  806. if (!sortable) return;
  807. var evt,
  808. options = sortable.options,
  809. onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);
  810. // Support for new CustomEvent feature
  811. if (window.CustomEvent && !IE11OrLess && !Edge) {
  812. evt = new CustomEvent(name, {
  813. bubbles: true,
  814. cancelable: true
  815. });
  816. } else {
  817. evt = document.createEvent('Event');
  818. evt.initEvent(name, true, true);
  819. }
  820. evt.to = toEl || rootEl;
  821. evt.from = fromEl || rootEl;
  822. evt.item = targetEl || rootEl;
  823. evt.clone = cloneEl;
  824. evt.oldIndex = oldIndex;
  825. evt.newIndex = newIndex;
  826. evt.oldDraggableIndex = oldDraggableIndex;
  827. evt.newDraggableIndex = newDraggableIndex;
  828. evt.originalEvent = originalEvent;
  829. evt.pullMode = putSortable ? putSortable.lastPutMode : undefined;
  830. var allEventProperties = _objectSpread2(_objectSpread2({}, extraEventProperties), PluginManager.getEventProperties(name, sortable));
  831. for (var option in allEventProperties) {
  832. evt[option] = allEventProperties[option];
  833. }
  834. if (rootEl) {
  835. rootEl.dispatchEvent(evt);
  836. }
  837. if (options[onName]) {
  838. options[onName].call(sortable, evt);
  839. }
  840. }
  841.  
  842. var _excluded = ["evt"];
  843. var pluginEvent = function pluginEvent(eventName, sortable) {
  844. var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  845. originalEvent = _ref.evt,
  846. data = _objectWithoutProperties(_ref, _excluded);
  847. PluginManager.pluginEvent.bind(Sortable)(eventName, sortable, _objectSpread2({
  848. dragEl: dragEl,
  849. parentEl: parentEl,
  850. ghostEl: ghostEl,
  851. rootEl: rootEl,
  852. nextEl: nextEl,
  853. lastDownEl: lastDownEl,
  854. cloneEl: cloneEl,
  855. cloneHidden: cloneHidden,
  856. dragStarted: moved,
  857. putSortable: putSortable,
  858. activeSortable: Sortable.active,
  859. originalEvent: originalEvent,
  860. oldIndex: oldIndex,
  861. oldDraggableIndex: oldDraggableIndex,
  862. newIndex: newIndex,
  863. newDraggableIndex: newDraggableIndex,
  864. hideGhostForTarget: _hideGhostForTarget,
  865. unhideGhostForTarget: _unhideGhostForTarget,
  866. cloneNowHidden: function cloneNowHidden() {
  867. cloneHidden = true;
  868. },
  869. cloneNowShown: function cloneNowShown() {
  870. cloneHidden = false;
  871. },
  872. dispatchSortableEvent: function dispatchSortableEvent(name) {
  873. _dispatchEvent({
  874. sortable: sortable,
  875. name: name,
  876. originalEvent: originalEvent
  877. });
  878. }
  879. }, data));
  880. };
  881. function _dispatchEvent(info) {
  882. dispatchEvent(_objectSpread2({
  883. putSortable: putSortable,
  884. cloneEl: cloneEl,
  885. targetEl: dragEl,
  886. rootEl: rootEl,
  887. oldIndex: oldIndex,
  888. oldDraggableIndex: oldDraggableIndex,
  889. newIndex: newIndex,
  890. newDraggableIndex: newDraggableIndex
  891. }, info));
  892. }
  893. var dragEl,
  894. parentEl,
  895. ghostEl,
  896. rootEl,
  897. nextEl,
  898. lastDownEl,
  899. cloneEl,
  900. cloneHidden,
  901. oldIndex,
  902. newIndex,
  903. oldDraggableIndex,
  904. newDraggableIndex,
  905. activeGroup,
  906. putSortable,
  907. awaitingDragStarted = false,
  908. ignoreNextClick = false,
  909. sortables = [],
  910. tapEvt,
  911. touchEvt,
  912. lastDx,
  913. lastDy,
  914. tapDistanceLeft,
  915. tapDistanceTop,
  916. moved,
  917. lastTarget,
  918. lastDirection,
  919. pastFirstInvertThresh = false,
  920. isCircumstantialInvert = false,
  921. targetMoveDistance,
  922. // For positioning ghost absolutely
  923. ghostRelativeParent,
  924. ghostRelativeParentInitialScroll = [],
  925. // (left, top)
  926.  
  927. _silent = false,
  928. savedInputChecked = [];
  929.  
  930. /** @const */
  931. var documentExists = typeof document !== 'undefined',
  932. PositionGhostAbsolutely = IOS,
  933. CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float',
  934. // This will not pass for IE9, because IE9 DnD only works on anchors
  935. supportDraggable = documentExists && !ChromeForAndroid && !IOS && 'draggable' in document.createElement('div'),
  936. supportCssPointerEvents = function () {
  937. if (!documentExists) return;
  938. // false when <= IE11
  939. if (IE11OrLess) {
  940. return false;
  941. }
  942. var el = document.createElement('x');
  943. el.style.cssText = 'pointer-events:auto';
  944. return el.style.pointerEvents === 'auto';
  945. }(),
  946. _detectDirection = function _detectDirection(el, options) {
  947. var elCSS = css(el),
  948. elWidth = parseInt(elCSS.width) - parseInt(elCSS.paddingLeft) - parseInt(elCSS.paddingRight) - parseInt(elCSS.borderLeftWidth) - parseInt(elCSS.borderRightWidth),
  949. child1 = getChild(el, 0, options),
  950. child2 = getChild(el, 1, options),
  951. firstChildCSS = child1 && css(child1),
  952. secondChildCSS = child2 && css(child2),
  953. firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + getRect(child1).width,
  954. secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + getRect(child2).width;
  955. if (elCSS.display === 'flex') {
  956. return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal';
  957. }
  958. if (elCSS.display === 'grid') {
  959. return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal';
  960. }
  961. if (child1 && firstChildCSS["float"] && firstChildCSS["float"] !== 'none') {
  962. var touchingSideChild2 = firstChildCSS["float"] === 'left' ? 'left' : 'right';
  963. return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ? 'vertical' : 'horizontal';
  964. }
  965. return child1 && (firstChildCSS.display === 'block' || firstChildCSS.display === 'flex' || firstChildCSS.display === 'table' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS[CSSFloatProperty] === 'none' || child2 && elCSS[CSSFloatProperty] === 'none' && firstChildWidth + secondChildWidth > elWidth) ? 'vertical' : 'horizontal';
  966. },
  967. _dragElInRowColumn = function _dragElInRowColumn(dragRect, targetRect, vertical) {
  968. var dragElS1Opp = vertical ? dragRect.left : dragRect.top,
  969. dragElS2Opp = vertical ? dragRect.right : dragRect.bottom,
  970. dragElOppLength = vertical ? dragRect.width : dragRect.height,
  971. targetS1Opp = vertical ? targetRect.left : targetRect.top,
  972. targetS2Opp = vertical ? targetRect.right : targetRect.bottom,
  973. targetOppLength = vertical ? targetRect.width : targetRect.height;
  974. return dragElS1Opp === targetS1Opp || dragElS2Opp === targetS2Opp || dragElS1Opp + dragElOppLength / 2 === targetS1Opp + targetOppLength / 2;
  975. },
  976. /**
  977. * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold.
  978. * @param {Number} x X position
  979. * @param {Number} y Y position
  980. * @return {HTMLElement} Element of the first found nearest Sortable
  981. */
  982. _detectNearestEmptySortable = function _detectNearestEmptySortable(x, y) {
  983. var ret;
  984. sortables.some(function (sortable) {
  985. var threshold = sortable[expando].options.emptyInsertThreshold;
  986. if (!threshold || lastChild(sortable)) return;
  987. var rect = getRect(sortable),
  988. insideHorizontally = x >= rect.left - threshold && x <= rect.right + threshold,
  989. insideVertically = y >= rect.top - threshold && y <= rect.bottom + threshold;
  990. if (insideHorizontally && insideVertically) {
  991. return ret = sortable;
  992. }
  993. });
  994. return ret;
  995. },
  996. _prepareGroup = function _prepareGroup(options) {
  997. function toFn(value, pull) {
  998. return function (to, from, dragEl, evt) {
  999. var sameGroup = to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name;
  1000. if (value == null && (pull || sameGroup)) {
  1001. // Default pull value
  1002. // Default pull and put value if same group
  1003. return true;
  1004. } else if (value == null || value === false) {
  1005. return false;
  1006. } else if (pull && value === 'clone') {
  1007. return value;
  1008. } else if (typeof value === 'function') {
  1009. return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt);
  1010. } else {
  1011. var otherGroup = (pull ? to : from).options.group.name;
  1012. return value === true || typeof value === 'string' && value === otherGroup || value.join && value.indexOf(otherGroup) > -1;
  1013. }
  1014. };
  1015. }
  1016. var group = {};
  1017. var originalGroup = options.group;
  1018. if (!originalGroup || _typeof(originalGroup) != 'object') {
  1019. originalGroup = {
  1020. name: originalGroup
  1021. };
  1022. }
  1023. group.name = originalGroup.name;
  1024. group.checkPull = toFn(originalGroup.pull, true);
  1025. group.checkPut = toFn(originalGroup.put);
  1026. group.revertClone = originalGroup.revertClone;
  1027. options.group = group;
  1028. },
  1029. _hideGhostForTarget = function _hideGhostForTarget() {
  1030. if (!supportCssPointerEvents && ghostEl) {
  1031. css(ghostEl, 'display', 'none');
  1032. }
  1033. },
  1034. _unhideGhostForTarget = function _unhideGhostForTarget() {
  1035. if (!supportCssPointerEvents && ghostEl) {
  1036. css(ghostEl, 'display', '');
  1037. }
  1038. };
  1039.  
  1040. // #1184 fix - Prevent click event on fallback if dragged but item not changed position
  1041. if (documentExists && !ChromeForAndroid) {
  1042. document.addEventListener('click', function (evt) {
  1043. if (ignoreNextClick) {
  1044. evt.preventDefault();
  1045. evt.stopPropagation && evt.stopPropagation();
  1046. evt.stopImmediatePropagation && evt.stopImmediatePropagation();
  1047. ignoreNextClick = false;
  1048. return false;
  1049. }
  1050. }, true);
  1051. }
  1052. var nearestEmptyInsertDetectEvent = function nearestEmptyInsertDetectEvent(evt) {
  1053. if (dragEl) {
  1054. evt = evt.touches ? evt.touches[0] : evt;
  1055. var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY);
  1056. if (nearest) {
  1057. // Create imitation event
  1058. var event = {};
  1059. for (var i in evt) {
  1060. if (evt.hasOwnProperty(i)) {
  1061. event[i] = evt[i];
  1062. }
  1063. }
  1064. event.target = event.rootEl = nearest;
  1065. event.preventDefault = void 0;
  1066. event.stopPropagation = void 0;
  1067. nearest[expando]._onDragOver(event);
  1068. }
  1069. }
  1070. };
  1071. var _checkOutsideTargetEl = function _checkOutsideTargetEl(evt) {
  1072. if (dragEl) {
  1073. dragEl.parentNode[expando]._isOutsideThisEl(evt.target);
  1074. }
  1075. };
  1076.  
  1077. /**
  1078. * @class Sortable
  1079. * @param {HTMLElement} el
  1080. * @param {Object} [options]
  1081. */
  1082. function Sortable(el, options) {
  1083. if (!(el && el.nodeType && el.nodeType === 1)) {
  1084. throw "Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(el));
  1085. }
  1086. this.el = el; // root element
  1087. this.options = options = _extends({}, options);
  1088.  
  1089. // Export instance
  1090. el[expando] = this;
  1091. var defaults = {
  1092. group: null,
  1093. sort: true,
  1094. disabled: false,
  1095. store: null,
  1096. handle: null,
  1097. draggable: /^[uo]l$/i.test(el.nodeName) ? '>li' : '>*',
  1098. swapThreshold: 1,
  1099. // percentage; 0 <= x <= 1
  1100. invertSwap: false,
  1101. // invert always
  1102. invertedSwapThreshold: null,
  1103. // will be set to same as swapThreshold if default
  1104. removeCloneOnHide: true,
  1105. direction: function direction() {
  1106. return _detectDirection(el, this.options);
  1107. },
  1108. ghostClass: 'sortable-ghost',
  1109. chosenClass: 'sortable-chosen',
  1110. dragClass: 'sortable-drag',
  1111. ignore: 'a, img',
  1112. filter: null,
  1113. preventOnFilter: true,
  1114. animation: 0,
  1115. easing: null,
  1116. setData: function setData(dataTransfer, dragEl) {
  1117. dataTransfer.setData('Text', dragEl.textContent);
  1118. },
  1119. dropBubble: false,
  1120. dragoverBubble: false,
  1121. dataIdAttr: 'data-id',
  1122. delay: 0,
  1123. delayOnTouchOnly: false,
  1124. touchStartThreshold: (Number.parseInt ? Number : window).parseInt(window.devicePixelRatio, 10) || 1,
  1125. forceFallback: false,
  1126. fallbackClass: 'sortable-fallback',
  1127. fallbackOnBody: false,
  1128. fallbackTolerance: 0,
  1129. fallbackOffset: {
  1130. x: 0,
  1131. y: 0
  1132. },
  1133. supportPointer: Sortable.supportPointer !== false && 'PointerEvent' in window && !Safari,
  1134. emptyInsertThreshold: 5
  1135. };
  1136. PluginManager.initializePlugins(this, el, defaults);
  1137.  
  1138. // Set default options
  1139. for (var name in defaults) {
  1140. !(name in options) && (options[name] = defaults[name]);
  1141. }
  1142. _prepareGroup(options);
  1143.  
  1144. // Bind all private methods
  1145. for (var fn in this) {
  1146. if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
  1147. this[fn] = this[fn].bind(this);
  1148. }
  1149. }
  1150.  
  1151. // Setup drag mode
  1152. this.nativeDraggable = options.forceFallback ? false : supportDraggable;
  1153. if (this.nativeDraggable) {
  1154. // Touch start threshold cannot be greater than the native dragstart threshold
  1155. this.options.touchStartThreshold = 1;
  1156. }
  1157.  
  1158. // Bind events
  1159. if (options.supportPointer) {
  1160. on(el, 'pointerdown', this._onTapStart);
  1161. } else {
  1162. on(el, 'mousedown', this._onTapStart);
  1163. on(el, 'touchstart', this._onTapStart);
  1164. }
  1165. if (this.nativeDraggable) {
  1166. on(el, 'dragover', this);
  1167. on(el, 'dragenter', this);
  1168. }
  1169. sortables.push(this.el);
  1170.  
  1171. // Restore sorting
  1172. options.store && options.store.get && this.sort(options.store.get(this) || []);
  1173.  
  1174. // Add animation state manager
  1175. _extends(this, AnimationStateManager());
  1176. }
  1177. Sortable.prototype = /** @lends Sortable.prototype */{
  1178. constructor: Sortable,
  1179. _isOutsideThisEl: function _isOutsideThisEl(target) {
  1180. if (!this.el.contains(target) && target !== this.el) {
  1181. lastTarget = null;
  1182. }
  1183. },
  1184. _getDirection: function _getDirection(evt, target) {
  1185. return typeof this.options.direction === 'function' ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction;
  1186. },
  1187. _onTapStart: function _onTapStart( /** Event|TouchEvent */evt) {
  1188. if (!evt.cancelable) return;
  1189. var _this = this,
  1190. el = this.el,
  1191. options = this.options,
  1192. preventOnFilter = options.preventOnFilter,
  1193. type = evt.type,
  1194. touch = evt.touches && evt.touches[0] || evt.pointerType && evt.pointerType === 'touch' && evt,
  1195. target = (touch || evt).target,
  1196. originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0] || evt.composedPath && evt.composedPath()[0]) || target,
  1197. filter = options.filter;
  1198. _saveInputCheckedState(el);
  1199.  
  1200. // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.
  1201. if (dragEl) {
  1202. return;
  1203. }
  1204. if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {
  1205. return; // only left button and enabled
  1206. }
  1207.  
  1208. // cancel dnd if original target is content editable
  1209. if (originalTarget.isContentEditable) {
  1210. return;
  1211. }
  1212.  
  1213. // Safari ignores further event handling after mousedown
  1214. if (!this.nativeDraggable && Safari && target && target.tagName.toUpperCase() === 'SELECT') {
  1215. return;
  1216. }
  1217. target = closest(target, options.draggable, el, false);
  1218. if (target && target.animated) {
  1219. return;
  1220. }
  1221. if (lastDownEl === target) {
  1222. // Ignoring duplicate `down`
  1223. return;
  1224. }
  1225.  
  1226. // Get the index of the dragged element within its parent
  1227. oldIndex = index(target);
  1228. oldDraggableIndex = index(target, options.draggable);
  1229.  
  1230. // Check filter
  1231. if (typeof filter === 'function') {
  1232. if (filter.call(this, evt, target, this)) {
  1233. _dispatchEvent({
  1234. sortable: _this,
  1235. rootEl: originalTarget,
  1236. name: 'filter',
  1237. targetEl: target,
  1238. toEl: el,
  1239. fromEl: el
  1240. });
  1241. pluginEvent('filter', _this, {
  1242. evt: evt
  1243. });
  1244. preventOnFilter && evt.cancelable && evt.preventDefault();
  1245. return; // cancel dnd
  1246. }
  1247. } else if (filter) {
  1248. filter = filter.split(',').some(function (criteria) {
  1249. criteria = closest(originalTarget, criteria.trim(), el, false);
  1250. if (criteria) {
  1251. _dispatchEvent({
  1252. sortable: _this,
  1253. rootEl: criteria,
  1254. name: 'filter',
  1255. targetEl: target,
  1256. fromEl: el,
  1257. toEl: el
  1258. });
  1259. pluginEvent('filter', _this, {
  1260. evt: evt
  1261. });
  1262. return true;
  1263. }
  1264. });
  1265. if (filter) {
  1266. preventOnFilter && evt.cancelable && evt.preventDefault();
  1267. return; // cancel dnd
  1268. }
  1269. }
  1270. if (options.handle && !closest(originalTarget, options.handle, el, false)) {
  1271. return;
  1272. }
  1273.  
  1274. // Prepare `dragstart`
  1275. this._prepareDragStart(evt, touch, target);
  1276. },
  1277. _prepareDragStart: function _prepareDragStart( /** Event */evt, /** Touch */touch, /** HTMLElement */target) {
  1278. var _this = this,
  1279. el = _this.el,
  1280. options = _this.options,
  1281. ownerDocument = el.ownerDocument,
  1282. dragStartFn;
  1283. if (target && !dragEl && target.parentNode === el) {
  1284. var dragRect = getRect(target);
  1285. rootEl = el;
  1286. dragEl = target;
  1287. parentEl = dragEl.parentNode;
  1288. nextEl = dragEl.nextSibling;
  1289. lastDownEl = target;
  1290. activeGroup = options.group;
  1291. Sortable.dragged = dragEl;
  1292. tapEvt = {
  1293. target: dragEl,
  1294. clientX: (touch || evt).clientX,
  1295. clientY: (touch || evt).clientY
  1296. };
  1297. tapDistanceLeft = tapEvt.clientX - dragRect.left;
  1298. tapDistanceTop = tapEvt.clientY - dragRect.top;
  1299. this._lastX = (touch || evt).clientX;
  1300. this._lastY = (touch || evt).clientY;
  1301. dragEl.style['will-change'] = 'all';
  1302. dragStartFn = function dragStartFn() {
  1303. pluginEvent('delayEnded', _this, {
  1304. evt: evt
  1305. });
  1306. if (Sortable.eventCanceled) {
  1307. _this._onDrop();
  1308. return;
  1309. }
  1310. // Delayed drag has been triggered
  1311. // we can re-enable the events: touchmove/mousemove
  1312. _this._disableDelayedDragEvents();
  1313. if (!FireFox && _this.nativeDraggable) {
  1314. dragEl.draggable = true;
  1315. }
  1316.  
  1317. // Bind the events: dragstart/dragend
  1318. _this._triggerDragStart(evt, touch);
  1319.  
  1320. // Drag start event
  1321. _dispatchEvent({
  1322. sortable: _this,
  1323. name: 'choose',
  1324. originalEvent: evt
  1325. });
  1326.  
  1327. // Chosen item
  1328. toggleClass(dragEl, options.chosenClass, true);
  1329. };
  1330.  
  1331. // Disable "draggable"
  1332. options.ignore.split(',').forEach(function (criteria) {
  1333. find(dragEl, criteria.trim(), _disableDraggable);
  1334. });
  1335. on(ownerDocument, 'dragover', nearestEmptyInsertDetectEvent);
  1336. on(ownerDocument, 'mousemove', nearestEmptyInsertDetectEvent);
  1337. on(ownerDocument, 'touchmove', nearestEmptyInsertDetectEvent);
  1338. on(ownerDocument, 'mouseup', _this._onDrop);
  1339. on(ownerDocument, 'touchend', _this._onDrop);
  1340. on(ownerDocument, 'touchcancel', _this._onDrop);
  1341.  
  1342. // Make dragEl draggable (must be before delay for FireFox)
  1343. if (FireFox && this.nativeDraggable) {
  1344. this.options.touchStartThreshold = 4;
  1345. dragEl.draggable = true;
  1346. }
  1347. pluginEvent('delayStart', this, {
  1348. evt: evt
  1349. });
  1350.  
  1351. // Delay is impossible for native DnD in Edge or IE
  1352. if (options.delay && (!options.delayOnTouchOnly || touch) && (!this.nativeDraggable || !(Edge || IE11OrLess))) {
  1353. if (Sortable.eventCanceled) {
  1354. this._onDrop();
  1355. return;
  1356. }
  1357. // If the user moves the pointer or let go the click or touch
  1358. // before the delay has been reached:
  1359. // disable the delayed drag
  1360. on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
  1361. on(ownerDocument, 'touchend', _this._disableDelayedDrag);
  1362. on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
  1363. on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler);
  1364. on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);
  1365. options.supportPointer && on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);
  1366. _this._dragStartTimer = setTimeout(dragStartFn, options.delay);
  1367. } else {
  1368. dragStartFn();
  1369. }
  1370. }
  1371. },
  1372. _delayedDragTouchMoveHandler: function _delayedDragTouchMoveHandler( /** TouchEvent|PointerEvent **/e) {
  1373. var touch = e.touches ? e.touches[0] : e;
  1374. if (Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))) {
  1375. this._disableDelayedDrag();
  1376. }
  1377. },
  1378. _disableDelayedDrag: function _disableDelayedDrag() {
  1379. dragEl && _disableDraggable(dragEl);
  1380. clearTimeout(this._dragStartTimer);
  1381. this._disableDelayedDragEvents();
  1382. },
  1383. _disableDelayedDragEvents: function _disableDelayedDragEvents() {
  1384. var ownerDocument = this.el.ownerDocument;
  1385. off(ownerDocument, 'mouseup', this._disableDelayedDrag);
  1386. off(ownerDocument, 'touchend', this._disableDelayedDrag);
  1387. off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
  1388. off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler);
  1389. off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler);
  1390. off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler);
  1391. },
  1392. _triggerDragStart: function _triggerDragStart( /** Event */evt, /** Touch */touch) {
  1393. touch = touch || evt.pointerType == 'touch' && evt;
  1394. if (!this.nativeDraggable || touch) {
  1395. if (this.options.supportPointer) {
  1396. on(document, 'pointermove', this._onTouchMove);
  1397. } else if (touch) {
  1398. on(document, 'touchmove', this._onTouchMove);
  1399. } else {
  1400. on(document, 'mousemove', this._onTouchMove);
  1401. }
  1402. } else {
  1403. on(dragEl, 'dragend', this);
  1404. on(rootEl, 'dragstart', this._onDragStart);
  1405. }
  1406. try {
  1407. if (document.selection) {
  1408. // Timeout neccessary for IE9
  1409. _nextTick(function () {
  1410. document.selection.empty();
  1411. });
  1412. } else {
  1413. window.getSelection().removeAllRanges();
  1414. }
  1415. } catch (err) {}
  1416. },
  1417. _dragStarted: function _dragStarted(fallback, evt) {
  1418. awaitingDragStarted = false;
  1419. if (rootEl && dragEl) {
  1420. pluginEvent('dragStarted', this, {
  1421. evt: evt
  1422. });
  1423. if (this.nativeDraggable) {
  1424. on(document, 'dragover', _checkOutsideTargetEl);
  1425. }
  1426. var options = this.options;
  1427.  
  1428. // Apply effect
  1429. !fallback && toggleClass(dragEl, options.dragClass, false);
  1430. toggleClass(dragEl, options.ghostClass, true);
  1431. Sortable.active = this;
  1432. fallback && this._appendGhost();
  1433.  
  1434. // Drag start event
  1435. _dispatchEvent({
  1436. sortable: this,
  1437. name: 'start',
  1438. originalEvent: evt
  1439. });
  1440. } else {
  1441. this._nulling();
  1442. }
  1443. },
  1444. _emulateDragOver: function _emulateDragOver() {
  1445. if (touchEvt) {
  1446. this._lastX = touchEvt.clientX;
  1447. this._lastY = touchEvt.clientY;
  1448. _hideGhostForTarget();
  1449. var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
  1450. var parent = target;
  1451. while (target && target.shadowRoot) {
  1452. target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
  1453. if (target === parent) break;
  1454. parent = target;
  1455. }
  1456. dragEl.parentNode[expando]._isOutsideThisEl(target);
  1457. if (parent) {
  1458. do {
  1459. if (parent[expando]) {
  1460. var inserted = void 0;
  1461. inserted = parent[expando]._onDragOver({
  1462. clientX: touchEvt.clientX,
  1463. clientY: touchEvt.clientY,
  1464. target: target,
  1465. rootEl: parent
  1466. });
  1467. if (inserted && !this.options.dragoverBubble) {
  1468. break;
  1469. }
  1470. }
  1471. target = parent; // store last element
  1472. }
  1473. /* jshint boss:true */ while (parent = parent.parentNode);
  1474. }
  1475. _unhideGhostForTarget();
  1476. }
  1477. },
  1478. _onTouchMove: function _onTouchMove( /**TouchEvent*/evt) {
  1479. if (tapEvt) {
  1480. var options = this.options,
  1481. fallbackTolerance = options.fallbackTolerance,
  1482. fallbackOffset = options.fallbackOffset,
  1483. touch = evt.touches ? evt.touches[0] : evt,
  1484. ghostMatrix = ghostEl && matrix(ghostEl, true),
  1485. scaleX = ghostEl && ghostMatrix && ghostMatrix.a,
  1486. scaleY = ghostEl && ghostMatrix && ghostMatrix.d,
  1487. relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && getRelativeScrollOffset(ghostRelativeParent),
  1488. dx = (touch.clientX - tapEvt.clientX + fallbackOffset.x) / (scaleX || 1) + (relativeScrollOffset ? relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0] : 0) / (scaleX || 1),
  1489. dy = (touch.clientY - tapEvt.clientY + fallbackOffset.y) / (scaleY || 1) + (relativeScrollOffset ? relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1] : 0) / (scaleY || 1);
  1490.  
  1491. // only set the status to dragging, when we are actually dragging
  1492. if (!Sortable.active && !awaitingDragStarted) {
  1493. if (fallbackTolerance && Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) < fallbackTolerance) {
  1494. return;
  1495. }
  1496. this._onDragStart(evt, true);
  1497. }
  1498. if (ghostEl) {
  1499. if (ghostMatrix) {
  1500. ghostMatrix.e += dx - (lastDx || 0);
  1501. ghostMatrix.f += dy - (lastDy || 0);
  1502. } else {
  1503. ghostMatrix = {
  1504. a: 1,
  1505. b: 0,
  1506. c: 0,
  1507. d: 1,
  1508. e: dx,
  1509. f: dy
  1510. };
  1511. }
  1512. var cssMatrix = "matrix(".concat(ghostMatrix.a, ",").concat(ghostMatrix.b, ",").concat(ghostMatrix.c, ",").concat(ghostMatrix.d, ",").concat(ghostMatrix.e, ",").concat(ghostMatrix.f, ")");
  1513. css(ghostEl, 'webkitTransform', cssMatrix);
  1514. css(ghostEl, 'mozTransform', cssMatrix);
  1515. css(ghostEl, 'msTransform', cssMatrix);
  1516. css(ghostEl, 'transform', cssMatrix);
  1517. lastDx = dx;
  1518. lastDy = dy;
  1519. touchEvt = touch;
  1520. }
  1521. evt.cancelable && evt.preventDefault();
  1522. }
  1523. },
  1524. _appendGhost: function _appendGhost() {
  1525. // Bug if using scale(): https://stackoverflow.com/questions/2637058
  1526. // Not being adjusted for
  1527. if (!ghostEl) {
  1528. var container = this.options.fallbackOnBody ? document.body : rootEl,
  1529. rect = getRect(dragEl, true, PositionGhostAbsolutely, true, container),
  1530. options = this.options;
  1531.  
  1532. // Position absolutely
  1533. if (PositionGhostAbsolutely) {
  1534. // Get relatively positioned parent
  1535. ghostRelativeParent = container;
  1536. while (css(ghostRelativeParent, 'position') === 'static' && css(ghostRelativeParent, 'transform') === 'none' && ghostRelativeParent !== document) {
  1537. ghostRelativeParent = ghostRelativeParent.parentNode;
  1538. }
  1539. if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) {
  1540. if (ghostRelativeParent === document) ghostRelativeParent = getWindowScrollingElement();
  1541. rect.top += ghostRelativeParent.scrollTop;
  1542. rect.left += ghostRelativeParent.scrollLeft;
  1543. } else {
  1544. ghostRelativeParent = getWindowScrollingElement();
  1545. }
  1546. ghostRelativeParentInitialScroll = getRelativeScrollOffset(ghostRelativeParent);
  1547. }
  1548. ghostEl = dragEl.cloneNode(true);
  1549. toggleClass(ghostEl, options.ghostClass, false);
  1550. toggleClass(ghostEl, options.fallbackClass, true);
  1551. toggleClass(ghostEl, options.dragClass, true);
  1552. css(ghostEl, 'transition', '');
  1553. css(ghostEl, 'transform', '');
  1554. css(ghostEl, 'box-sizing', 'border-box');
  1555. css(ghostEl, 'margin', 0);
  1556. css(ghostEl, 'top', rect.top);
  1557. css(ghostEl, 'left', rect.left);
  1558. css(ghostEl, 'width', rect.width);
  1559. css(ghostEl, 'height', rect.height);
  1560. css(ghostEl, 'opacity', '0.8');
  1561. css(ghostEl, 'position', PositionGhostAbsolutely ? 'absolute' : 'fixed');
  1562. css(ghostEl, 'zIndex', '100000');
  1563. css(ghostEl, 'pointerEvents', 'none');
  1564. Sortable.ghost = ghostEl;
  1565. container.appendChild(ghostEl);
  1566.  
  1567. // Set transform-origin
  1568. css(ghostEl, 'transform-origin', tapDistanceLeft / parseInt(ghostEl.style.width) * 100 + '% ' + tapDistanceTop / parseInt(ghostEl.style.height) * 100 + '%');
  1569. }
  1570. },
  1571. _onDragStart: function _onDragStart( /**Event*/evt, /**boolean*/fallback) {
  1572. var _this = this;
  1573. var dataTransfer = evt.dataTransfer;
  1574. var options = _this.options;
  1575. pluginEvent('dragStart', this, {
  1576. evt: evt
  1577. });
  1578. if (Sortable.eventCanceled) {
  1579. this._onDrop();
  1580. return;
  1581. }
  1582. pluginEvent('setupClone', this);
  1583. if (!Sortable.eventCanceled) {
  1584. cloneEl = clone(dragEl);
  1585. cloneEl.removeAttribute("id");
  1586. cloneEl.draggable = false;
  1587. cloneEl.style['will-change'] = '';
  1588. this._hideClone();
  1589. toggleClass(cloneEl, this.options.chosenClass, false);
  1590. Sortable.clone = cloneEl;
  1591. }
  1592.  
  1593. // #1143: IFrame support workaround
  1594. _this.cloneId = _nextTick(function () {
  1595. pluginEvent('clone', _this);
  1596. if (Sortable.eventCanceled) return;
  1597. if (!_this.options.removeCloneOnHide) {
  1598. rootEl.insertBefore(cloneEl, dragEl);
  1599. }
  1600. _this._hideClone();
  1601. _dispatchEvent({
  1602. sortable: _this,
  1603. name: 'clone'
  1604. });
  1605. });
  1606. !fallback && toggleClass(dragEl, options.dragClass, true);
  1607.  
  1608. // Set proper drop events
  1609. if (fallback) {
  1610. ignoreNextClick = true;
  1611. _this._loopId = setInterval(_this._emulateDragOver, 50);
  1612. } else {
  1613. // Undo what was set in _prepareDragStart before drag started
  1614. off(document, 'mouseup', _this._onDrop);
  1615. off(document, 'touchend', _this._onDrop);
  1616. off(document, 'touchcancel', _this._onDrop);
  1617. if (dataTransfer) {
  1618. dataTransfer.effectAllowed = 'move';
  1619. options.setData && options.setData.call(_this, dataTransfer, dragEl);
  1620. }
  1621. on(document, 'drop', _this);
  1622.  
  1623. // #1276 fix:
  1624. css(dragEl, 'transform', 'translateZ(0)');
  1625. }
  1626. awaitingDragStarted = true;
  1627. _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt));
  1628. on(document, 'selectstart', _this);
  1629. moved = true;
  1630. if (Safari) {
  1631. css(document.body, 'user-select', 'none');
  1632. }
  1633. },
  1634. // Returns true - if no further action is needed (either inserted or another condition)
  1635. _onDragOver: function _onDragOver( /**Event*/evt) {
  1636. var el = this.el,
  1637. target = evt.target,
  1638. dragRect,
  1639. targetRect,
  1640. revert,
  1641. options = this.options,
  1642. group = options.group,
  1643. activeSortable = Sortable.active,
  1644. isOwner = activeGroup === group,
  1645. canSort = options.sort,
  1646. fromSortable = putSortable || activeSortable,
  1647. vertical,
  1648. _this = this,
  1649. completedFired = false;
  1650. if (_silent) return;
  1651. function dragOverEvent(name, extra) {
  1652. pluginEvent(name, _this, _objectSpread2({
  1653. evt: evt,
  1654. isOwner: isOwner,
  1655. axis: vertical ? 'vertical' : 'horizontal',
  1656. revert: revert,
  1657. dragRect: dragRect,
  1658. targetRect: targetRect,
  1659. canSort: canSort,
  1660. fromSortable: fromSortable,
  1661. target: target,
  1662. completed: completed,
  1663. onMove: function onMove(target, after) {
  1664. return _onMove(rootEl, el, dragEl, dragRect, target, getRect(target), evt, after);
  1665. },
  1666. changed: changed
  1667. }, extra));
  1668. }
  1669.  
  1670. // Capture animation state
  1671. function capture() {
  1672. dragOverEvent('dragOverAnimationCapture');
  1673. _this.captureAnimationState();
  1674. if (_this !== fromSortable) {
  1675. fromSortable.captureAnimationState();
  1676. }
  1677. }
  1678.  
  1679. // Return invocation when dragEl is inserted (or completed)
  1680. function completed(insertion) {
  1681. dragOverEvent('dragOverCompleted', {
  1682. insertion: insertion
  1683. });
  1684. if (insertion) {
  1685. // Clones must be hidden before folding animation to capture dragRectAbsolute properly
  1686. if (isOwner) {
  1687. activeSortable._hideClone();
  1688. } else {
  1689. activeSortable._showClone(_this);
  1690. }
  1691. if (_this !== fromSortable) {
  1692. // Set ghost class to new sortable's ghost class
  1693. toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false);
  1694. toggleClass(dragEl, options.ghostClass, true);
  1695. }
  1696. if (putSortable !== _this && _this !== Sortable.active) {
  1697. putSortable = _this;
  1698. } else if (_this === Sortable.active && putSortable) {
  1699. putSortable = null;
  1700. }
  1701.  
  1702. // Animation
  1703. if (fromSortable === _this) {
  1704. _this._ignoreWhileAnimating = target;
  1705. }
  1706. _this.animateAll(function () {
  1707. dragOverEvent('dragOverAnimationComplete');
  1708. _this._ignoreWhileAnimating = null;
  1709. });
  1710. if (_this !== fromSortable) {
  1711. fromSortable.animateAll();
  1712. fromSortable._ignoreWhileAnimating = null;
  1713. }
  1714. }
  1715.  
  1716. // Null lastTarget if it is not inside a previously swapped element
  1717. if (target === dragEl && !dragEl.animated || target === el && !target.animated) {
  1718. lastTarget = null;
  1719. }
  1720.  
  1721. // no bubbling and not fallback
  1722. if (!options.dragoverBubble && !evt.rootEl && target !== document) {
  1723. dragEl.parentNode[expando]._isOutsideThisEl(evt.target);
  1724.  
  1725. // Do not detect for empty insert if already inserted
  1726. !insertion && nearestEmptyInsertDetectEvent(evt);
  1727. }
  1728. !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation();
  1729. return completedFired = true;
  1730. }
  1731.  
  1732. // Call when dragEl has been inserted
  1733. function changed() {
  1734. newIndex = index(dragEl);
  1735. newDraggableIndex = index(dragEl, options.draggable);
  1736. _dispatchEvent({
  1737. sortable: _this,
  1738. name: 'change',
  1739. toEl: el,
  1740. newIndex: newIndex,
  1741. newDraggableIndex: newDraggableIndex,
  1742. originalEvent: evt
  1743. });
  1744. }
  1745. if (evt.preventDefault !== void 0) {
  1746. evt.cancelable && evt.preventDefault();
  1747. }
  1748. target = closest(target, options.draggable, el, true);
  1749. dragOverEvent('dragOver');
  1750. if (Sortable.eventCanceled) return completedFired;
  1751. if (dragEl.contains(evt.target) || target.animated && target.animatingX && target.animatingY || _this._ignoreWhileAnimating === target) {
  1752. return completed(false);
  1753. }
  1754. ignoreNextClick = false;
  1755. if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = parentEl !== rootEl) // Reverting item into the original list
  1756. : putSortable === this || (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt))) {
  1757. vertical = this._getDirection(evt, target) === 'vertical';
  1758. dragRect = getRect(dragEl);
  1759. dragOverEvent('dragOverValid');
  1760. if (Sortable.eventCanceled) return completedFired;
  1761. if (revert) {
  1762. parentEl = rootEl; // actualization
  1763. capture();
  1764. this._hideClone();
  1765. dragOverEvent('revert');
  1766. if (!Sortable.eventCanceled) {
  1767. if (nextEl) {
  1768. rootEl.insertBefore(dragEl, nextEl);
  1769. } else {
  1770. rootEl.appendChild(dragEl);
  1771. }
  1772. }
  1773. return completed(true);
  1774. }
  1775. var elLastChild = lastChild(el, options.draggable);
  1776. if (!elLastChild || _ghostIsLast(evt, vertical, this) && !elLastChild.animated) {
  1777. // Insert to end of list
  1778.  
  1779. // If already at end of list: Do not insert
  1780. if (elLastChild === dragEl) {
  1781. return completed(false);
  1782. }
  1783.  
  1784. // if there is a last element, it is the target
  1785. if (elLastChild && el === evt.target) {
  1786. target = elLastChild;
  1787. }
  1788. if (target) {
  1789. targetRect = getRect(target);
  1790. }
  1791. if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) {
  1792. capture();
  1793. if (elLastChild && elLastChild.nextSibling) {
  1794. // the last draggable element is not the last node
  1795. el.insertBefore(dragEl, elLastChild.nextSibling);
  1796. } else {
  1797. el.appendChild(dragEl);
  1798. }
  1799. parentEl = el; // actualization
  1800.  
  1801. changed();
  1802. return completed(true);
  1803. }
  1804. } else if (elLastChild && _ghostIsFirst(evt, vertical, this)) {
  1805. // Insert to start of list
  1806. var firstChild = getChild(el, 0, options, true);
  1807. if (firstChild === dragEl) {
  1808. return completed(false);
  1809. }
  1810. target = firstChild;
  1811. targetRect = getRect(target);
  1812. if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, false) !== false) {
  1813. capture();
  1814. el.insertBefore(dragEl, firstChild);
  1815. parentEl = el; // actualization
  1816.  
  1817. changed();
  1818. return completed(true);
  1819. }
  1820. } else if (target.parentNode === el) {
  1821. targetRect = getRect(target);
  1822. var direction = 0,
  1823. targetBeforeFirstSwap,
  1824. differentLevel = dragEl.parentNode !== el,
  1825. differentRowCol = !_dragElInRowColumn(dragEl.animated && dragEl.toRect || dragRect, target.animated && target.toRect || targetRect, vertical),
  1826. side1 = vertical ? 'top' : 'left',
  1827. scrolledPastTop = isScrolledPast(target, 'top', 'top') || isScrolledPast(dragEl, 'top', 'top'),
  1828. scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0;
  1829. if (lastTarget !== target) {
  1830. targetBeforeFirstSwap = targetRect[side1];
  1831. pastFirstInvertThresh = false;
  1832. isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel;
  1833. }
  1834. direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target);
  1835. var sibling;
  1836. if (direction !== 0) {
  1837. // Check if target is beside dragEl in respective direction (ignoring hidden elements)
  1838. var dragIndex = index(dragEl);
  1839. do {
  1840. dragIndex -= direction;
  1841. sibling = parentEl.children[dragIndex];
  1842. } while (sibling && (css(sibling, 'display') === 'none' || sibling === ghostEl));
  1843. }
  1844. // If dragEl is already beside target: Do not insert
  1845. if (direction === 0 || sibling === target) {
  1846. return completed(false);
  1847. }
  1848. lastTarget = target;
  1849. lastDirection = direction;
  1850. var nextSibling = target.nextElementSibling,
  1851. after = false;
  1852. after = direction === 1;
  1853. var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);
  1854. if (moveVector !== false) {
  1855. if (moveVector === 1 || moveVector === -1) {
  1856. after = moveVector === 1;
  1857. }
  1858. _silent = true;
  1859. setTimeout(_unsilent, 30);
  1860. capture();
  1861. if (after && !nextSibling) {
  1862. el.appendChild(dragEl);
  1863. } else {
  1864. target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
  1865. }
  1866.  
  1867. // Undo chrome's scroll adjustment (has no effect on other browsers)
  1868. if (scrolledPastTop) {
  1869. scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop);
  1870. }
  1871. parentEl = dragEl.parentNode; // actualization
  1872.  
  1873. // must be done before animation
  1874. if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) {
  1875. targetMoveDistance = Math.abs(targetBeforeFirstSwap - getRect(target)[side1]);
  1876. }
  1877. changed();
  1878. return completed(true);
  1879. }
  1880. }
  1881. if (el.contains(dragEl)) {
  1882. return completed(false);
  1883. }
  1884. }
  1885. return false;
  1886. },
  1887. _ignoreWhileAnimating: null,
  1888. _offMoveEvents: function _offMoveEvents() {
  1889. off(document, 'mousemove', this._onTouchMove);
  1890. off(document, 'touchmove', this._onTouchMove);
  1891. off(document, 'pointermove', this._onTouchMove);
  1892. off(document, 'dragover', nearestEmptyInsertDetectEvent);
  1893. off(document, 'mousemove', nearestEmptyInsertDetectEvent);
  1894. off(document, 'touchmove', nearestEmptyInsertDetectEvent);
  1895. },
  1896. _offUpEvents: function _offUpEvents() {
  1897. var ownerDocument = this.el.ownerDocument;
  1898. off(ownerDocument, 'mouseup', this._onDrop);
  1899. off(ownerDocument, 'touchend', this._onDrop);
  1900. off(ownerDocument, 'pointerup', this._onDrop);
  1901. off(ownerDocument, 'touchcancel', this._onDrop);
  1902. off(document, 'selectstart', this);
  1903. },
  1904. _onDrop: function _onDrop( /**Event*/evt) {
  1905. var el = this.el,
  1906. options = this.options;
  1907.  
  1908. // Get the index of the dragged element within its parent
  1909. newIndex = index(dragEl);
  1910. newDraggableIndex = index(dragEl, options.draggable);
  1911. pluginEvent('drop', this, {
  1912. evt: evt
  1913. });
  1914. parentEl = dragEl && dragEl.parentNode;
  1915.  
  1916. // Get again after plugin event
  1917. newIndex = index(dragEl);
  1918. newDraggableIndex = index(dragEl, options.draggable);
  1919. if (Sortable.eventCanceled) {
  1920. this._nulling();
  1921. return;
  1922. }
  1923. awaitingDragStarted = false;
  1924. isCircumstantialInvert = false;
  1925. pastFirstInvertThresh = false;
  1926. clearInterval(this._loopId);
  1927. clearTimeout(this._dragStartTimer);
  1928. _cancelNextTick(this.cloneId);
  1929. _cancelNextTick(this._dragStartId);
  1930.  
  1931. // Unbind events
  1932. if (this.nativeDraggable) {
  1933. off(document, 'drop', this);
  1934. off(el, 'dragstart', this._onDragStart);
  1935. }
  1936. this._offMoveEvents();
  1937. this._offUpEvents();
  1938. if (Safari) {
  1939. css(document.body, 'user-select', '');
  1940. }
  1941. css(dragEl, 'transform', '');
  1942. if (evt) {
  1943. if (moved) {
  1944. evt.cancelable && evt.preventDefault();
  1945. !options.dropBubble && evt.stopPropagation();
  1946. }
  1947. ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);
  1948. if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {
  1949. // Remove clone(s)
  1950. cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);
  1951. }
  1952. if (dragEl) {
  1953. if (this.nativeDraggable) {
  1954. off(dragEl, 'dragend', this);
  1955. }
  1956. _disableDraggable(dragEl);
  1957. dragEl.style['will-change'] = '';
  1958.  
  1959. // Remove classes
  1960. // ghostClass is added in dragStarted
  1961. if (moved && !awaitingDragStarted) {
  1962. toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false);
  1963. }
  1964. toggleClass(dragEl, this.options.chosenClass, false);
  1965.  
  1966. // Drag stop event
  1967. _dispatchEvent({
  1968. sortable: this,
  1969. name: 'unchoose',
  1970. toEl: parentEl,
  1971. newIndex: null,
  1972. newDraggableIndex: null,
  1973. originalEvent: evt
  1974. });
  1975. if (rootEl !== parentEl) {
  1976. if (newIndex >= 0) {
  1977. // Add event
  1978. _dispatchEvent({
  1979. rootEl: parentEl,
  1980. name: 'add',
  1981. toEl: parentEl,
  1982. fromEl: rootEl,
  1983. originalEvent: evt
  1984. });
  1985.  
  1986. // Remove event
  1987. _dispatchEvent({
  1988. sortable: this,
  1989. name: 'remove',
  1990. toEl: parentEl,
  1991. originalEvent: evt
  1992. });
  1993.  
  1994. // drag from one list and drop into another
  1995. _dispatchEvent({
  1996. rootEl: parentEl,
  1997. name: 'sort',
  1998. toEl: parentEl,
  1999. fromEl: rootEl,
  2000. originalEvent: evt
  2001. });
  2002. _dispatchEvent({
  2003. sortable: this,
  2004. name: 'sort',
  2005. toEl: parentEl,
  2006. originalEvent: evt
  2007. });
  2008. }
  2009. putSortable && putSortable.save();
  2010. } else {
  2011. if (newIndex !== oldIndex) {
  2012. if (newIndex >= 0) {
  2013. // drag & drop within the same list
  2014. _dispatchEvent({
  2015. sortable: this,
  2016. name: 'update',
  2017. toEl: parentEl,
  2018. originalEvent: evt
  2019. });
  2020. _dispatchEvent({
  2021. sortable: this,
  2022. name: 'sort',
  2023. toEl: parentEl,
  2024. originalEvent: evt
  2025. });
  2026. }
  2027. }
  2028. }
  2029. if (Sortable.active) {
  2030. /* jshint eqnull:true */
  2031. if (newIndex == null || newIndex === -1) {
  2032. newIndex = oldIndex;
  2033. newDraggableIndex = oldDraggableIndex;
  2034. }
  2035. _dispatchEvent({
  2036. sortable: this,
  2037. name: 'end',
  2038. toEl: parentEl,
  2039. originalEvent: evt
  2040. });
  2041.  
  2042. // Save sorting
  2043. this.save();
  2044. }
  2045. }
  2046. }
  2047. this._nulling();
  2048. },
  2049. _nulling: function _nulling() {
  2050. pluginEvent('nulling', this);
  2051. rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = cloneHidden = tapEvt = touchEvt = moved = newIndex = newDraggableIndex = oldIndex = oldDraggableIndex = lastTarget = lastDirection = putSortable = activeGroup = Sortable.dragged = Sortable.ghost = Sortable.clone = Sortable.active = null;
  2052. savedInputChecked.forEach(function (el) {
  2053. el.checked = true;
  2054. });
  2055. savedInputChecked.length = lastDx = lastDy = 0;
  2056. },
  2057. handleEvent: function handleEvent( /**Event*/evt) {
  2058. switch (evt.type) {
  2059. case 'drop':
  2060. case 'dragend':
  2061. this._onDrop(evt);
  2062. break;
  2063. case 'dragenter':
  2064. case 'dragover':
  2065. if (dragEl) {
  2066. this._onDragOver(evt);
  2067. _globalDragOver(evt);
  2068. }
  2069. break;
  2070. case 'selectstart':
  2071. evt.preventDefault();
  2072. break;
  2073. }
  2074. },
  2075. /**
  2076. * Serializes the item into an array of string.
  2077. * @returns {String[]}
  2078. */
  2079. toArray: function toArray() {
  2080. var order = [],
  2081. el,
  2082. children = this.el.children,
  2083. i = 0,
  2084. n = children.length,
  2085. options = this.options;
  2086. for (; i < n; i++) {
  2087. el = children[i];
  2088. if (closest(el, options.draggable, this.el, false)) {
  2089. order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
  2090. }
  2091. }
  2092. return order;
  2093. },
  2094. /**
  2095. * Sorts the elements according to the array.
  2096. * @param {String[]} order order of the items
  2097. */
  2098. sort: function sort(order, useAnimation) {
  2099. var items = {},
  2100. rootEl = this.el;
  2101. this.toArray().forEach(function (id, i) {
  2102. var el = rootEl.children[i];
  2103. if (closest(el, this.options.draggable, rootEl, false)) {
  2104. items[id] = el;
  2105. }
  2106. }, this);
  2107. useAnimation && this.captureAnimationState();
  2108. order.forEach(function (id) {
  2109. if (items[id]) {
  2110. rootEl.removeChild(items[id]);
  2111. rootEl.appendChild(items[id]);
  2112. }
  2113. });
  2114. useAnimation && this.animateAll();
  2115. },
  2116. /**
  2117. * Save the current sorting
  2118. */
  2119. save: function save() {
  2120. var store = this.options.store;
  2121. store && store.set && store.set(this);
  2122. },
  2123. /**
  2124. * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
  2125. * @param {HTMLElement} el
  2126. * @param {String} [selector] default: `options.draggable`
  2127. * @returns {HTMLElement|null}
  2128. */
  2129. closest: function closest$1(el, selector) {
  2130. return closest(el, selector || this.options.draggable, this.el, false);
  2131. },
  2132. /**
  2133. * Set/get option
  2134. * @param {string} name
  2135. * @param {*} [value]
  2136. * @returns {*}
  2137. */
  2138. option: function option(name, value) {
  2139. var options = this.options;
  2140. if (value === void 0) {
  2141. return options[name];
  2142. } else {
  2143. var modifiedValue = PluginManager.modifyOption(this, name, value);
  2144. if (typeof modifiedValue !== 'undefined') {
  2145. options[name] = modifiedValue;
  2146. } else {
  2147. options[name] = value;
  2148. }
  2149. if (name === 'group') {
  2150. _prepareGroup(options);
  2151. }
  2152. }
  2153. },
  2154. /**
  2155. * Destroy
  2156. */
  2157. destroy: function destroy() {
  2158. pluginEvent('destroy', this);
  2159. var el = this.el;
  2160. el[expando] = null;
  2161. off(el, 'mousedown', this._onTapStart);
  2162. off(el, 'touchstart', this._onTapStart);
  2163. off(el, 'pointerdown', this._onTapStart);
  2164. if (this.nativeDraggable) {
  2165. off(el, 'dragover', this);
  2166. off(el, 'dragenter', this);
  2167. }
  2168. // Remove draggable attributes
  2169. Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
  2170. el.removeAttribute('draggable');
  2171. });
  2172. this._onDrop();
  2173. this._disableDelayedDragEvents();
  2174. sortables.splice(sortables.indexOf(this.el), 1);
  2175. this.el = el = null;
  2176. },
  2177. _hideClone: function _hideClone() {
  2178. if (!cloneHidden) {
  2179. pluginEvent('hideClone', this);
  2180. if (Sortable.eventCanceled) return;
  2181. css(cloneEl, 'display', 'none');
  2182. if (this.options.removeCloneOnHide && cloneEl.parentNode) {
  2183. cloneEl.parentNode.removeChild(cloneEl);
  2184. }
  2185. cloneHidden = true;
  2186. }
  2187. },
  2188. _showClone: function _showClone(putSortable) {
  2189. if (putSortable.lastPutMode !== 'clone') {
  2190. this._hideClone();
  2191. return;
  2192. }
  2193. if (cloneHidden) {
  2194. pluginEvent('showClone', this);
  2195. if (Sortable.eventCanceled) return;
  2196.  
  2197. // show clone at dragEl or original position
  2198. if (dragEl.parentNode == rootEl && !this.options.group.revertClone) {
  2199. rootEl.insertBefore(cloneEl, dragEl);
  2200. } else if (nextEl) {
  2201. rootEl.insertBefore(cloneEl, nextEl);
  2202. } else {
  2203. rootEl.appendChild(cloneEl);
  2204. }
  2205. if (this.options.group.revertClone) {
  2206. this.animate(dragEl, cloneEl);
  2207. }
  2208. css(cloneEl, 'display', '');
  2209. cloneHidden = false;
  2210. }
  2211. }
  2212. };
  2213. function _globalDragOver( /**Event*/evt) {
  2214. if (evt.dataTransfer) {
  2215. evt.dataTransfer.dropEffect = 'move';
  2216. }
  2217. evt.cancelable && evt.preventDefault();
  2218. }
  2219. function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvent, willInsertAfter) {
  2220. var evt,
  2221. sortable = fromEl[expando],
  2222. onMoveFn = sortable.options.onMove,
  2223. retVal;
  2224. // Support for new CustomEvent feature
  2225. if (window.CustomEvent && !IE11OrLess && !Edge) {
  2226. evt = new CustomEvent('move', {
  2227. bubbles: true,
  2228. cancelable: true
  2229. });
  2230. } else {
  2231. evt = document.createEvent('Event');
  2232. evt.initEvent('move', true, true);
  2233. }
  2234. evt.to = toEl;
  2235. evt.from = fromEl;
  2236. evt.dragged = dragEl;
  2237. evt.draggedRect = dragRect;
  2238. evt.related = targetEl || toEl;
  2239. evt.relatedRect = targetRect || getRect(toEl);
  2240. evt.willInsertAfter = willInsertAfter;
  2241. evt.originalEvent = originalEvent;
  2242. fromEl.dispatchEvent(evt);
  2243. if (onMoveFn) {
  2244. retVal = onMoveFn.call(sortable, evt, originalEvent);
  2245. }
  2246. return retVal;
  2247. }
  2248. function _disableDraggable(el) {
  2249. el.draggable = false;
  2250. }
  2251. function _unsilent() {
  2252. _silent = false;
  2253. }
  2254. function _ghostIsFirst(evt, vertical, sortable) {
  2255. var firstElRect = getRect(getChild(sortable.el, 0, sortable.options, true));
  2256. var sortableContentRect = getContentRect(sortable.el);
  2257. var spacer = 10;
  2258. return vertical ? evt.clientX < sortableContentRect.left - spacer || evt.clientY < firstElRect.top && evt.clientX < firstElRect.right : evt.clientY < sortableContentRect.top - spacer || evt.clientY < firstElRect.bottom && evt.clientX < firstElRect.left;
  2259. }
  2260. function _ghostIsLast(evt, vertical, sortable) {
  2261. var lastElRect = getRect(lastChild(sortable.el, sortable.options.draggable));
  2262. var sortableContentRect = getContentRect(sortable.el);
  2263. var spacer = 10;
  2264. return vertical ? evt.clientX > sortableContentRect.right + spacer || evt.clientY > lastElRect.bottom && evt.clientX > lastElRect.left : evt.clientY > sortableContentRect.bottom + spacer || evt.clientX > lastElRect.right && evt.clientY > lastElRect.top;
  2265. }
  2266. function _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) {
  2267. var mouseOnAxis = vertical ? evt.clientY : evt.clientX,
  2268. targetLength = vertical ? targetRect.height : targetRect.width,
  2269. targetS1 = vertical ? targetRect.top : targetRect.left,
  2270. targetS2 = vertical ? targetRect.bottom : targetRect.right,
  2271. invert = false;
  2272. if (!invertSwap) {
  2273. // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold
  2274. if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) {
  2275. // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2
  2276. // check if past first invert threshold on side opposite of lastDirection
  2277. if (!pastFirstInvertThresh && (lastDirection === 1 ? mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 : mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2)) {
  2278. // past first invert threshold, do not restrict inverted threshold to dragEl shadow
  2279. pastFirstInvertThresh = true;
  2280. }
  2281. if (!pastFirstInvertThresh) {
  2282. // dragEl shadow (target move distance shadow)
  2283. if (lastDirection === 1 ? mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow
  2284. : mouseOnAxis > targetS2 - targetMoveDistance) {
  2285. return -lastDirection;
  2286. }
  2287. } else {
  2288. invert = true;
  2289. }
  2290. } else {
  2291. // Regular
  2292. if (mouseOnAxis > targetS1 + targetLength * (1 - swapThreshold) / 2 && mouseOnAxis < targetS2 - targetLength * (1 - swapThreshold) / 2) {
  2293. return _getInsertDirection(target);
  2294. }
  2295. }
  2296. }
  2297. invert = invert || invertSwap;
  2298. if (invert) {
  2299. // Invert of regular
  2300. if (mouseOnAxis < targetS1 + targetLength * invertedSwapThreshold / 2 || mouseOnAxis > targetS2 - targetLength * invertedSwapThreshold / 2) {
  2301. return mouseOnAxis > targetS1 + targetLength / 2 ? 1 : -1;
  2302. }
  2303. }
  2304. return 0;
  2305. }
  2306.  
  2307. /**
  2308. * Gets the direction dragEl must be swapped relative to target in order to make it
  2309. * seem that dragEl has been "inserted" into that element's position
  2310. * @param {HTMLElement} target The target whose position dragEl is being inserted at
  2311. * @return {Number} Direction dragEl must be swapped
  2312. */
  2313. function _getInsertDirection(target) {
  2314. if (index(dragEl) < index(target)) {
  2315. return 1;
  2316. } else {
  2317. return -1;
  2318. }
  2319. }
  2320.  
  2321. /**
  2322. * Generate id
  2323. * @param {HTMLElement} el
  2324. * @returns {String}
  2325. * @private
  2326. */
  2327. function _generateId(el) {
  2328. var str = el.tagName + el.className + el.src + el.href + el.textContent,
  2329. i = str.length,
  2330. sum = 0;
  2331. while (i--) {
  2332. sum += str.charCodeAt(i);
  2333. }
  2334. return sum.toString(36);
  2335. }
  2336. function _saveInputCheckedState(root) {
  2337. savedInputChecked.length = 0;
  2338. var inputs = root.getElementsByTagName('input');
  2339. var idx = inputs.length;
  2340. while (idx--) {
  2341. var el = inputs[idx];
  2342. el.checked && savedInputChecked.push(el);
  2343. }
  2344. }
  2345. function _nextTick(fn) {
  2346. return setTimeout(fn, 0);
  2347. }
  2348. function _cancelNextTick(id) {
  2349. return clearTimeout(id);
  2350. }
  2351.  
  2352. // Fixed #973:
  2353. if (documentExists) {
  2354. on(document, 'touchmove', function (evt) {
  2355. if ((Sortable.active || awaitingDragStarted) && evt.cancelable) {
  2356. evt.preventDefault();
  2357. }
  2358. });
  2359. }
  2360.  
  2361. // Export utils
  2362. Sortable.utils = {
  2363. on: on,
  2364. off: off,
  2365. css: css,
  2366. find: find,
  2367. is: function is(el, selector) {
  2368. return !!closest(el, selector, el, false);
  2369. },
  2370. extend: extend,
  2371. throttle: throttle,
  2372. closest: closest,
  2373. toggleClass: toggleClass,
  2374. clone: clone,
  2375. index: index,
  2376. nextTick: _nextTick,
  2377. cancelNextTick: _cancelNextTick,
  2378. detectDirection: _detectDirection,
  2379. getChild: getChild
  2380. };
  2381.  
  2382. /**
  2383. * Get the Sortable instance of an element
  2384. * @param {HTMLElement} element The element
  2385. * @return {Sortable|undefined} The instance of Sortable
  2386. */
  2387. Sortable.get = function (element) {
  2388. return element[expando];
  2389. };
  2390.  
  2391. /**
  2392. * Mount a plugin to Sortable
  2393. * @param {...SortablePlugin|SortablePlugin[]} plugins Plugins being mounted
  2394. */
  2395. Sortable.mount = function () {
  2396. for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {
  2397. plugins[_key] = arguments[_key];
  2398. }
  2399. if (plugins[0].constructor === Array) plugins = plugins[0];
  2400. plugins.forEach(function (plugin) {
  2401. if (!plugin.prototype || !plugin.prototype.constructor) {
  2402. throw "Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(plugin));
  2403. }
  2404. if (plugin.utils) Sortable.utils = _objectSpread2(_objectSpread2({}, Sortable.utils), plugin.utils);
  2405. PluginManager.mount(plugin);
  2406. });
  2407. };
  2408.  
  2409. /**
  2410. * Create sortable instance
  2411. * @param {HTMLElement} el
  2412. * @param {Object} [options]
  2413. */
  2414. Sortable.create = function (el, options) {
  2415. return new Sortable(el, options);
  2416. };
  2417.  
  2418. // Export
  2419. Sortable.version = version;
  2420.  
  2421. var autoScrolls = [],
  2422. scrollEl,
  2423. scrollRootEl,
  2424. scrolling = false,
  2425. lastAutoScrollX,
  2426. lastAutoScrollY,
  2427. touchEvt$1,
  2428. pointerElemChangedInterval;
  2429. function AutoScrollPlugin() {
  2430. function AutoScroll() {
  2431. this.defaults = {
  2432. scroll: true,
  2433. forceAutoScrollFallback: false,
  2434. scrollSensitivity: 30,
  2435. scrollSpeed: 10,
  2436. bubbleScroll: true
  2437. };
  2438.  
  2439. // Bind all private methods
  2440. for (var fn in this) {
  2441. if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
  2442. this[fn] = this[fn].bind(this);
  2443. }
  2444. }
  2445. }
  2446. AutoScroll.prototype = {
  2447. dragStarted: function dragStarted(_ref) {
  2448. var originalEvent = _ref.originalEvent;
  2449. if (this.sortable.nativeDraggable) {
  2450. on(document, 'dragover', this._handleAutoScroll);
  2451. } else {
  2452. if (this.options.supportPointer) {
  2453. on(document, 'pointermove', this._handleFallbackAutoScroll);
  2454. } else if (originalEvent.touches) {
  2455. on(document, 'touchmove', this._handleFallbackAutoScroll);
  2456. } else {
  2457. on(document, 'mousemove', this._handleFallbackAutoScroll);
  2458. }
  2459. }
  2460. },
  2461. dragOverCompleted: function dragOverCompleted(_ref2) {
  2462. var originalEvent = _ref2.originalEvent;
  2463. // For when bubbling is canceled and using fallback (fallback 'touchmove' always reached)
  2464. if (!this.options.dragOverBubble && !originalEvent.rootEl) {
  2465. this._handleAutoScroll(originalEvent);
  2466. }
  2467. },
  2468. drop: function drop() {
  2469. if (this.sortable.nativeDraggable) {
  2470. off(document, 'dragover', this._handleAutoScroll);
  2471. } else {
  2472. off(document, 'pointermove', this._handleFallbackAutoScroll);
  2473. off(document, 'touchmove', this._handleFallbackAutoScroll);
  2474. off(document, 'mousemove', this._handleFallbackAutoScroll);
  2475. }
  2476. clearPointerElemChangedInterval();
  2477. clearAutoScrolls();
  2478. cancelThrottle();
  2479. },
  2480. nulling: function nulling() {
  2481. touchEvt$1 = scrollRootEl = scrollEl = scrolling = pointerElemChangedInterval = lastAutoScrollX = lastAutoScrollY = null;
  2482. autoScrolls.length = 0;
  2483. },
  2484. _handleFallbackAutoScroll: function _handleFallbackAutoScroll(evt) {
  2485. this._handleAutoScroll(evt, true);
  2486. },
  2487. _handleAutoScroll: function _handleAutoScroll(evt, fallback) {
  2488. var _this = this;
  2489. var x = (evt.touches ? evt.touches[0] : evt).clientX,
  2490. y = (evt.touches ? evt.touches[0] : evt).clientY,
  2491. elem = document.elementFromPoint(x, y);
  2492. touchEvt$1 = evt;
  2493.  
  2494. // IE does not seem to have native autoscroll,
  2495. // Edge's autoscroll seems too conditional,
  2496. // MACOS Safari does not have autoscroll,
  2497. // Firefox and Chrome are good
  2498. if (fallback || this.options.forceAutoScrollFallback || Edge || IE11OrLess || Safari) {
  2499. autoScroll(evt, this.options, elem, fallback);
  2500.  
  2501. // Listener for pointer element change
  2502. var ogElemScroller = getParentAutoScrollElement(elem, true);
  2503. if (scrolling && (!pointerElemChangedInterval || x !== lastAutoScrollX || y !== lastAutoScrollY)) {
  2504. pointerElemChangedInterval && clearPointerElemChangedInterval();
  2505. // Detect for pointer elem change, emulating native DnD behaviour
  2506. pointerElemChangedInterval = setInterval(function () {
  2507. var newElem = getParentAutoScrollElement(document.elementFromPoint(x, y), true);
  2508. if (newElem !== ogElemScroller) {
  2509. ogElemScroller = newElem;
  2510. clearAutoScrolls();
  2511. }
  2512. autoScroll(evt, _this.options, newElem, fallback);
  2513. }, 10);
  2514. lastAutoScrollX = x;
  2515. lastAutoScrollY = y;
  2516. }
  2517. } else {
  2518. // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll
  2519. if (!this.options.bubbleScroll || getParentAutoScrollElement(elem, true) === getWindowScrollingElement()) {
  2520. clearAutoScrolls();
  2521. return;
  2522. }
  2523. autoScroll(evt, this.options, getParentAutoScrollElement(elem, false), false);
  2524. }
  2525. }
  2526. };
  2527. return _extends(AutoScroll, {
  2528. pluginName: 'scroll',
  2529. initializeByDefault: true
  2530. });
  2531. }
  2532. function clearAutoScrolls() {
  2533. autoScrolls.forEach(function (autoScroll) {
  2534. clearInterval(autoScroll.pid);
  2535. });
  2536. autoScrolls = [];
  2537. }
  2538. function clearPointerElemChangedInterval() {
  2539. clearInterval(pointerElemChangedInterval);
  2540. }
  2541. var autoScroll = throttle(function (evt, options, rootEl, isFallback) {
  2542. // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
  2543. if (!options.scroll) return;
  2544. var x = (evt.touches ? evt.touches[0] : evt).clientX,
  2545. y = (evt.touches ? evt.touches[0] : evt).clientY,
  2546. sens = options.scrollSensitivity,
  2547. speed = options.scrollSpeed,
  2548. winScroller = getWindowScrollingElement();
  2549. var scrollThisInstance = false,
  2550. scrollCustomFn;
  2551.  
  2552. // New scroll root, set scrollEl
  2553. if (scrollRootEl !== rootEl) {
  2554. scrollRootEl = rootEl;
  2555. clearAutoScrolls();
  2556. scrollEl = options.scroll;
  2557. scrollCustomFn = options.scrollFn;
  2558. if (scrollEl === true) {
  2559. scrollEl = getParentAutoScrollElement(rootEl, true);
  2560. }
  2561. }
  2562. var layersOut = 0;
  2563. var currentParent = scrollEl;
  2564. do {
  2565. var el = currentParent,
  2566. rect = getRect(el),
  2567. top = rect.top,
  2568. bottom = rect.bottom,
  2569. left = rect.left,
  2570. right = rect.right,
  2571. width = rect.width,
  2572. height = rect.height,
  2573. canScrollX = void 0,
  2574. canScrollY = void 0,
  2575. scrollWidth = el.scrollWidth,
  2576. scrollHeight = el.scrollHeight,
  2577. elCSS = css(el),
  2578. scrollPosX = el.scrollLeft,
  2579. scrollPosY = el.scrollTop;
  2580. if (el === winScroller) {
  2581. canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll' || elCSS.overflowX === 'visible');
  2582. canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll' || elCSS.overflowY === 'visible');
  2583. } else {
  2584. canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll');
  2585. canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll');
  2586. }
  2587. var vx = canScrollX && (Math.abs(right - x) <= sens && scrollPosX + width < scrollWidth) - (Math.abs(left - x) <= sens && !!scrollPosX);
  2588. var vy = canScrollY && (Math.abs(bottom - y) <= sens && scrollPosY + height < scrollHeight) - (Math.abs(top - y) <= sens && !!scrollPosY);
  2589. if (!autoScrolls[layersOut]) {
  2590. for (var i = 0; i <= layersOut; i++) {
  2591. if (!autoScrolls[i]) {
  2592. autoScrolls[i] = {};
  2593. }
  2594. }
  2595. }
  2596. if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) {
  2597. autoScrolls[layersOut].el = el;
  2598. autoScrolls[layersOut].vx = vx;
  2599. autoScrolls[layersOut].vy = vy;
  2600. clearInterval(autoScrolls[layersOut].pid);
  2601. if (vx != 0 || vy != 0) {
  2602. scrollThisInstance = true;
  2603. /* jshint loopfunc:true */
  2604. autoScrolls[layersOut].pid = setInterval(function () {
  2605. // emulate drag over during autoscroll (fallback), emulating native DnD behaviour
  2606. if (isFallback && this.layer === 0) {
  2607. Sortable.active._onTouchMove(touchEvt$1); // To move ghost if it is positioned absolutely
  2608. }
  2609. var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0;
  2610. var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0;
  2611. if (typeof scrollCustomFn === 'function') {
  2612. if (scrollCustomFn.call(Sortable.dragged.parentNode[expando], scrollOffsetX, scrollOffsetY, evt, touchEvt$1, autoScrolls[this.layer].el) !== 'continue') {
  2613. return;
  2614. }
  2615. }
  2616. scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY);
  2617. }.bind({
  2618. layer: layersOut
  2619. }), 24);
  2620. }
  2621. }
  2622. layersOut++;
  2623. } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = getParentAutoScrollElement(currentParent, false)));
  2624. scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not
  2625. }, 30);
  2626.  
  2627. var drop = function drop(_ref) {
  2628. var originalEvent = _ref.originalEvent,
  2629. putSortable = _ref.putSortable,
  2630. dragEl = _ref.dragEl,
  2631. activeSortable = _ref.activeSortable,
  2632. dispatchSortableEvent = _ref.dispatchSortableEvent,
  2633. hideGhostForTarget = _ref.hideGhostForTarget,
  2634. unhideGhostForTarget = _ref.unhideGhostForTarget;
  2635. if (!originalEvent) return;
  2636. var toSortable = putSortable || activeSortable;
  2637. hideGhostForTarget();
  2638. var touch = originalEvent.changedTouches && originalEvent.changedTouches.length ? originalEvent.changedTouches[0] : originalEvent;
  2639. var target = document.elementFromPoint(touch.clientX, touch.clientY);
  2640. unhideGhostForTarget();
  2641. if (toSortable && !toSortable.el.contains(target)) {
  2642. dispatchSortableEvent('spill');
  2643. this.onSpill({
  2644. dragEl: dragEl,
  2645. putSortable: putSortable
  2646. });
  2647. }
  2648. };
  2649. function Revert() {}
  2650. Revert.prototype = {
  2651. startIndex: null,
  2652. dragStart: function dragStart(_ref2) {
  2653. var oldDraggableIndex = _ref2.oldDraggableIndex;
  2654. this.startIndex = oldDraggableIndex;
  2655. },
  2656. onSpill: function onSpill(_ref3) {
  2657. var dragEl = _ref3.dragEl,
  2658. putSortable = _ref3.putSortable;
  2659. this.sortable.captureAnimationState();
  2660. if (putSortable) {
  2661. putSortable.captureAnimationState();
  2662. }
  2663. var nextSibling = getChild(this.sortable.el, this.startIndex, this.options);
  2664. if (nextSibling) {
  2665. this.sortable.el.insertBefore(dragEl, nextSibling);
  2666. } else {
  2667. this.sortable.el.appendChild(dragEl);
  2668. }
  2669. this.sortable.animateAll();
  2670. if (putSortable) {
  2671. putSortable.animateAll();
  2672. }
  2673. },
  2674. drop: drop
  2675. };
  2676. _extends(Revert, {
  2677. pluginName: 'revertOnSpill'
  2678. });
  2679. function Remove() {}
  2680. Remove.prototype = {
  2681. onSpill: function onSpill(_ref4) {
  2682. var dragEl = _ref4.dragEl,
  2683. putSortable = _ref4.putSortable;
  2684. var parentSortable = putSortable || this.sortable;
  2685. parentSortable.captureAnimationState();
  2686. dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);
  2687. parentSortable.animateAll();
  2688. },
  2689. drop: drop
  2690. };
  2691. _extends(Remove, {
  2692. pluginName: 'removeOnSpill'
  2693. });
  2694.  
  2695. var lastSwapEl;
  2696. function SwapPlugin() {
  2697. function Swap() {
  2698. this.defaults = {
  2699. swapClass: 'sortable-swap-highlight'
  2700. };
  2701. }
  2702. Swap.prototype = {
  2703. dragStart: function dragStart(_ref) {
  2704. var dragEl = _ref.dragEl;
  2705. lastSwapEl = dragEl;
  2706. },
  2707. dragOverValid: function dragOverValid(_ref2) {
  2708. var completed = _ref2.completed,
  2709. target = _ref2.target,
  2710. onMove = _ref2.onMove,
  2711. activeSortable = _ref2.activeSortable,
  2712. changed = _ref2.changed,
  2713. cancel = _ref2.cancel;
  2714. if (!activeSortable.options.swap) return;
  2715. var el = this.sortable.el,
  2716. options = this.options;
  2717. if (target && target !== el) {
  2718. var prevSwapEl = lastSwapEl;
  2719. if (onMove(target) !== false) {
  2720. toggleClass(target, options.swapClass, true);
  2721. lastSwapEl = target;
  2722. } else {
  2723. lastSwapEl = null;
  2724. }
  2725. if (prevSwapEl && prevSwapEl !== lastSwapEl) {
  2726. toggleClass(prevSwapEl, options.swapClass, false);
  2727. }
  2728. }
  2729. changed();
  2730. completed(true);
  2731. cancel();
  2732. },
  2733. drop: function drop(_ref3) {
  2734. var activeSortable = _ref3.activeSortable,
  2735. putSortable = _ref3.putSortable,
  2736. dragEl = _ref3.dragEl;
  2737. var toSortable = putSortable || this.sortable;
  2738. var options = this.options;
  2739. lastSwapEl && toggleClass(lastSwapEl, options.swapClass, false);
  2740. if (lastSwapEl && (options.swap || putSortable && putSortable.options.swap)) {
  2741. if (dragEl !== lastSwapEl) {
  2742. toSortable.captureAnimationState();
  2743. if (toSortable !== activeSortable) activeSortable.captureAnimationState();
  2744. swapNodes(dragEl, lastSwapEl);
  2745. toSortable.animateAll();
  2746. if (toSortable !== activeSortable) activeSortable.animateAll();
  2747. }
  2748. }
  2749. },
  2750. nulling: function nulling() {
  2751. lastSwapEl = null;
  2752. }
  2753. };
  2754. return _extends(Swap, {
  2755. pluginName: 'swap',
  2756. eventProperties: function eventProperties() {
  2757. return {
  2758. swapItem: lastSwapEl
  2759. };
  2760. }
  2761. });
  2762. }
  2763. function swapNodes(n1, n2) {
  2764. var p1 = n1.parentNode,
  2765. p2 = n2.parentNode,
  2766. i1,
  2767. i2;
  2768. if (!p1 || !p2 || p1.isEqualNode(n2) || p2.isEqualNode(n1)) return;
  2769. i1 = index(n1);
  2770. i2 = index(n2);
  2771. if (p1.isEqualNode(p2) && i1 < i2) {
  2772. i2++;
  2773. }
  2774. p1.insertBefore(n2, p1.children[i1]);
  2775. p2.insertBefore(n1, p2.children[i2]);
  2776. }
  2777.  
  2778. var multiDragElements = [],
  2779. multiDragClones = [],
  2780. lastMultiDragSelect,
  2781. // for selection with modifier key down (SHIFT)
  2782. multiDragSortable,
  2783. initialFolding = false,
  2784. // Initial multi-drag fold when drag started
  2785. folding = false,
  2786. // Folding any other time
  2787. dragStarted = false,
  2788. dragEl$1,
  2789. clonesFromRect,
  2790. clonesHidden;
  2791. function MultiDragPlugin() {
  2792. function MultiDrag(sortable) {
  2793. // Bind all private methods
  2794. for (var fn in this) {
  2795. if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
  2796. this[fn] = this[fn].bind(this);
  2797. }
  2798. }
  2799. if (!sortable.options.avoidImplicitDeselect) {
  2800. if (sortable.options.supportPointer) {
  2801. on(document, 'pointerup', this._deselectMultiDrag);
  2802. } else {
  2803. on(document, 'mouseup', this._deselectMultiDrag);
  2804. on(document, 'touchend', this._deselectMultiDrag);
  2805. }
  2806. }
  2807. on(document, 'keydown', this._checkKeyDown);
  2808. on(document, 'keyup', this._checkKeyUp);
  2809. this.defaults = {
  2810. selectedClass: 'sortable-selected',
  2811. multiDragKey: null,
  2812. avoidImplicitDeselect: false,
  2813. setData: function setData(dataTransfer, dragEl) {
  2814. var data = '';
  2815. if (multiDragElements.length && multiDragSortable === sortable) {
  2816. multiDragElements.forEach(function (multiDragElement, i) {
  2817. data += (!i ? '' : ', ') + multiDragElement.textContent;
  2818. });
  2819. } else {
  2820. data = dragEl.textContent;
  2821. }
  2822. dataTransfer.setData('Text', data);
  2823. }
  2824. };
  2825. }
  2826. MultiDrag.prototype = {
  2827. multiDragKeyDown: false,
  2828. isMultiDrag: false,
  2829. delayStartGlobal: function delayStartGlobal(_ref) {
  2830. var dragged = _ref.dragEl;
  2831. dragEl$1 = dragged;
  2832. },
  2833. delayEnded: function delayEnded() {
  2834. this.isMultiDrag = ~multiDragElements.indexOf(dragEl$1);
  2835. },
  2836. setupClone: function setupClone(_ref2) {
  2837. var sortable = _ref2.sortable,
  2838. cancel = _ref2.cancel;
  2839. if (!this.isMultiDrag) return;
  2840. for (var i = 0; i < multiDragElements.length; i++) {
  2841. multiDragClones.push(clone(multiDragElements[i]));
  2842. multiDragClones[i].sortableIndex = multiDragElements[i].sortableIndex;
  2843. multiDragClones[i].draggable = false;
  2844. multiDragClones[i].style['will-change'] = '';
  2845. toggleClass(multiDragClones[i], this.options.selectedClass, false);
  2846. multiDragElements[i] === dragEl$1 && toggleClass(multiDragClones[i], this.options.chosenClass, false);
  2847. }
  2848. sortable._hideClone();
  2849. cancel();
  2850. },
  2851. clone: function clone(_ref3) {
  2852. var sortable = _ref3.sortable,
  2853. rootEl = _ref3.rootEl,
  2854. dispatchSortableEvent = _ref3.dispatchSortableEvent,
  2855. cancel = _ref3.cancel;
  2856. if (!this.isMultiDrag) return;
  2857. if (!this.options.removeCloneOnHide) {
  2858. if (multiDragElements.length && multiDragSortable === sortable) {
  2859. insertMultiDragClones(true, rootEl);
  2860. dispatchSortableEvent('clone');
  2861. cancel();
  2862. }
  2863. }
  2864. },
  2865. showClone: function showClone(_ref4) {
  2866. var cloneNowShown = _ref4.cloneNowShown,
  2867. rootEl = _ref4.rootEl,
  2868. cancel = _ref4.cancel;
  2869. if (!this.isMultiDrag) return;
  2870. insertMultiDragClones(false, rootEl);
  2871. multiDragClones.forEach(function (clone) {
  2872. css(clone, 'display', '');
  2873. });
  2874. cloneNowShown();
  2875. clonesHidden = false;
  2876. cancel();
  2877. },
  2878. hideClone: function hideClone(_ref5) {
  2879. var _this = this;
  2880. var sortable = _ref5.sortable,
  2881. cloneNowHidden = _ref5.cloneNowHidden,
  2882. cancel = _ref5.cancel;
  2883. if (!this.isMultiDrag) return;
  2884. multiDragClones.forEach(function (clone) {
  2885. css(clone, 'display', 'none');
  2886. if (_this.options.removeCloneOnHide && clone.parentNode) {
  2887. clone.parentNode.removeChild(clone);
  2888. }
  2889. });
  2890. cloneNowHidden();
  2891. clonesHidden = true;
  2892. cancel();
  2893. },
  2894. dragStartGlobal: function dragStartGlobal(_ref6) {
  2895. var sortable = _ref6.sortable;
  2896. if (!this.isMultiDrag && multiDragSortable) {
  2897. multiDragSortable.multiDrag._deselectMultiDrag();
  2898. }
  2899. multiDragElements.forEach(function (multiDragElement) {
  2900. multiDragElement.sortableIndex = index(multiDragElement);
  2901. });
  2902.  
  2903. // Sort multi-drag elements
  2904. multiDragElements = multiDragElements.sort(function (a, b) {
  2905. return a.sortableIndex - b.sortableIndex;
  2906. });
  2907. dragStarted = true;
  2908. },
  2909. dragStarted: function dragStarted(_ref7) {
  2910. var _this2 = this;
  2911. var sortable = _ref7.sortable;
  2912. if (!this.isMultiDrag) return;
  2913. if (this.options.sort) {
  2914. // Capture rects,
  2915. // hide multi drag elements (by positioning them absolute),
  2916. // set multi drag elements rects to dragRect,
  2917. // show multi drag elements,
  2918. // animate to rects,
  2919. // unset rects & remove from DOM
  2920.  
  2921. sortable.captureAnimationState();
  2922. if (this.options.animation) {
  2923. multiDragElements.forEach(function (multiDragElement) {
  2924. if (multiDragElement === dragEl$1) return;
  2925. css(multiDragElement, 'position', 'absolute');
  2926. });
  2927. var dragRect = getRect(dragEl$1, false, true, true);
  2928. multiDragElements.forEach(function (multiDragElement) {
  2929. if (multiDragElement === dragEl$1) return;
  2930. setRect(multiDragElement, dragRect);
  2931. });
  2932. folding = true;
  2933. initialFolding = true;
  2934. }
  2935. }
  2936. sortable.animateAll(function () {
  2937. folding = false;
  2938. initialFolding = false;
  2939. if (_this2.options.animation) {
  2940. multiDragElements.forEach(function (multiDragElement) {
  2941. unsetRect(multiDragElement);
  2942. });
  2943. }
  2944.  
  2945. // Remove all auxiliary multidrag items from el, if sorting enabled
  2946. if (_this2.options.sort) {
  2947. removeMultiDragElements();
  2948. }
  2949. });
  2950. },
  2951. dragOver: function dragOver(_ref8) {
  2952. var target = _ref8.target,
  2953. completed = _ref8.completed,
  2954. cancel = _ref8.cancel;
  2955. if (folding && ~multiDragElements.indexOf(target)) {
  2956. completed(false);
  2957. cancel();
  2958. }
  2959. },
  2960. revert: function revert(_ref9) {
  2961. var fromSortable = _ref9.fromSortable,
  2962. rootEl = _ref9.rootEl,
  2963. sortable = _ref9.sortable,
  2964. dragRect = _ref9.dragRect;
  2965. if (multiDragElements.length > 1) {
  2966. // Setup unfold animation
  2967. multiDragElements.forEach(function (multiDragElement) {
  2968. sortable.addAnimationState({
  2969. target: multiDragElement,
  2970. rect: folding ? getRect(multiDragElement) : dragRect
  2971. });
  2972. unsetRect(multiDragElement);
  2973. multiDragElement.fromRect = dragRect;
  2974. fromSortable.removeAnimationState(multiDragElement);
  2975. });
  2976. folding = false;
  2977. insertMultiDragElements(!this.options.removeCloneOnHide, rootEl);
  2978. }
  2979. },
  2980. dragOverCompleted: function dragOverCompleted(_ref10) {
  2981. var sortable = _ref10.sortable,
  2982. isOwner = _ref10.isOwner,
  2983. insertion = _ref10.insertion,
  2984. activeSortable = _ref10.activeSortable,
  2985. parentEl = _ref10.parentEl,
  2986. putSortable = _ref10.putSortable;
  2987. var options = this.options;
  2988. if (insertion) {
  2989. // Clones must be hidden before folding animation to capture dragRectAbsolute properly
  2990. if (isOwner) {
  2991. activeSortable._hideClone();
  2992. }
  2993. initialFolding = false;
  2994. // If leaving sort:false root, or already folding - Fold to new location
  2995. if (options.animation && multiDragElements.length > 1 && (folding || !isOwner && !activeSortable.options.sort && !putSortable)) {
  2996. // Fold: Set all multi drag elements's rects to dragEl's rect when multi-drag elements are invisible
  2997. var dragRectAbsolute = getRect(dragEl$1, false, true, true);
  2998. multiDragElements.forEach(function (multiDragElement) {
  2999. if (multiDragElement === dragEl$1) return;
  3000. setRect(multiDragElement, dragRectAbsolute);
  3001.  
  3002. // Move element(s) to end of parentEl so that it does not interfere with multi-drag clones insertion if they are inserted
  3003. // while folding, and so that we can capture them again because old sortable will no longer be fromSortable
  3004. parentEl.appendChild(multiDragElement);
  3005. });
  3006. folding = true;
  3007. }
  3008.  
  3009. // Clones must be shown (and check to remove multi drags) after folding when interfering multiDragElements are moved out
  3010. if (!isOwner) {
  3011. // Only remove if not folding (folding will remove them anyways)
  3012. if (!folding) {
  3013. removeMultiDragElements();
  3014. }
  3015. if (multiDragElements.length > 1) {
  3016. var clonesHiddenBefore = clonesHidden;
  3017. activeSortable._showClone(sortable);
  3018.  
  3019. // Unfold animation for clones if showing from hidden
  3020. if (activeSortable.options.animation && !clonesHidden && clonesHiddenBefore) {
  3021. multiDragClones.forEach(function (clone) {
  3022. activeSortable.addAnimationState({
  3023. target: clone,
  3024. rect: clonesFromRect
  3025. });
  3026. clone.fromRect = clonesFromRect;
  3027. clone.thisAnimationDuration = null;
  3028. });
  3029. }
  3030. } else {
  3031. activeSortable._showClone(sortable);
  3032. }
  3033. }
  3034. }
  3035. },
  3036. dragOverAnimationCapture: function dragOverAnimationCapture(_ref11) {
  3037. var dragRect = _ref11.dragRect,
  3038. isOwner = _ref11.isOwner,
  3039. activeSortable = _ref11.activeSortable;
  3040. multiDragElements.forEach(function (multiDragElement) {
  3041. multiDragElement.thisAnimationDuration = null;
  3042. });
  3043. if (activeSortable.options.animation && !isOwner && activeSortable.multiDrag.isMultiDrag) {
  3044. clonesFromRect = _extends({}, dragRect);
  3045. var dragMatrix = matrix(dragEl$1, true);
  3046. clonesFromRect.top -= dragMatrix.f;
  3047. clonesFromRect.left -= dragMatrix.e;
  3048. }
  3049. },
  3050. dragOverAnimationComplete: function dragOverAnimationComplete() {
  3051. if (folding) {
  3052. folding = false;
  3053. removeMultiDragElements();
  3054. }
  3055. },
  3056. drop: function drop(_ref12) {
  3057. var evt = _ref12.originalEvent,
  3058. rootEl = _ref12.rootEl,
  3059. parentEl = _ref12.parentEl,
  3060. sortable = _ref12.sortable,
  3061. dispatchSortableEvent = _ref12.dispatchSortableEvent,
  3062. oldIndex = _ref12.oldIndex,
  3063. putSortable = _ref12.putSortable;
  3064. var toSortable = putSortable || this.sortable;
  3065. if (!evt) return;
  3066. var options = this.options,
  3067. children = parentEl.children;
  3068.  
  3069. // Multi-drag selection
  3070. if (!dragStarted) {
  3071. if (options.multiDragKey && !this.multiDragKeyDown) {
  3072. this._deselectMultiDrag();
  3073. }
  3074. toggleClass(dragEl$1, options.selectedClass, !~multiDragElements.indexOf(dragEl$1));
  3075. if (!~multiDragElements.indexOf(dragEl$1)) {
  3076. multiDragElements.push(dragEl$1);
  3077. dispatchEvent({
  3078. sortable: sortable,
  3079. rootEl: rootEl,
  3080. name: 'select',
  3081. targetEl: dragEl$1,
  3082. originalEvent: evt
  3083. });
  3084.  
  3085. // Modifier activated, select from last to dragEl
  3086. if (evt.shiftKey && lastMultiDragSelect && sortable.el.contains(lastMultiDragSelect)) {
  3087. var lastIndex = index(lastMultiDragSelect),
  3088. currentIndex = index(dragEl$1);
  3089. if (~lastIndex && ~currentIndex && lastIndex !== currentIndex) {
  3090. // Must include lastMultiDragSelect (select it), in case modified selection from no selection
  3091. // (but previous selection existed)
  3092. var n, i;
  3093. if (currentIndex > lastIndex) {
  3094. i = lastIndex;
  3095. n = currentIndex;
  3096. } else {
  3097. i = currentIndex;
  3098. n = lastIndex + 1;
  3099. }
  3100. for (; i < n; i++) {
  3101. if (~multiDragElements.indexOf(children[i])) continue;
  3102. toggleClass(children[i], options.selectedClass, true);
  3103. multiDragElements.push(children[i]);
  3104. dispatchEvent({
  3105. sortable: sortable,
  3106. rootEl: rootEl,
  3107. name: 'select',
  3108. targetEl: children[i],
  3109. originalEvent: evt
  3110. });
  3111. }
  3112. }
  3113. } else {
  3114. lastMultiDragSelect = dragEl$1;
  3115. }
  3116. multiDragSortable = toSortable;
  3117. } else {
  3118. multiDragElements.splice(multiDragElements.indexOf(dragEl$1), 1);
  3119. lastMultiDragSelect = null;
  3120. dispatchEvent({
  3121. sortable: sortable,
  3122. rootEl: rootEl,
  3123. name: 'deselect',
  3124. targetEl: dragEl$1,
  3125. originalEvent: evt
  3126. });
  3127. }
  3128. }
  3129.  
  3130. // Multi-drag drop
  3131. if (dragStarted && this.isMultiDrag) {
  3132. folding = false;
  3133. // Do not "unfold" after around dragEl if reverted
  3134. if ((parentEl[expando].options.sort || parentEl !== rootEl) && multiDragElements.length > 1) {
  3135. var dragRect = getRect(dragEl$1),
  3136. multiDragIndex = index(dragEl$1, ':not(.' + this.options.selectedClass + ')');
  3137. if (!initialFolding && options.animation) dragEl$1.thisAnimationDuration = null;
  3138. toSortable.captureAnimationState();
  3139. if (!initialFolding) {
  3140. if (options.animation) {
  3141. dragEl$1.fromRect = dragRect;
  3142. multiDragElements.forEach(function (multiDragElement) {
  3143. multiDragElement.thisAnimationDuration = null;
  3144. if (multiDragElement !== dragEl$1) {
  3145. var rect = folding ? getRect(multiDragElement) : dragRect;
  3146. multiDragElement.fromRect = rect;
  3147.  
  3148. // Prepare unfold animation
  3149. toSortable.addAnimationState({
  3150. target: multiDragElement,
  3151. rect: rect
  3152. });
  3153. }
  3154. });
  3155. }
  3156.  
  3157. // Multi drag elements are not necessarily removed from the DOM on drop, so to reinsert
  3158. // properly they must all be removed
  3159. removeMultiDragElements();
  3160. multiDragElements.forEach(function (multiDragElement) {
  3161. if (children[multiDragIndex]) {
  3162. parentEl.insertBefore(multiDragElement, children[multiDragIndex]);
  3163. } else {
  3164. parentEl.appendChild(multiDragElement);
  3165. }
  3166. multiDragIndex++;
  3167. });
  3168.  
  3169. // If initial folding is done, the elements may have changed position because they are now
  3170. // unfolding around dragEl, even though dragEl may not have his index changed, so update event
  3171. // must be fired here as Sortable will not.
  3172. if (oldIndex === index(dragEl$1)) {
  3173. var update = false;
  3174. multiDragElements.forEach(function (multiDragElement) {
  3175. if (multiDragElement.sortableIndex !== index(multiDragElement)) {
  3176. update = true;
  3177. return;
  3178. }
  3179. });
  3180. if (update) {
  3181. dispatchSortableEvent('update');
  3182. dispatchSortableEvent('sort');
  3183. }
  3184. }
  3185. }
  3186.  
  3187. // Must be done after capturing individual rects (scroll bar)
  3188. multiDragElements.forEach(function (multiDragElement) {
  3189. unsetRect(multiDragElement);
  3190. });
  3191. toSortable.animateAll();
  3192. }
  3193. multiDragSortable = toSortable;
  3194. }
  3195.  
  3196. // Remove clones if necessary
  3197. if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {
  3198. multiDragClones.forEach(function (clone) {
  3199. clone.parentNode && clone.parentNode.removeChild(clone);
  3200. });
  3201. }
  3202. },
  3203. nullingGlobal: function nullingGlobal() {
  3204. this.isMultiDrag = dragStarted = false;
  3205. multiDragClones.length = 0;
  3206. },
  3207. destroyGlobal: function destroyGlobal() {
  3208. this._deselectMultiDrag();
  3209. off(document, 'pointerup', this._deselectMultiDrag);
  3210. off(document, 'mouseup', this._deselectMultiDrag);
  3211. off(document, 'touchend', this._deselectMultiDrag);
  3212. off(document, 'keydown', this._checkKeyDown);
  3213. off(document, 'keyup', this._checkKeyUp);
  3214. },
  3215. _deselectMultiDrag: function _deselectMultiDrag(evt) {
  3216. if (typeof dragStarted !== "undefined" && dragStarted) return;
  3217.  
  3218. // Only deselect if selection is in this sortable
  3219. if (multiDragSortable !== this.sortable) return;
  3220.  
  3221. // Only deselect if target is not item in this sortable
  3222. if (evt && closest(evt.target, this.options.draggable, this.sortable.el, false)) return;
  3223.  
  3224. // Only deselect if left click
  3225. if (evt && evt.button !== 0) return;
  3226. while (multiDragElements.length) {
  3227. var el = multiDragElements[0];
  3228. toggleClass(el, this.options.selectedClass, false);
  3229. multiDragElements.shift();
  3230. dispatchEvent({
  3231. sortable: this.sortable,
  3232. rootEl: this.sortable.el,
  3233. name: 'deselect',
  3234. targetEl: el,
  3235. originalEvent: evt
  3236. });
  3237. }
  3238. },
  3239. _checkKeyDown: function _checkKeyDown(evt) {
  3240. if (evt.key === this.options.multiDragKey) {
  3241. this.multiDragKeyDown = true;
  3242. }
  3243. },
  3244. _checkKeyUp: function _checkKeyUp(evt) {
  3245. if (evt.key === this.options.multiDragKey) {
  3246. this.multiDragKeyDown = false;
  3247. }
  3248. }
  3249. };
  3250. return _extends(MultiDrag, {
  3251. // Static methods & properties
  3252. pluginName: 'multiDrag',
  3253. utils: {
  3254. /**
  3255. * Selects the provided multi-drag item
  3256. * @param {HTMLElement} el The element to be selected
  3257. */
  3258. select: function select(el) {
  3259. var sortable = el.parentNode[expando];
  3260. if (!sortable || !sortable.options.multiDrag || ~multiDragElements.indexOf(el)) return;
  3261. if (multiDragSortable && multiDragSortable !== sortable) {
  3262. multiDragSortable.multiDrag._deselectMultiDrag();
  3263. multiDragSortable = sortable;
  3264. }
  3265. toggleClass(el, sortable.options.selectedClass, true);
  3266. multiDragElements.push(el);
  3267. },
  3268. /**
  3269. * Deselects the provided multi-drag item
  3270. * @param {HTMLElement} el The element to be deselected
  3271. */
  3272. deselect: function deselect(el) {
  3273. var sortable = el.parentNode[expando],
  3274. index = multiDragElements.indexOf(el);
  3275. if (!sortable || !sortable.options.multiDrag || !~index) return;
  3276. toggleClass(el, sortable.options.selectedClass, false);
  3277. multiDragElements.splice(index, 1);
  3278. }
  3279. },
  3280. eventProperties: function eventProperties() {
  3281. var _this3 = this;
  3282. var oldIndicies = [],
  3283. newIndicies = [];
  3284. multiDragElements.forEach(function (multiDragElement) {
  3285. oldIndicies.push({
  3286. multiDragElement: multiDragElement,
  3287. index: multiDragElement.sortableIndex
  3288. });
  3289.  
  3290. // multiDragElements will already be sorted if folding
  3291. var newIndex;
  3292. if (folding && multiDragElement !== dragEl$1) {
  3293. newIndex = -1;
  3294. } else if (folding) {
  3295. newIndex = index(multiDragElement, ':not(.' + _this3.options.selectedClass + ')');
  3296. } else {
  3297. newIndex = index(multiDragElement);
  3298. }
  3299. newIndicies.push({
  3300. multiDragElement: multiDragElement,
  3301. index: newIndex
  3302. });
  3303. });
  3304. return {
  3305. items: _toConsumableArray(multiDragElements),
  3306. clones: [].concat(multiDragClones),
  3307. oldIndicies: oldIndicies,
  3308. newIndicies: newIndicies
  3309. };
  3310. },
  3311. optionListeners: {
  3312. multiDragKey: function multiDragKey(key) {
  3313. key = key.toLowerCase();
  3314. if (key === 'ctrl') {
  3315. key = 'Control';
  3316. } else if (key.length > 1) {
  3317. key = key.charAt(0).toUpperCase() + key.substr(1);
  3318. }
  3319. return key;
  3320. }
  3321. }
  3322. });
  3323. }
  3324. function insertMultiDragElements(clonesInserted, rootEl) {
  3325. multiDragElements.forEach(function (multiDragElement, i) {
  3326. var target = rootEl.children[multiDragElement.sortableIndex + (clonesInserted ? Number(i) : 0)];
  3327. if (target) {
  3328. rootEl.insertBefore(multiDragElement, target);
  3329. } else {
  3330. rootEl.appendChild(multiDragElement);
  3331. }
  3332. });
  3333. }
  3334.  
  3335. /**
  3336. * Insert multi-drag clones
  3337. * @param {[Boolean]} elementsInserted Whether the multi-drag elements are inserted
  3338. * @param {HTMLElement} rootEl
  3339. */
  3340. function insertMultiDragClones(elementsInserted, rootEl) {
  3341. multiDragClones.forEach(function (clone, i) {
  3342. var target = rootEl.children[clone.sortableIndex + (elementsInserted ? Number(i) : 0)];
  3343. if (target) {
  3344. rootEl.insertBefore(clone, target);
  3345. } else {
  3346. rootEl.appendChild(clone);
  3347. }
  3348. });
  3349. }
  3350. function removeMultiDragElements() {
  3351. multiDragElements.forEach(function (multiDragElement) {
  3352. if (multiDragElement === dragEl$1) return;
  3353. multiDragElement.parentNode && multiDragElement.parentNode.removeChild(multiDragElement);
  3354. });
  3355. }
  3356.  
  3357. Sortable.mount(new AutoScrollPlugin());
  3358. Sortable.mount(Remove, Revert);
  3359.  
  3360. Sortable.mount(new SwapPlugin());
  3361. Sortable.mount(new MultiDragPlugin());
  3362.  
  3363. return Sortable;
  3364.  
  3365. })));

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址