Sortable-edit.js 30 KB

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