sortable.js 28 KB

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