sortable.js 30 KB

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