Sortable.js 35 KB

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