sortable.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  1. /**!
  2. * Sortable
  3. * @author RubaXa <[email protected]>
  4. * @license MIT
  5. */
  6. (function (factory) {
  7. "use strict";
  8. if (typeof define === "function" && define.amd) {
  9. define(factory);
  10. }
  11. else if (typeof module != "undefined" && typeof module.exports != "undefined") {
  12. module.exports = factory();
  13. }
  14. else if (typeof Package !== "undefined") {
  15. Sortable = factory(); // export for Meteor.js
  16. }
  17. else {
  18. /* jshint sub:true */
  19. window["Sortable"] = factory();
  20. }
  21. })(function () {
  22. "use strict";
  23. if (typeof window === "undefined" || typeof window.document == "undefined") {
  24. return function() {
  25. throw new Error( "Sortable.js requires a window with a document" );
  26. }
  27. }
  28. var dragEl,
  29. parentEl,
  30. ghostEl,
  31. cloneEl,
  32. rootEl,
  33. nextEl,
  34. scrollEl,
  35. scrollParentEl,
  36. lastEl,
  37. lastCSS,
  38. lastParentCSS,
  39. oldIndex,
  40. newIndex,
  41. activeGroup,
  42. autoScroll = {},
  43. tapEvt,
  44. touchEvt,
  45. moved,
  46. /** @const */
  47. RSPACE = /\s+/g,
  48. expando = 'Sortable' + (new Date).getTime(),
  49. win = window,
  50. document = win.document,
  51. parseInt = win.parseInt,
  52. supportDraggable = !!('draggable' in document.createElement('div')),
  53. supportCssPointerEvents = (function (el) {
  54. el = document.createElement('x');
  55. el.style.cssText = 'pointer-events:auto';
  56. return el.style.pointerEvents === 'auto';
  57. })(),
  58. _silent = false,
  59. abs = Math.abs,
  60. slice = [].slice,
  61. touchDragOverListeners = [],
  62. _autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl) {
  63. // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
  64. if (rootEl && options.scroll) {
  65. var el,
  66. rect,
  67. sens = options.scrollSensitivity,
  68. speed = options.scrollSpeed,
  69. x = evt.clientX,
  70. y = evt.clientY,
  71. winWidth = window.innerWidth,
  72. winHeight = window.innerHeight,
  73. vx,
  74. vy
  75. ;
  76. // Delect scrollEl
  77. if (scrollParentEl !== rootEl) {
  78. scrollEl = options.scroll;
  79. scrollParentEl = rootEl;
  80. if (scrollEl === true) {
  81. scrollEl = rootEl;
  82. do {
  83. if ((scrollEl.offsetWidth < scrollEl.scrollWidth) ||
  84. (scrollEl.offsetHeight < scrollEl.scrollHeight)
  85. ) {
  86. break;
  87. }
  88. /* jshint boss:true */
  89. } while (scrollEl = scrollEl.parentNode);
  90. }
  91. }
  92. if (scrollEl) {
  93. el = scrollEl;
  94. rect = scrollEl.getBoundingClientRect();
  95. vx = (abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens);
  96. vy = (abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens);
  97. }
  98. if (!(vx || vy)) {
  99. vx = (winWidth - x <= sens) - (x <= sens);
  100. vy = (winHeight - y <= sens) - (y <= sens);
  101. /* jshint expr:true */
  102. (vx || vy) && (el = win);
  103. }
  104. if (autoScroll.vx !== vx || autoScroll.vy !== vy || autoScroll.el !== el) {
  105. autoScroll.el = el;
  106. autoScroll.vx = vx;
  107. autoScroll.vy = vy;
  108. clearInterval(autoScroll.pid);
  109. if (el) {
  110. autoScroll.pid = setInterval(function () {
  111. if (el === win) {
  112. win.scrollTo(win.pageXOffset + vx * speed, win.pageYOffset + vy * speed);
  113. } else {
  114. vy && (el.scrollTop += vy * speed);
  115. vx && (el.scrollLeft += vx * speed);
  116. }
  117. }, 24);
  118. }
  119. }
  120. }
  121. }, 30),
  122. _prepareGroup = function (options) {
  123. var group = options.group;
  124. if (!group || typeof group != 'object') {
  125. group = options.group = {name: group};
  126. }
  127. ['pull', 'put'].forEach(function (key) {
  128. if (!(key in group)) {
  129. group[key] = true;
  130. }
  131. });
  132. options.groups = ' ' + group.name + (group.put.join ? ' ' + group.put.join(' ') : '') + ' ';
  133. }
  134. ;
  135. /**
  136. * @class Sortable
  137. * @param {HTMLElement} el
  138. * @param {Object} [options]
  139. */
  140. function Sortable(el, options) {
  141. if (!(el && el.nodeType && el.nodeType === 1)) {
  142. throw 'Sortable: `el` must be HTMLElement, and not ' + {}.toString.call(el);
  143. }
  144. this.el = el; // root element
  145. this.options = options = _extend({}, options);
  146. // Export instance
  147. el[expando] = this;
  148. // Default options
  149. var defaults = {
  150. group: Math.random(),
  151. sort: true,
  152. disabled: false,
  153. store: null,
  154. handle: null,
  155. scroll: true,
  156. scrollSensitivity: 30,
  157. scrollSpeed: 10,
  158. draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*',
  159. ghostClass: 'sortable-ghost',
  160. chosenClass: 'sortable-chosen',
  161. ignore: 'a, img',
  162. filter: null,
  163. animation: 0,
  164. setData: function (dataTransfer, dragEl) {
  165. dataTransfer.setData('Text', dragEl.textContent);
  166. },
  167. dropBubble: false,
  168. dragoverBubble: false,
  169. dataIdAttr: 'data-id',
  170. delay: 0,
  171. forceFallback: false,
  172. fallbackClass: 'sortable-fallback',
  173. fallbackOnBody: false
  174. };
  175. // Set default options
  176. for (var name in defaults) {
  177. !(name in options) && (options[name] = defaults[name]);
  178. }
  179. _prepareGroup(options);
  180. // Bind all private methods
  181. for (var fn in this) {
  182. if (fn.charAt(0) === '_') {
  183. this[fn] = this[fn].bind(this);
  184. }
  185. }
  186. // Setup drag mode
  187. this.nativeDraggable = options.forceFallback ? false : supportDraggable;
  188. // Bind events
  189. _on(el, 'mousedown', this._onTapStart);
  190. _on(el, 'touchstart', this._onTapStart);
  191. if (this.nativeDraggable) {
  192. _on(el, 'dragover', this);
  193. _on(el, 'dragenter', this);
  194. }
  195. touchDragOverListeners.push(this._onDragOver);
  196. // Restore sorting
  197. options.store && this.sort(options.store.get(this));
  198. }
  199. Sortable.prototype = /** @lends Sortable.prototype */ {
  200. constructor: Sortable,
  201. _onTapStart: function (/** Event|TouchEvent */evt) {
  202. var _this = this,
  203. el = this.el,
  204. options = this.options,
  205. type = evt.type,
  206. touch = evt.touches && evt.touches[0],
  207. target = (touch || evt).target,
  208. originalTarget = target,
  209. filter = options.filter;
  210. if (type === 'mousedown' && evt.button !== 0 || options.disabled) {
  211. return; // only left button or enabled
  212. }
  213. target = _closest(target, options.draggable, el);
  214. if (!target) {
  215. return;
  216. }
  217. // get the index of the dragged element within its parent
  218. oldIndex = _index(target, options.draggable);
  219. // Check filter
  220. if (typeof filter === 'function') {
  221. if (filter.call(this, evt, target, this)) {
  222. _dispatchEvent(_this, originalTarget, 'filter', target, el, oldIndex);
  223. evt.preventDefault();
  224. return; // cancel dnd
  225. }
  226. }
  227. else if (filter) {
  228. filter = filter.split(',').some(function (criteria) {
  229. criteria = _closest(originalTarget, criteria.trim(), el);
  230. if (criteria) {
  231. _dispatchEvent(_this, criteria, 'filter', target, el, oldIndex);
  232. return true;
  233. }
  234. });
  235. if (filter) {
  236. evt.preventDefault();
  237. return; // cancel dnd
  238. }
  239. }
  240. if (options.handle && !_closest(originalTarget, options.handle, el)) {
  241. return;
  242. }
  243. // Prepare `dragstart`
  244. this._prepareDragStart(evt, touch, target);
  245. },
  246. _prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target) {
  247. var _this = this,
  248. el = _this.el,
  249. options = _this.options,
  250. ownerDocument = el.ownerDocument,
  251. dragStartFn;
  252. if (target && !dragEl && (target.parentNode === el)) {
  253. tapEvt = evt;
  254. rootEl = el;
  255. dragEl = target;
  256. parentEl = dragEl.parentNode;
  257. nextEl = dragEl.nextSibling;
  258. activeGroup = options.group;
  259. dragStartFn = function () {
  260. // Delayed drag has been triggered
  261. // we can re-enable the events: touchmove/mousemove
  262. _this._disableDelayedDrag();
  263. // Make the element draggable
  264. dragEl.draggable = true;
  265. // Chosen item
  266. _toggleClass(dragEl, _this.options.chosenClass, true);
  267. // Bind the events: dragstart/dragend
  268. _this._triggerDragStart(touch);
  269. };
  270. // Disable "draggable"
  271. options.ignore.split(',').forEach(function (criteria) {
  272. _find(dragEl, criteria.trim(), _disableDraggable);
  273. });
  274. _on(ownerDocument, 'mouseup', _this._onDrop);
  275. _on(ownerDocument, 'touchend', _this._onDrop);
  276. _on(ownerDocument, 'touchcancel', _this._onDrop);
  277. if (options.delay) {
  278. // If the user moves the pointer or let go the click or touch
  279. // before the delay has been reached:
  280. // disable the delayed drag
  281. _on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
  282. _on(ownerDocument, 'touchend', _this._disableDelayedDrag);
  283. _on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
  284. _on(ownerDocument, 'mousemove', _this._disableDelayedDrag);
  285. _on(ownerDocument, 'touchmove', _this._disableDelayedDrag);
  286. _this._dragStartTimer = setTimeout(dragStartFn, options.delay);
  287. } else {
  288. dragStartFn();
  289. }
  290. }
  291. },
  292. _disableDelayedDrag: function () {
  293. var ownerDocument = this.el.ownerDocument;
  294. clearTimeout(this._dragStartTimer);
  295. _off(ownerDocument, 'mouseup', this._disableDelayedDrag);
  296. _off(ownerDocument, 'touchend', this._disableDelayedDrag);
  297. _off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
  298. _off(ownerDocument, 'mousemove', this._disableDelayedDrag);
  299. _off(ownerDocument, 'touchmove', this._disableDelayedDrag);
  300. },
  301. _triggerDragStart: function (/** Touch */touch) {
  302. if (touch) {
  303. // Touch device support
  304. tapEvt = {
  305. target: dragEl,
  306. clientX: touch.clientX,
  307. clientY: touch.clientY
  308. };
  309. this._onDragStart(tapEvt, 'touch');
  310. }
  311. else if (!this.nativeDraggable) {
  312. this._onDragStart(tapEvt, true);
  313. }
  314. else {
  315. _on(dragEl, 'dragend', this);
  316. _on(rootEl, 'dragstart', this._onDragStart);
  317. }
  318. try {
  319. if (document.selection) {
  320. document.selection.empty();
  321. } else {
  322. window.getSelection().removeAllRanges();
  323. }
  324. } catch (err) {
  325. }
  326. },
  327. _dragStarted: function () {
  328. if (rootEl && dragEl) {
  329. // Apply effect
  330. _toggleClass(dragEl, this.options.ghostClass, true);
  331. Sortable.active = this;
  332. // Drag start event
  333. _dispatchEvent(this, rootEl, 'start', dragEl, rootEl, oldIndex);
  334. }
  335. },
  336. _emulateDragOver: function () {
  337. if (touchEvt) {
  338. if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY) {
  339. return;
  340. }
  341. this._lastX = touchEvt.clientX;
  342. this._lastY = touchEvt.clientY;
  343. if (!supportCssPointerEvents) {
  344. _css(ghostEl, 'display', 'none');
  345. }
  346. var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY),
  347. parent = target,
  348. groupName = ' ' + this.options.group.name + '',
  349. i = touchDragOverListeners.length;
  350. if (parent) {
  351. do {
  352. if (parent[expando] && parent[expando].options.groups.indexOf(groupName) > -1) {
  353. while (i--) {
  354. touchDragOverListeners[i]({
  355. clientX: touchEvt.clientX,
  356. clientY: touchEvt.clientY,
  357. target: target,
  358. rootEl: parent
  359. });
  360. }
  361. break;
  362. }
  363. target = parent; // store last element
  364. }
  365. /* jshint boss:true */
  366. while (parent = parent.parentNode);
  367. }
  368. if (!supportCssPointerEvents) {
  369. _css(ghostEl, 'display', '');
  370. }
  371. }
  372. },
  373. _onTouchMove: function (/**TouchEvent*/evt) {
  374. if (tapEvt) {
  375. // only set the status to dragging, when we are actually dragging
  376. if (!Sortable.active) {
  377. this._dragStarted();
  378. }
  379. // as well as creating the ghost element on the document body
  380. this._appendGhost();
  381. var touch = evt.touches ? evt.touches[0] : evt,
  382. dx = touch.clientX - tapEvt.clientX,
  383. dy = touch.clientY - tapEvt.clientY,
  384. translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)';
  385. moved = true;
  386. touchEvt = touch;
  387. _css(ghostEl, 'webkitTransform', translate3d);
  388. _css(ghostEl, 'mozTransform', translate3d);
  389. _css(ghostEl, 'msTransform', translate3d);
  390. _css(ghostEl, 'transform', translate3d);
  391. evt.preventDefault();
  392. }
  393. },
  394. _appendGhost: function () {
  395. if (!ghostEl) {
  396. var rect = dragEl.getBoundingClientRect(),
  397. css = _css(dragEl),
  398. options = this.options,
  399. ghostRect;
  400. ghostEl = dragEl.cloneNode(true);
  401. _toggleClass(ghostEl, options.ghostClass, false);
  402. _toggleClass(ghostEl, options.fallbackClass, true);
  403. _css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10));
  404. _css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10));
  405. _css(ghostEl, 'width', rect.width);
  406. _css(ghostEl, 'height', rect.height);
  407. _css(ghostEl, 'opacity', '0.8');
  408. _css(ghostEl, 'position', 'fixed');
  409. _css(ghostEl, 'zIndex', '100000');
  410. _css(ghostEl, 'pointerEvents', 'none');
  411. options.fallbackOnBody && document.body.appendChild(ghostEl) || rootEl.appendChild(ghostEl);
  412. // Fixing dimensions.
  413. ghostRect = ghostEl.getBoundingClientRect();
  414. _css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
  415. _css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
  416. }
  417. },
  418. _onDragStart: function (/**Event*/evt, /**boolean*/useFallback) {
  419. var dataTransfer = evt.dataTransfer,
  420. options = this.options;
  421. this._offUpEvents();
  422. if (activeGroup.pull == 'clone') {
  423. cloneEl = dragEl.cloneNode(true);
  424. _css(cloneEl, 'display', 'none');
  425. rootEl.insertBefore(cloneEl, dragEl);
  426. }
  427. if (useFallback) {
  428. if (useFallback === 'touch') {
  429. // Bind touch events
  430. _on(document, 'touchmove', this._onTouchMove);
  431. _on(document, 'touchend', this._onDrop);
  432. _on(document, 'touchcancel', this._onDrop);
  433. } else {
  434. // Old brwoser
  435. _on(document, 'mousemove', this._onTouchMove);
  436. _on(document, 'mouseup', this._onDrop);
  437. }
  438. this._loopId = setInterval(this._emulateDragOver, 50);
  439. }
  440. else {
  441. if (dataTransfer) {
  442. dataTransfer.effectAllowed = 'move';
  443. options.setData && options.setData.call(this, dataTransfer, dragEl);
  444. }
  445. _on(document, 'drop', this);
  446. setTimeout(this._dragStarted, 0);
  447. }
  448. },
  449. _onDragOver: function (/**Event*/evt) {
  450. var el = this.el,
  451. target,
  452. dragRect,
  453. revert,
  454. options = this.options,
  455. group = options.group,
  456. groupPut = group.put,
  457. isOwner = (activeGroup === group),
  458. canSort = options.sort;
  459. if (evt.preventDefault !== void 0) {
  460. evt.preventDefault();
  461. !options.dragoverBubble && evt.stopPropagation();
  462. }
  463. moved = true;
  464. if (activeGroup && !options.disabled &&
  465. (isOwner
  466. ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list
  467. : activeGroup.pull && groupPut && (
  468. (activeGroup.name === group.name) || // by Name
  469. (groupPut.indexOf && ~groupPut.indexOf(activeGroup.name)) // by Array
  470. )
  471. ) &&
  472. (evt.rootEl === void 0 || evt.rootEl === this.el) // touch fallback
  473. ) {
  474. // Smart auto-scrolling
  475. _autoScroll(evt, options, this.el);
  476. if (_silent) {
  477. return;
  478. }
  479. target = _closest(evt.target, options.draggable, el);
  480. dragRect = dragEl.getBoundingClientRect();
  481. if (revert) {
  482. _cloneHide(true);
  483. if (cloneEl || nextEl) {
  484. rootEl.insertBefore(dragEl, cloneEl || nextEl);
  485. }
  486. else if (!canSort) {
  487. rootEl.appendChild(dragEl);
  488. }
  489. return;
  490. }
  491. if ((el.children.length === 0) || (el.children[0] === ghostEl) ||
  492. (el === evt.target) && (target = _ghostIsLast(el, evt))
  493. ) {
  494. if (target) {
  495. if (target.animated) {
  496. return;
  497. }
  498. targetRect = target.getBoundingClientRect();
  499. }
  500. _cloneHide(isOwner);
  501. if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect) !== false) {
  502. if (!dragEl.contains(el)) {
  503. el.appendChild(dragEl);
  504. parentEl = el; // actualization
  505. }
  506. this._animate(dragRect, dragEl);
  507. target && this._animate(targetRect, target);
  508. }
  509. }
  510. else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) {
  511. if (lastEl !== target) {
  512. lastEl = target;
  513. lastCSS = _css(target);
  514. lastParentCSS = _css(target.parentNode);
  515. }
  516. var targetRect = target.getBoundingClientRect(),
  517. width = targetRect.right - targetRect.left,
  518. height = targetRect.bottom - targetRect.top,
  519. floating = /left|right|inline/.test(lastCSS.cssFloat + lastCSS.display)
  520. || (lastParentCSS.display == 'flex' && lastParentCSS['flex-direction'].indexOf('row') === 0),
  521. isWide = (target.offsetWidth > dragEl.offsetWidth),
  522. isLong = (target.offsetHeight > dragEl.offsetHeight),
  523. halfway = (floating ? (evt.clientX - targetRect.left) / width : (evt.clientY - targetRect.top) / height) > 0.5,
  524. nextSibling = target.nextElementSibling,
  525. moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect),
  526. after
  527. ;
  528. if (moveVector !== false) {
  529. _silent = true;
  530. setTimeout(_unsilent, 30);
  531. _cloneHide(isOwner);
  532. if (moveVector === 1 || moveVector === -1) {
  533. after = (moveVector === 1);
  534. }
  535. else if (floating) {
  536. var elTop = dragEl.offsetTop,
  537. tgTop = target.offsetTop;
  538. if (elTop === tgTop) {
  539. after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
  540. } else {
  541. after = tgTop > elTop;
  542. }
  543. } else {
  544. after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
  545. }
  546. if (!dragEl.contains(el)) {
  547. if (after && !nextSibling) {
  548. el.appendChild(dragEl);
  549. } else {
  550. target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
  551. }
  552. }
  553. parentEl = dragEl.parentNode; // actualization
  554. this._animate(dragRect, dragEl);
  555. this._animate(targetRect, target);
  556. }
  557. }
  558. }
  559. },
  560. _animate: function (prevRect, target) {
  561. var ms = this.options.animation;
  562. if (ms) {
  563. var currentRect = target.getBoundingClientRect();
  564. _css(target, 'transition', 'none');
  565. _css(target, 'transform', 'translate3d('
  566. + (prevRect.left - currentRect.left) + 'px,'
  567. + (prevRect.top - currentRect.top) + 'px,0)'
  568. );
  569. target.offsetWidth; // repaint
  570. _css(target, 'transition', 'all ' + ms + 'ms');
  571. _css(target, 'transform', 'translate3d(0,0,0)');
  572. clearTimeout(target.animated);
  573. target.animated = setTimeout(function () {
  574. _css(target, 'transition', '');
  575. _css(target, 'transform', '');
  576. target.animated = false;
  577. }, ms);
  578. }
  579. },
  580. _offUpEvents: function () {
  581. var ownerDocument = this.el.ownerDocument;
  582. _off(document, 'touchmove', this._onTouchMove);
  583. _off(ownerDocument, 'mouseup', this._onDrop);
  584. _off(ownerDocument, 'touchend', this._onDrop);
  585. _off(ownerDocument, 'touchcancel', this._onDrop);
  586. },
  587. _onDrop: function (/**Event*/evt) {
  588. var el = this.el,
  589. options = this.options;
  590. clearInterval(this._loopId);
  591. clearInterval(autoScroll.pid);
  592. clearTimeout(this._dragStartTimer);
  593. // Unbind events
  594. _off(document, 'mousemove', this._onTouchMove);
  595. if (this.nativeDraggable) {
  596. _off(document, 'drop', this);
  597. _off(el, 'dragstart', this._onDragStart);
  598. }
  599. this._offUpEvents();
  600. if (evt) {
  601. if (moved) {
  602. evt.preventDefault();
  603. !options.dropBubble && evt.stopPropagation();
  604. }
  605. ghostEl && ghostEl.parentNode.removeChild(ghostEl);
  606. if (dragEl) {
  607. if (this.nativeDraggable) {
  608. _off(dragEl, 'dragend', this);
  609. }
  610. _disableDraggable(dragEl);
  611. // Remove class's
  612. _toggleClass(dragEl, this.options.ghostClass, false);
  613. _toggleClass(dragEl, this.options.chosenClass, false);
  614. if (rootEl !== parentEl) {
  615. newIndex = _index(dragEl, options.draggable);
  616. if (newIndex >= 0) {
  617. // drag from one list and drop into another
  618. _dispatchEvent(null, parentEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
  619. _dispatchEvent(this, rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
  620. // Add event
  621. _dispatchEvent(null, parentEl, 'add', dragEl, rootEl, oldIndex, newIndex);
  622. // Remove event
  623. _dispatchEvent(this, rootEl, 'remove', dragEl, rootEl, oldIndex, newIndex);
  624. }
  625. }
  626. else {
  627. // Remove clone
  628. cloneEl && cloneEl.parentNode.removeChild(cloneEl);
  629. if (dragEl.nextSibling !== nextEl) {
  630. // Get the index of the dragged element within its parent
  631. newIndex = _index(dragEl, options.draggable);
  632. if (newIndex >= 0) {
  633. // drag & drop within the same list
  634. _dispatchEvent(this, rootEl, 'update', dragEl, rootEl, oldIndex, newIndex);
  635. _dispatchEvent(this, rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
  636. }
  637. }
  638. }
  639. if (Sortable.active) {
  640. if (newIndex === null || newIndex === -1) {
  641. newIndex = oldIndex;
  642. }
  643. _dispatchEvent(this, rootEl, 'end', dragEl, rootEl, oldIndex, newIndex);
  644. // Save sorting
  645. this.save();
  646. }
  647. }
  648. }
  649. this._nulling();
  650. },
  651. _nulling: function() {
  652. // Nulling
  653. rootEl =
  654. dragEl =
  655. parentEl =
  656. ghostEl =
  657. nextEl =
  658. cloneEl =
  659. scrollEl =
  660. scrollParentEl =
  661. tapEvt =
  662. touchEvt =
  663. moved =
  664. newIndex =
  665. lastEl =
  666. lastCSS =
  667. activeGroup =
  668. Sortable.active = null;
  669. },
  670. handleEvent: function (/**Event*/evt) {
  671. var type = evt.type;
  672. if (type === 'dragover' || type === 'dragenter') {
  673. if (dragEl) {
  674. this._onDragOver(evt);
  675. _globalDragOver(evt);
  676. }
  677. }
  678. else if (type === 'drop' || type === 'dragend') {
  679. this._onDrop(evt);
  680. }
  681. },
  682. /**
  683. * Serializes the item into an array of string.
  684. * @returns {String[]}
  685. */
  686. toArray: function () {
  687. var order = [],
  688. el,
  689. children = this.el.children,
  690. i = 0,
  691. n = children.length,
  692. options = this.options;
  693. for (; i < n; i++) {
  694. el = children[i];
  695. if (_closest(el, options.draggable, this.el)) {
  696. order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
  697. }
  698. }
  699. return order;
  700. },
  701. /**
  702. * Sorts the elements according to the array.
  703. * @param {String[]} order order of the items
  704. */
  705. sort: function (order) {
  706. var items = {}, rootEl = this.el;
  707. this.toArray().forEach(function (id, i) {
  708. var el = rootEl.children[i];
  709. if (_closest(el, this.options.draggable, rootEl)) {
  710. items[id] = el;
  711. }
  712. }, this);
  713. order.forEach(function (id) {
  714. if (items[id]) {
  715. rootEl.removeChild(items[id]);
  716. rootEl.appendChild(items[id]);
  717. }
  718. });
  719. },
  720. /**
  721. * Save the current sorting
  722. */
  723. save: function () {
  724. var store = this.options.store;
  725. store && store.set(this);
  726. },
  727. /**
  728. * 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.
  729. * @param {HTMLElement} el
  730. * @param {String} [selector] default: `options.draggable`
  731. * @returns {HTMLElement|null}
  732. */
  733. closest: function (el, selector) {
  734. return _closest(el, selector || this.options.draggable, this.el);
  735. },
  736. /**
  737. * Set/get option
  738. * @param {string} name
  739. * @param {*} [value]
  740. * @returns {*}
  741. */
  742. option: function (name, value) {
  743. var options = this.options;
  744. if (value === void 0) {
  745. return options[name];
  746. } else {
  747. options[name] = value;
  748. if (name === 'group') {
  749. _prepareGroup(options);
  750. }
  751. }
  752. },
  753. /**
  754. * Destroy
  755. */
  756. destroy: function () {
  757. var el = this.el;
  758. el[expando] = null;
  759. _off(el, 'mousedown', this._onTapStart);
  760. _off(el, 'touchstart', this._onTapStart);
  761. if (this.nativeDraggable) {
  762. _off(el, 'dragover', this);
  763. _off(el, 'dragenter', this);
  764. }
  765. // Remove draggable attributes
  766. Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
  767. el.removeAttribute('draggable');
  768. });
  769. touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);
  770. this._onDrop();
  771. this.el = el = null;
  772. }
  773. };
  774. function _cloneHide(state) {
  775. if (cloneEl && (cloneEl.state !== state)) {
  776. _css(cloneEl, 'display', state ? 'none' : '');
  777. !state && cloneEl.state && rootEl.insertBefore(cloneEl, dragEl);
  778. cloneEl.state = state;
  779. }
  780. }
  781. function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) {
  782. if (el) {
  783. ctx = ctx || document;
  784. do {
  785. if (
  786. (selector === '>*' && el.parentNode === ctx)
  787. || _matches(el, selector)
  788. ) {
  789. return el;
  790. }
  791. }
  792. while (el !== ctx && (el = el.parentNode));
  793. }
  794. return null;
  795. }
  796. function _globalDragOver(/**Event*/evt) {
  797. if (evt.dataTransfer) {
  798. evt.dataTransfer.dropEffect = 'move';
  799. }
  800. evt.preventDefault();
  801. }
  802. function _on(el, event, fn) {
  803. el.addEventListener(event, fn, false);
  804. }
  805. function _off(el, event, fn) {
  806. el.removeEventListener(event, fn, false);
  807. }
  808. function _toggleClass(el, name, state) {
  809. if (el) {
  810. if (el.classList) {
  811. el.classList[state ? 'add' : 'remove'](name);
  812. }
  813. else {
  814. var className = (' ' + el.className + ' ').replace(RSPACE, ' ').replace(' ' + name + ' ', ' ');
  815. el.className = (className + (state ? ' ' + name : '')).replace(RSPACE, ' ');
  816. }
  817. }
  818. }
  819. function _css(el, prop, val) {
  820. var style = el && el.style;
  821. if (style) {
  822. if (val === void 0) {
  823. if (document.defaultView && document.defaultView.getComputedStyle) {
  824. val = document.defaultView.getComputedStyle(el, '');
  825. }
  826. else if (el.currentStyle) {
  827. val = el.currentStyle;
  828. }
  829. return prop === void 0 ? val : val[prop];
  830. }
  831. else {
  832. if (!(prop in style)) {
  833. prop = '-webkit-' + prop;
  834. }
  835. style[prop] = val + (typeof val === 'string' ? '' : 'px');
  836. }
  837. }
  838. }
  839. function _find(ctx, tagName, iterator) {
  840. if (ctx) {
  841. var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
  842. if (iterator) {
  843. for (; i < n; i++) {
  844. iterator(list[i], i);
  845. }
  846. }
  847. return list;
  848. }
  849. return [];
  850. }
  851. function _dispatchEvent(sortable, rootEl, name, targetEl, fromEl, startIndex, newIndex) {
  852. var evt = document.createEvent('Event'),
  853. options = (sortable || rootEl[expando]).options,
  854. onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);
  855. evt.initEvent(name, true, true);
  856. evt.to = rootEl;
  857. evt.from = fromEl || rootEl;
  858. evt.item = targetEl || rootEl;
  859. evt.clone = cloneEl;
  860. evt.oldIndex = startIndex;
  861. evt.newIndex = newIndex;
  862. rootEl.dispatchEvent(evt);
  863. if (options[onName]) {
  864. options[onName].call(sortable, evt);
  865. }
  866. }
  867. function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect) {
  868. var evt,
  869. sortable = fromEl[expando],
  870. onMoveFn = sortable.options.onMove,
  871. retVal;
  872. evt = document.createEvent('Event');
  873. evt.initEvent('move', true, true);
  874. evt.to = toEl;
  875. evt.from = fromEl;
  876. evt.dragged = dragEl;
  877. evt.draggedRect = dragRect;
  878. evt.related = targetEl || toEl;
  879. evt.relatedRect = targetRect || toEl.getBoundingClientRect();
  880. fromEl.dispatchEvent(evt);
  881. if (onMoveFn) {
  882. retVal = onMoveFn.call(sortable, evt);
  883. }
  884. return retVal;
  885. }
  886. function _disableDraggable(el) {
  887. el.draggable = false;
  888. }
  889. function _unsilent() {
  890. _silent = false;
  891. }
  892. /** @returns {HTMLElement|false} */
  893. function _ghostIsLast(el, evt) {
  894. var lastEl = el.lastElementChild,
  895. rect = lastEl.getBoundingClientRect();
  896. return ((evt.clientY - (rect.top + rect.height) > 5) || (evt.clientX - (rect.right + rect.width) > 5)) && lastEl; // min delta
  897. }
  898. /**
  899. * Generate id
  900. * @param {HTMLElement} el
  901. * @returns {String}
  902. * @private
  903. */
  904. function _generateId(el) {
  905. var str = el.tagName + el.className + el.src + el.href + el.textContent,
  906. i = str.length,
  907. sum = 0;
  908. while (i--) {
  909. sum += str.charCodeAt(i);
  910. }
  911. return sum.toString(36);
  912. }
  913. /**
  914. * Returns the index of an element within its parent for a selected set of
  915. * elements
  916. * @param {HTMLElement} el
  917. * @param {selector} selector
  918. * @return {number}
  919. */
  920. function _index(el, selector) {
  921. var index = 0;
  922. if (!el || !el.parentNode) {
  923. return -1;
  924. }
  925. while (el && (el = el.previousElementSibling)) {
  926. if (el.nodeName.toUpperCase() !== 'TEMPLATE'
  927. && _matches(el, selector)) {
  928. index++;
  929. }
  930. }
  931. return index;
  932. }
  933. function _matches(/**HTMLElement*/el, /**String*/selector) {
  934. if (el) {
  935. selector = selector.split('.');
  936. var tag = selector.shift().toUpperCase(),
  937. re = new RegExp('\\s(' + selector.join('|') + ')(?=\\s)', 'g');
  938. return (
  939. (tag === '' || el.nodeName.toUpperCase() == tag) &&
  940. (!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
  941. );
  942. }
  943. return false;
  944. }
  945. function _throttle(callback, ms) {
  946. var args, _this;
  947. return function () {
  948. if (args === void 0) {
  949. args = arguments;
  950. _this = this;
  951. setTimeout(function () {
  952. if (args.length === 1) {
  953. callback.call(_this, args[0]);
  954. } else {
  955. callback.apply(_this, args);
  956. }
  957. args = void 0;
  958. }, ms);
  959. }
  960. };
  961. }
  962. function _extend(dst, src) {
  963. if (dst && src) {
  964. for (var key in src) {
  965. if (src.hasOwnProperty(key)) {
  966. dst[key] = src[key];
  967. }
  968. }
  969. }
  970. return dst;
  971. }
  972. // Export utils
  973. Sortable.utils = {
  974. on: _on,
  975. off: _off,
  976. css: _css,
  977. find: _find,
  978. is: function (el, selector) {
  979. return !!_closest(el, selector, el);
  980. },
  981. extend: _extend,
  982. throttle: _throttle,
  983. closest: _closest,
  984. toggleClass: _toggleClass,
  985. index: _index
  986. };
  987. /**
  988. * Create sortable instance
  989. * @param {HTMLElement} el
  990. * @param {Object} [options]
  991. */
  992. Sortable.create = function (el, options) {
  993. return new Sortable(el, options);
  994. };
  995. // Export
  996. Sortable.version = '1.4.2';
  997. return Sortable;
  998. });
  999. /**
  1000. * jQuery plugin for Sortable
  1001. * @author RubaXa <[email protected]>
  1002. * @license MIT
  1003. */
  1004. (function (factory) {
  1005. "use strict";
  1006. if (typeof define === "function" && define.amd) {
  1007. define(["jquery"], factory);
  1008. }
  1009. else {
  1010. /* jshint sub:true */
  1011. factory(jQuery);
  1012. }
  1013. })(function ($) {
  1014. "use strict";
  1015. /* CODE */
  1016. /**
  1017. * jQuery plugin for Sortable
  1018. * @param {Object|String} options
  1019. * @param {..*} [args]
  1020. * @returns {jQuery|*}
  1021. */
  1022. $.fn.sortable = function (options) {
  1023. var retVal,
  1024. args = arguments;
  1025. this.each(function () {
  1026. var $el = $(this),
  1027. sortable = $el.data('sortable');
  1028. if (!sortable && (options instanceof Object || !options)) {
  1029. sortable = new Sortable(this, options);
  1030. $el.data('sortable', sortable);
  1031. }
  1032. if (sortable) {
  1033. if (options === 'widget') {
  1034. return sortable;
  1035. }
  1036. else if (options === 'destroy') {
  1037. sortable.destroy();
  1038. $el.removeData('sortable');
  1039. }
  1040. else if (typeof sortable[options] === 'function') {
  1041. retVal = sortable[options].apply(sortable, [].slice.call(args, 1));
  1042. }
  1043. else if (options in sortable.options) {
  1044. retVal = sortable.option.apply(sortable, args);
  1045. }
  1046. }
  1047. });
  1048. return (retVal === void 0) ? this : retVal;
  1049. };
  1050. });