Sortable.js 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473
  1. /**!
  2. * Sortable
  3. * @author RubaXa <trash@rubaxa.org>
  4. * @author owenm <owen23355@gmail.com>
  5. * @license MIT
  6. */
  7. (function sortableModule(factory) {
  8. "use strict";
  9. if (typeof define === "function" && define.amd) {
  10. define(factory);
  11. }
  12. else if (typeof module != "undefined" && typeof module.exports != "undefined") {
  13. module.exports = factory();
  14. }
  15. else {
  16. /* jshint sub:true */
  17. window["Sortable"] = factory();
  18. }
  19. })(function sortableFactory() {
  20. "use strict";
  21. if (typeof window === "undefined" || !window.document) {
  22. return function sortableError() {
  23. throw new Error("Sortable.js requires a window with a document");
  24. };
  25. }
  26. var dragEl,
  27. parentEl,
  28. ghostEl,
  29. cloneEl,
  30. rootEl,
  31. nextEl,
  32. lastDownEl,
  33. scrollEl,
  34. scrollParentEl,
  35. scrollCustomFn,
  36. oldIndex,
  37. newIndex,
  38. activeGroup,
  39. putSortable,
  40. autoScrolls = [],
  41. scrolling = false,
  42. awaitingDragStarted = false,
  43. ignoreNextClick = false,
  44. sortables = [],
  45. pointerElemChangedInterval,
  46. lastPointerElemX,
  47. lastPointerElemY,
  48. tapEvt,
  49. touchEvt,
  50. moved,
  51. lastTarget,
  52. lastDirection,
  53. pastFirstInvertThresh = false,
  54. isCircumstantialInvert = false,
  55. lastMode, // 'swap' or 'insert'
  56. targetMoveDistance,
  57. // For positioning ghost absolutely
  58. ghostRelativeParent,
  59. ghostRelativeParentInitialScroll = [], // (left, top)
  60. forRepaintDummy,
  61. realDragElRect, // dragEl rect after current animation
  62. /** @const */
  63. R_SPACE = /\s+/g,
  64. expando = 'Sortable' + (new Date).getTime(),
  65. win = window,
  66. document = win.document,
  67. parseInt = win.parseInt,
  68. setTimeout = win.setTimeout,
  69. $ = win.jQuery || win.Zepto,
  70. Polymer = win.Polymer,
  71. captureMode = {
  72. capture: false,
  73. passive: false
  74. },
  75. IE11OrLess = !!navigator.userAgent.match(/(?:Trident.*rv[ :]?11\.|msie|iemobile)/i),
  76. Edge = !!navigator.userAgent.match(/Edge/i),
  77. FireFox = !!navigator.userAgent.match(/firefox/i),
  78. Safari = !!(navigator.userAgent.match(/safari/i) && !navigator.userAgent.match(/chrome/i) && !navigator.userAgent.match(/android/i)),
  79. IOS = !!(navigator.userAgent.match(/iP(ad|od|hone)/i)),
  80. PositionGhostAbsolutely = IOS,
  81. CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float',
  82. // This will not pass for IE9, because IE9 DnD only works on anchors
  83. supportDraggable = ('draggable' in document.createElement('div')),
  84. supportCssPointerEvents = (function() {
  85. // false when <= IE11
  86. if (IE11OrLess) {
  87. return false;
  88. }
  89. var el = document.createElement('x');
  90. el.style.cssText = 'pointer-events:auto';
  91. return el.style.pointerEvents === 'auto';
  92. })(),
  93. _silent = false,
  94. _alignedSilent = false,
  95. abs = Math.abs,
  96. min = Math.min,
  97. max = Math.max,
  98. savedInputChecked = [],
  99. _detectDirection = function(el, options) {
  100. var elCSS = _css(el),
  101. elWidth = parseInt(elCSS.width)
  102. - parseInt(elCSS.paddingLeft)
  103. - parseInt(elCSS.paddingRight)
  104. - parseInt(elCSS.borderLeftWidth)
  105. - parseInt(elCSS.borderRightWidth),
  106. child1 = _getChild(el, 0, options),
  107. child2 = _getChild(el, 1, options),
  108. firstChildCSS = child1 && _css(child1),
  109. secondChildCSS = child2 && _css(child2),
  110. firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + _getRect(child1).width,
  111. secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + _getRect(child2).width;
  112. if (elCSS.display === 'flex') {
  113. return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse'
  114. ? 'vertical' : 'horizontal';
  115. }
  116. if (elCSS.display === 'grid') {
  117. return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal';
  118. }
  119. if (child1 && firstChildCSS.float !== 'none') {
  120. var touchingSideChild2 = firstChildCSS.float === 'left' ? 'left' : 'right';
  121. return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ?
  122. 'vertical' : 'horizontal';
  123. }
  124. return (child1 &&
  125. (
  126. firstChildCSS.display === 'block' ||
  127. firstChildCSS.display === 'flex' ||
  128. firstChildCSS.display === 'table' ||
  129. firstChildCSS.display === 'grid' ||
  130. firstChildWidth >= elWidth &&
  131. elCSS[CSSFloatProperty] === 'none' ||
  132. child2 &&
  133. elCSS[CSSFloatProperty] === 'none' &&
  134. firstChildWidth + secondChildWidth > elWidth
  135. ) ?
  136. 'vertical' : 'horizontal'
  137. );
  138. },
  139. /**
  140. * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold.
  141. * @param {Number} x X position
  142. * @param {Number} y Y position
  143. * @return {HTMLElement} Element of the first found nearest Sortable
  144. */
  145. _detectNearestEmptySortable = function(x, y) {
  146. for (var i = 0; i < sortables.length; i++) {
  147. if (_lastChild(sortables[i])) continue;
  148. var rect = _getRect(sortables[i]),
  149. threshold = sortables[i][expando].options.emptyInsertThreshold,
  150. insideHorizontally = x >= (rect.left - threshold) && x <= (rect.right + threshold),
  151. insideVertically = y >= (rect.top - threshold) && y <= (rect.bottom + threshold);
  152. if (insideHorizontally && insideVertically) {
  153. return sortables[i];
  154. }
  155. }
  156. },
  157. _isClientInRowColumn = function(x, y, el, axis, options) {
  158. var targetRect = _getRect(el),
  159. targetS1Opp = axis === 'vertical' ? targetRect.left : targetRect.top,
  160. targetS2Opp = axis === 'vertical' ? targetRect.right : targetRect.bottom,
  161. mouseOnOppAxis = axis === 'vertical' ? x : y;
  162. return targetS1Opp < mouseOnOppAxis && mouseOnOppAxis < targetS2Opp;
  163. },
  164. _isElInRowColumn = function(el1, el2, axis) {
  165. var el1Rect = el1 === dragEl && realDragElRect || _getRect(el1),
  166. el2Rect = el2 === dragEl && realDragElRect || _getRect(el2),
  167. el1S1Opp = axis === 'vertical' ? el1Rect.left : el1Rect.top,
  168. el1S2Opp = axis === 'vertical' ? el1Rect.right : el1Rect.bottom,
  169. el1OppLength = axis === 'vertical' ? el1Rect.width : el1Rect.height,
  170. el2S1Opp = axis === 'vertical' ? el2Rect.left : el2Rect.top,
  171. el2S2Opp = axis === 'vertical' ? el2Rect.right : el2Rect.bottom,
  172. el2OppLength = axis === 'vertical' ? el2Rect.width : el2Rect.height;
  173. return (
  174. el1S1Opp === el2S1Opp ||
  175. el1S2Opp === el2S2Opp ||
  176. (el1S1Opp + el1OppLength / 2) === (el2S1Opp + el2OppLength / 2)
  177. );
  178. },
  179. _getParentAutoScrollElement = function(el, includeSelf) {
  180. // skip to window
  181. if (!el || !el.getBoundingClientRect) return _getWindowScrollingElement();
  182. var elem = el;
  183. var gotSelf = false;
  184. do {
  185. // we don't need to get elem css if it isn't even overflowing in the first place (performance)
  186. if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) {
  187. var elemCSS = _css(elem);
  188. if (
  189. elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') ||
  190. elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')
  191. ) {
  192. if (!elem || !elem.getBoundingClientRect || elem === document.body) return _getWindowScrollingElement();
  193. if (gotSelf || includeSelf) return elem;
  194. gotSelf = true;
  195. }
  196. }
  197. /* jshint boss:true */
  198. } while (elem = elem.parentNode);
  199. return _getWindowScrollingElement();
  200. },
  201. _getWindowScrollingElement = function() {
  202. if (IE11OrLess) {
  203. return document.documentElement;
  204. } else {
  205. return document.scrollingElement;
  206. }
  207. },
  208. _scrollBy = function(el, x, y) {
  209. el.scrollLeft += x;
  210. el.scrollTop += y;
  211. },
  212. _autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl, /**Boolean*/isFallback) {
  213. // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
  214. if (options.scroll) {
  215. var _this = rootEl ? rootEl[expando] : window,
  216. sens = options.scrollSensitivity,
  217. speed = options.scrollSpeed,
  218. x = evt.clientX,
  219. y = evt.clientY,
  220. winScroller = _getWindowScrollingElement(),
  221. scrollThisInstance = false;
  222. // Detect scrollEl
  223. if (scrollParentEl !== rootEl) {
  224. _clearAutoScrolls();
  225. scrollEl = options.scroll;
  226. scrollCustomFn = options.scrollFn;
  227. if (scrollEl === true) {
  228. scrollEl = _getParentAutoScrollElement(rootEl, true);
  229. scrollParentEl = scrollEl;
  230. }
  231. }
  232. var layersOut = 0;
  233. var currentParent = scrollEl;
  234. do {
  235. var el = currentParent,
  236. rect = _getRect(el),
  237. top = rect.top,
  238. bottom = rect.bottom,
  239. left = rect.left,
  240. right = rect.right,
  241. width = rect.width,
  242. height = rect.height,
  243. scrollWidth,
  244. scrollHeight,
  245. css,
  246. vx,
  247. vy,
  248. canScrollX,
  249. canScrollY,
  250. scrollPosX,
  251. scrollPosY;
  252. scrollWidth = el.scrollWidth;
  253. scrollHeight = el.scrollHeight;
  254. css = _css(el);
  255. scrollPosX = el.scrollLeft;
  256. scrollPosY = el.scrollTop;
  257. if (el === winScroller) {
  258. canScrollX = width < scrollWidth && (css.overflowX === 'auto' || css.overflowX === 'scroll' || css.overflowX === 'visible');
  259. canScrollY = height < scrollHeight && (css.overflowY === 'auto' || css.overflowY === 'scroll' || css.overflowY === 'visible');
  260. } else {
  261. canScrollX = width < scrollWidth && (css.overflowX === 'auto' || css.overflowX === 'scroll');
  262. canScrollY = height < scrollHeight && (css.overflowY === 'auto' || css.overflowY === 'scroll');
  263. }
  264. vx = canScrollX && (abs(right - x) <= sens && (scrollPosX + width) < scrollWidth) - (abs(left - x) <= sens && !!scrollPosX);
  265. vy = canScrollY && (abs(bottom - y) <= sens && (scrollPosY + height) < scrollHeight) - (abs(top - y) <= sens && !!scrollPosY);
  266. if (!autoScrolls[layersOut]) {
  267. for (var i = 0; i <= layersOut; i++) {
  268. if (!autoScrolls[i]) {
  269. autoScrolls[i] = {};
  270. }
  271. }
  272. }
  273. if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) {
  274. autoScrolls[layersOut].el = el;
  275. autoScrolls[layersOut].vx = vx;
  276. autoScrolls[layersOut].vy = vy;
  277. clearInterval(autoScrolls[layersOut].pid);
  278. if (el && (vx != 0 || vy != 0)) {
  279. scrollThisInstance = true;
  280. /* jshint loopfunc:true */
  281. autoScrolls[layersOut].pid = setInterval((function () {
  282. // emulate drag over during autoscroll (fallback), emulating native DnD behaviour
  283. if (isFallback && this.layer === 0) {
  284. Sortable.active._emulateDragOver(true);
  285. Sortable.active._onTouchMove(touchEvt, true);
  286. }
  287. var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0;
  288. var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0;
  289. if ('function' === typeof(scrollCustomFn)) {
  290. if (scrollCustomFn.call(_this, scrollOffsetX, scrollOffsetY, evt, touchEvt, autoScrolls[this.layer].el) !== 'continue') {
  291. return;
  292. }
  293. }
  294. _scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY);
  295. }).bind({layer: layersOut}), 24);
  296. }
  297. }
  298. layersOut++;
  299. } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = _getParentAutoScrollElement(currentParent, false)));
  300. scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not
  301. }
  302. }, 30),
  303. _clearAutoScrolls = function () {
  304. autoScrolls.forEach(function(autoScroll) {
  305. clearInterval(autoScroll.pid);
  306. });
  307. autoScrolls = [];
  308. },
  309. _prepareGroup = function (options) {
  310. function toFn(value, pull) {
  311. return function(to, from, dragEl, evt) {
  312. var sameGroup = to.options.group.name &&
  313. from.options.group.name &&
  314. to.options.group.name === from.options.group.name;
  315. if (value == null && (pull || sameGroup)) {
  316. // Default pull value
  317. // Default pull and put value if same group
  318. return true;
  319. } else if (value == null || value === false) {
  320. return false;
  321. } else if (pull && value === 'clone') {
  322. return value;
  323. } else if (typeof value === 'function') {
  324. return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt);
  325. } else {
  326. var otherGroup = (pull ? to : from).options.group.name;
  327. return (value === true ||
  328. (typeof value === 'string' && value === otherGroup) ||
  329. (value.join && value.indexOf(otherGroup) > -1));
  330. }
  331. };
  332. }
  333. var group = {};
  334. var originalGroup = options.group;
  335. if (!originalGroup || typeof originalGroup != 'object') {
  336. originalGroup = {name: originalGroup};
  337. }
  338. group.name = originalGroup.name;
  339. group.checkPull = toFn(originalGroup.pull, true);
  340. group.checkPut = toFn(originalGroup.put);
  341. group.revertClone = originalGroup.revertClone;
  342. options.group = group;
  343. },
  344. _checkAlignment = function(evt) {
  345. if (!dragEl || !dragEl.parentNode) return;
  346. dragEl.parentNode[expando] && dragEl.parentNode[expando]._computeIsAligned(evt);
  347. },
  348. _isTrueParentSortable = function(el, target) {
  349. var trueParent = target;
  350. while (!trueParent[expando]) {
  351. trueParent = trueParent.parentNode;
  352. }
  353. return el === trueParent;
  354. },
  355. _artificalBubble = function(sortable, originalEvt, method) {
  356. // Artificial IE bubbling
  357. var nextParent = sortable.parentNode;
  358. while (nextParent && !nextParent[expando]) {
  359. nextParent = nextParent.parentNode;
  360. }
  361. if (nextParent) {
  362. nextParent[expando][method](_extend(originalEvt, {
  363. artificialBubble: true
  364. }));
  365. }
  366. },
  367. _hideGhostForTarget = function() {
  368. if (!supportCssPointerEvents && ghostEl) {
  369. _css(ghostEl, 'display', 'none');
  370. }
  371. },
  372. _unhideGhostForTarget = function() {
  373. if (!supportCssPointerEvents && ghostEl) {
  374. _css(ghostEl, 'display', '');
  375. }
  376. };
  377. // #1184 fix - Prevent click event on fallback if dragged but item not changed position
  378. document.addEventListener('click', function(evt) {
  379. if (ignoreNextClick) {
  380. evt.preventDefault();
  381. evt.stopPropagation && evt.stopPropagation();
  382. evt.stopImmediatePropagation && evt.stopImmediatePropagation();
  383. ignoreNextClick = false;
  384. return false;
  385. }
  386. }, true);
  387. var nearestEmptyInsertDetectEvent = function(evt) {
  388. evt = evt.touches ? evt.touches[0] : evt;
  389. if (dragEl) {
  390. var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY);
  391. if (nearest) {
  392. nearest[expando]._onDragOver({
  393. clientX: evt.clientX,
  394. clientY: evt.clientY,
  395. target: nearest,
  396. rootEl: nearest
  397. });
  398. }
  399. }
  400. };
  401. // We do not want this to be triggered if completed (bubbling canceled), so only define it here
  402. _on(document, 'dragover', nearestEmptyInsertDetectEvent);
  403. _on(document, 'mousemove', nearestEmptyInsertDetectEvent);
  404. _on(document, 'touchmove', nearestEmptyInsertDetectEvent);
  405. /**
  406. * @class Sortable
  407. * @param {HTMLElement} el
  408. * @param {Object} [options]
  409. */
  410. function Sortable(el, options) {
  411. if (!(el && el.nodeType && el.nodeType === 1)) {
  412. throw 'Sortable: `el` must be HTMLElement, not ' + {}.toString.call(el);
  413. }
  414. this.el = el; // root element
  415. this.options = options = _extend({}, options);
  416. // Export instance
  417. el[expando] = this;
  418. // Default options
  419. var defaults = {
  420. group: null,
  421. sort: true,
  422. disabled: false,
  423. store: null,
  424. handle: null,
  425. scroll: true,
  426. scrollSensitivity: 30,
  427. scrollSpeed: 10,
  428. bubbleScroll: true,
  429. draggable: /[uo]l/i.test(el.nodeName) ? '>li' : '>*',
  430. swapThreshold: 1, // percentage; 0 <= x <= 1
  431. invertSwap: false, // invert always
  432. invertedSwapThreshold: null, // will be set to same as swapThreshold if default
  433. removeCloneOnHide: true,
  434. direction: function() {
  435. return _detectDirection(el, this.options);
  436. },
  437. ghostClass: 'sortable-ghost',
  438. chosenClass: 'sortable-chosen',
  439. dragClass: 'sortable-drag',
  440. ignore: 'a, img',
  441. filter: null,
  442. preventOnFilter: true,
  443. animation: 0,
  444. easing: null,
  445. setData: function (dataTransfer, dragEl) {
  446. dataTransfer.setData('Text', dragEl.textContent);
  447. },
  448. dropBubble: false,
  449. dragoverBubble: false,
  450. dataIdAttr: 'data-id',
  451. delay: 0,
  452. touchStartThreshold: parseInt(window.devicePixelRatio, 10) || 1,
  453. forceFallback: false,
  454. fallbackClass: 'sortable-fallback',
  455. fallbackOnBody: false,
  456. fallbackTolerance: 0,
  457. fallbackOffset: {x: 0, y: 0},
  458. supportPointer: Sortable.supportPointer !== false && (
  459. ('PointerEvent' in window) ||
  460. window.navigator && ('msPointerEnabled' in window.navigator) // microsoft
  461. ),
  462. emptyInsertThreshold: 5
  463. };
  464. // Set default options
  465. for (var name in defaults) {
  466. !(name in options) && (options[name] = defaults[name]);
  467. }
  468. _prepareGroup(options);
  469. // Bind all private methods
  470. for (var fn in this) {
  471. if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
  472. this[fn] = this[fn].bind(this);
  473. }
  474. }
  475. // Setup drag mode
  476. this.nativeDraggable = options.forceFallback ? false : supportDraggable;
  477. if (this.nativeDraggable) {
  478. // Touch start threshold cannot be greater than the native dragstart threshold
  479. this.options.touchStartThreshold = 1;
  480. }
  481. // Bind events
  482. if (options.supportPointer) {
  483. _on(el, 'pointerdown', this._onTapStart);
  484. } else {
  485. _on(el, 'mousedown', this._onTapStart);
  486. _on(el, 'touchstart', this._onTapStart);
  487. }
  488. if (this.nativeDraggable) {
  489. _on(el, 'dragover', this);
  490. _on(el, 'dragenter', this);
  491. }
  492. sortables.push(this.el);
  493. // Restore sorting
  494. options.store && options.store.get && this.sort(options.store.get(this) || []);
  495. }
  496. Sortable.prototype = /** @lends Sortable.prototype */ {
  497. constructor: Sortable,
  498. _computeIsAligned: function(evt) {
  499. var target;
  500. if (ghostEl && !supportCssPointerEvents) {
  501. _hideGhostForTarget();
  502. target = document.elementFromPoint(evt.clientX, evt.clientY);
  503. _unhideGhostForTarget();
  504. } else {
  505. target = evt.target;
  506. }
  507. target = _closest(target, this.options.draggable, this.el, false);
  508. if (_alignedSilent) return;
  509. if (!dragEl || dragEl.parentNode !== this.el) return;
  510. var children = this.el.children;
  511. for (var i = 0; i < children.length; i++) {
  512. // Don't change for target in case it is changed to aligned before onDragOver is fired
  513. if (_closest(children[i], this.options.draggable, this.el, false) && children[i] !== target) {
  514. children[i].sortableMouseAligned = _isClientInRowColumn(evt.clientX, evt.clientY, children[i], this._getDirection(evt, null), this.options);
  515. }
  516. }
  517. // Used for nulling last target when not in element, nothing to do with checking if aligned
  518. if (!_closest(target, this.options.draggable, this.el, true)) {
  519. lastTarget = null;
  520. }
  521. _alignedSilent = true;
  522. setTimeout(function() {
  523. _alignedSilent = false;
  524. }, 30);
  525. },
  526. _getDirection: function(evt, target) {
  527. return (typeof this.options.direction === 'function') ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction;
  528. },
  529. _onTapStart: function (/** Event|TouchEvent */evt) {
  530. if (!evt.cancelable) return;
  531. var _this = this,
  532. el = this.el,
  533. options = this.options,
  534. preventOnFilter = options.preventOnFilter,
  535. type = evt.type,
  536. touch = evt.touches && evt.touches[0],
  537. target = (touch || evt).target,
  538. originalTarget = evt.target.shadowRoot && ((evt.path && evt.path[0]) || (evt.composedPath && evt.composedPath()[0])) || target,
  539. filter = options.filter,
  540. startIndex;
  541. _saveInputCheckedState(el);
  542. // IE: Calls events in capture mode if event element is nested. This ensures only correct element's _onTapStart goes through.
  543. // This process is also done in _onDragOver
  544. if (IE11OrLess && !evt.artificialBubble && !_isTrueParentSortable(el, target)) {
  545. return;
  546. }
  547. // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.
  548. if (dragEl) {
  549. return;
  550. }
  551. if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {
  552. return; // only left button and enabled
  553. }
  554. // cancel dnd if original target is content editable
  555. if (originalTarget.isContentEditable) {
  556. return;
  557. }
  558. target = _closest(target, options.draggable, el, false);
  559. if (!target) {
  560. if (IE11OrLess) {
  561. _artificalBubble(el, evt, '_onTapStart');
  562. }
  563. return;
  564. }
  565. if (lastDownEl === target) {
  566. // Ignoring duplicate `down`
  567. return;
  568. }
  569. // Get the index of the dragged element within its parent
  570. startIndex = _index(target, options.draggable);
  571. // Check filter
  572. if (typeof filter === 'function') {
  573. if (filter.call(this, evt, target, this)) {
  574. _dispatchEvent(_this, originalTarget, 'filter', target, el, el, startIndex);
  575. preventOnFilter && evt.cancelable && evt.preventDefault();
  576. return; // cancel dnd
  577. }
  578. }
  579. else if (filter) {
  580. filter = filter.split(',').some(function (criteria) {
  581. criteria = _closest(originalTarget, criteria.trim(), el, false);
  582. if (criteria) {
  583. _dispatchEvent(_this, criteria, 'filter', target, el, el, startIndex);
  584. return true;
  585. }
  586. });
  587. if (filter) {
  588. preventOnFilter && evt.cancelable && evt.preventDefault();
  589. return; // cancel dnd
  590. }
  591. }
  592. if (options.handle && !_closest(originalTarget, options.handle, el, false)) {
  593. return;
  594. }
  595. // Prepare `dragstart`
  596. this._prepareDragStart(evt, touch, target, startIndex);
  597. },
  598. _handleAutoScroll: function(evt, fallback) {
  599. if (!dragEl || !this.options.scroll) return;
  600. var x = evt.clientX,
  601. y = evt.clientY,
  602. elem = document.elementFromPoint(x, y),
  603. _this = this;
  604. // IE does not seem to have native autoscroll,
  605. // Edge's autoscroll seems too conditional,
  606. // MACOS Safari does not have autoscroll,
  607. // Firefox and Chrome are good
  608. if (fallback || Edge || IE11OrLess || Safari) {
  609. _autoScroll(evt, _this.options, elem, fallback);
  610. // Listener for pointer element change
  611. var ogElemScroller = _getParentAutoScrollElement(elem, true);
  612. if (
  613. scrolling &&
  614. (
  615. !pointerElemChangedInterval ||
  616. x !== lastPointerElemX ||
  617. y !== lastPointerElemY
  618. )
  619. ) {
  620. pointerElemChangedInterval && clearInterval(pointerElemChangedInterval);
  621. // Detect for pointer elem change, emulating native DnD behaviour
  622. pointerElemChangedInterval = setInterval(function() {
  623. if (!dragEl) return;
  624. // could also check if scroll direction on newElem changes due to parent autoscrolling
  625. var newElem = _getParentAutoScrollElement(document.elementFromPoint(x, y), true);
  626. if (newElem !== ogElemScroller) {
  627. ogElemScroller = newElem;
  628. _clearAutoScrolls();
  629. _autoScroll(evt, _this.options, ogElemScroller, fallback);
  630. }
  631. }, 10);
  632. lastPointerElemX = x;
  633. lastPointerElemY = y;
  634. }
  635. } else {
  636. // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll
  637. if (!_this.options.bubbleScroll || _getParentAutoScrollElement(elem, true) === _getWindowScrollingElement()) {
  638. _clearAutoScrolls();
  639. return;
  640. }
  641. _autoScroll(evt, _this.options, _getParentAutoScrollElement(elem, false), false);
  642. }
  643. },
  644. _prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target, /** Number */startIndex) {
  645. var _this = this,
  646. el = _this.el,
  647. options = _this.options,
  648. ownerDocument = el.ownerDocument,
  649. dragStartFn;
  650. if (target && !dragEl && (target.parentNode === el)) {
  651. rootEl = el;
  652. dragEl = target;
  653. parentEl = dragEl.parentNode;
  654. nextEl = dragEl.nextSibling;
  655. lastDownEl = target;
  656. activeGroup = options.group;
  657. oldIndex = startIndex;
  658. tapEvt = {
  659. target: dragEl,
  660. clientX: (touch || evt).clientX,
  661. clientY: (touch || evt).clientY
  662. };
  663. this._lastX = (touch || evt).clientX;
  664. this._lastY = (touch || evt).clientY;
  665. dragEl.style['will-change'] = 'all';
  666. // undo animation if needed
  667. dragEl.style.transition = '';
  668. dragEl.style.transform = '';
  669. dragStartFn = function () {
  670. // Delayed drag has been triggered
  671. // we can re-enable the events: touchmove/mousemove
  672. _this._disableDelayedDragEvents();
  673. if (!FireFox && _this.nativeDraggable) {
  674. dragEl.draggable = true;
  675. }
  676. // Bind the events: dragstart/dragend
  677. _this._triggerDragStart(evt, touch);
  678. // Drag start event
  679. _dispatchEvent(_this, rootEl, 'choose', dragEl, rootEl, rootEl, oldIndex);
  680. // Chosen item
  681. _toggleClass(dragEl, options.chosenClass, true);
  682. };
  683. // Disable "draggable"
  684. options.ignore.split(',').forEach(function (criteria) {
  685. _find(dragEl, criteria.trim(), _disableDraggable);
  686. });
  687. if (options.supportPointer) {
  688. _on(ownerDocument, 'pointerup', _this._onDrop);
  689. } else {
  690. _on(ownerDocument, 'mouseup', _this._onDrop);
  691. _on(ownerDocument, 'touchend', _this._onDrop);
  692. _on(ownerDocument, 'touchcancel', _this._onDrop);
  693. }
  694. // Make dragEl draggable (must be before delay for FireFox)
  695. if (FireFox && this.nativeDraggable) {
  696. this.options.touchStartThreshold = 4;
  697. dragEl.draggable = true;
  698. }
  699. // Delay is impossible for native DnD in Edge or IE
  700. if (options.delay && (!this.nativeDraggable || !(Edge || IE11OrLess))) {
  701. // If the user moves the pointer or let go the click or touch
  702. // before the delay has been reached:
  703. // disable the delayed drag
  704. _on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
  705. _on(ownerDocument, 'touchend', _this._disableDelayedDrag);
  706. _on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
  707. _on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler);
  708. _on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);
  709. options.supportPointer && _on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);
  710. _this._dragStartTimer = setTimeout(dragStartFn, options.delay);
  711. } else {
  712. dragStartFn();
  713. }
  714. }
  715. },
  716. _delayedDragTouchMoveHandler: function (/** TouchEvent|PointerEvent **/e) {
  717. var touch = e.touches ? e.touches[0] : e;
  718. if (max(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY))
  719. >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))
  720. ) {
  721. this._disableDelayedDrag();
  722. }
  723. },
  724. _disableDelayedDrag: function () {
  725. dragEl && _disableDraggable(dragEl);
  726. clearTimeout(this._dragStartTimer);
  727. this._disableDelayedDragEvents();
  728. },
  729. _disableDelayedDragEvents: function () {
  730. var ownerDocument = this.el.ownerDocument;
  731. _off(ownerDocument, 'mouseup', this._disableDelayedDrag);
  732. _off(ownerDocument, 'touchend', this._disableDelayedDrag);
  733. _off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
  734. _off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler);
  735. _off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler);
  736. _off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler);
  737. },
  738. _triggerDragStart: function (/** Event */evt, /** Touch */touch) {
  739. touch = touch || (evt.pointerType == 'touch' ? evt : null);
  740. if (!this.nativeDraggable || touch) {
  741. if (this.options.supportPointer) {
  742. _on(document, 'pointermove', this._onTouchMove);
  743. } else if (touch) {
  744. _on(document, 'touchmove', this._onTouchMove);
  745. } else {
  746. _on(document, 'mousemove', this._onTouchMove);
  747. }
  748. } else {
  749. _on(dragEl, 'dragend', this);
  750. _on(rootEl, 'dragstart', this._onDragStart);
  751. }
  752. try {
  753. if (document.selection) {
  754. // Timeout neccessary for IE9
  755. _nextTick(function () {
  756. document.selection.empty();
  757. });
  758. } else {
  759. window.getSelection().removeAllRanges();
  760. }
  761. } catch (err) {
  762. }
  763. },
  764. _dragStarted: function (fallback, evt) {
  765. awaitingDragStarted = false;
  766. if (rootEl && dragEl) {
  767. if (this.nativeDraggable) {
  768. _on(document, 'dragover', this._handleAutoScroll);
  769. _on(document, 'dragover', _checkAlignment);
  770. }
  771. var options = this.options;
  772. // Apply effect
  773. !fallback && _toggleClass(dragEl, options.dragClass, false);
  774. _toggleClass(dragEl, options.ghostClass, true);
  775. // In case dragging an animated element
  776. _css(dragEl, 'transform', '');
  777. Sortable.active = this;
  778. fallback && this._appendGhost();
  779. // Drag start event
  780. _dispatchEvent(this, rootEl, 'start', dragEl, rootEl, rootEl, oldIndex, undefined, evt);
  781. } else {
  782. this._nulling();
  783. }
  784. },
  785. _emulateDragOver: function (forAutoScroll) {
  786. if (touchEvt) {
  787. if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY && !forAutoScroll) {
  788. return;
  789. }
  790. this._lastX = touchEvt.clientX;
  791. this._lastY = touchEvt.clientY;
  792. _hideGhostForTarget();
  793. var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
  794. var parent = target;
  795. while (target && target.shadowRoot) {
  796. target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
  797. parent = target;
  798. }
  799. if (parent) {
  800. do {
  801. if (parent[expando]) {
  802. var inserted;
  803. inserted = parent[expando]._onDragOver({
  804. clientX: touchEvt.clientX,
  805. clientY: touchEvt.clientY,
  806. target: target,
  807. rootEl: parent
  808. });
  809. if (inserted && !this.options.dragoverBubble) {
  810. break;
  811. }
  812. }
  813. target = parent; // store last element
  814. }
  815. /* jshint boss:true */
  816. while (parent = parent.parentNode);
  817. }
  818. dragEl.parentNode[expando]._computeIsAligned(touchEvt);
  819. _unhideGhostForTarget();
  820. }
  821. },
  822. _onTouchMove: function (/**TouchEvent*/evt, forAutoScroll) {
  823. if (tapEvt) {
  824. var options = this.options,
  825. fallbackTolerance = options.fallbackTolerance,
  826. fallbackOffset = options.fallbackOffset,
  827. touch = evt.touches ? evt.touches[0] : evt,
  828. matrix = ghostEl && _matrix(ghostEl),
  829. scaleX = ghostEl && matrix && matrix.a,
  830. scaleY = ghostEl && matrix && matrix.d,
  831. relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && _getRelativeScrollOffset(ghostRelativeParent),
  832. dx = ((touch.clientX - tapEvt.clientX)
  833. + fallbackOffset.x) / (scaleX || 1)
  834. + (relativeScrollOffset ? (relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0]) : 0) / (scaleX || 1),
  835. dy = ((touch.clientY - tapEvt.clientY)
  836. + fallbackOffset.y) / (scaleY || 1)
  837. + (relativeScrollOffset ? (relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1]) : 0) / (scaleY || 1),
  838. translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)';
  839. // only set the status to dragging, when we are actually dragging
  840. if (!Sortable.active && !awaitingDragStarted) {
  841. if (fallbackTolerance &&
  842. min(abs(touch.clientX - this._lastX), abs(touch.clientY - this._lastY)) < fallbackTolerance
  843. ) {
  844. return;
  845. }
  846. this._onDragStart(evt, true);
  847. }
  848. !forAutoScroll && this._handleAutoScroll(touch, true);
  849. moved = true;
  850. touchEvt = touch;
  851. _css(ghostEl, 'webkitTransform', translate3d);
  852. _css(ghostEl, 'mozTransform', translate3d);
  853. _css(ghostEl, 'msTransform', translate3d);
  854. _css(ghostEl, 'transform', translate3d);
  855. evt.cancelable && evt.preventDefault();
  856. }
  857. },
  858. _appendGhost: function () {
  859. // Bug if using scale(): https://stackoverflow.com/questions/2637058
  860. // Not being adjusted for
  861. if (!ghostEl) {
  862. var container = this.options.fallbackOnBody ? document.body : rootEl,
  863. rect = _getRect(dragEl, true, container, !PositionGhostAbsolutely),
  864. css = _css(dragEl),
  865. options = this.options;
  866. // Position absolutely
  867. if (PositionGhostAbsolutely) {
  868. // Get relatively positioned parent
  869. ghostRelativeParent = container;
  870. while (
  871. _css(ghostRelativeParent, 'position') === 'static' &&
  872. _css(ghostRelativeParent, 'transform') === 'none' &&
  873. ghostRelativeParent !== document
  874. ) {
  875. ghostRelativeParent = ghostRelativeParent.parentNode;
  876. }
  877. if (ghostRelativeParent !== document) {
  878. var ghostRelativeParentRect = _getRect(ghostRelativeParent, true);
  879. rect.top -= ghostRelativeParentRect.top;
  880. rect.left -= ghostRelativeParentRect.left;
  881. }
  882. if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) {
  883. if (ghostRelativeParent === document) ghostRelativeParent = _getWindowScrollingElement();
  884. rect.top += ghostRelativeParent.scrollTop;
  885. rect.left += ghostRelativeParent.scrollLeft;
  886. } else {
  887. ghostRelativeParent = _getWindowScrollingElement();
  888. }
  889. ghostRelativeParentInitialScroll = _getRelativeScrollOffset(ghostRelativeParent);
  890. }
  891. ghostEl = dragEl.cloneNode(true);
  892. _toggleClass(ghostEl, options.ghostClass, false);
  893. _toggleClass(ghostEl, options.fallbackClass, true);
  894. _toggleClass(ghostEl, options.dragClass, true);
  895. _css(ghostEl, 'box-sizing', 'border-box');
  896. _css(ghostEl, 'margin', 0);
  897. _css(ghostEl, 'top', rect.top);
  898. _css(ghostEl, 'left', rect.left);
  899. _css(ghostEl, 'width', rect.width);
  900. _css(ghostEl, 'height', rect.height);
  901. _css(ghostEl, 'opacity', '0.8');
  902. _css(ghostEl, 'position', (PositionGhostAbsolutely ? 'absolute' : 'fixed'));
  903. _css(ghostEl, 'zIndex', '100000');
  904. _css(ghostEl, 'pointerEvents', 'none');
  905. container.appendChild(ghostEl);
  906. }
  907. },
  908. _onDragStart: function (/**Event*/evt, /**boolean*/fallback) {
  909. var _this = this;
  910. var dataTransfer = evt.dataTransfer;
  911. var options = _this.options;
  912. // Setup clone
  913. cloneEl = _clone(dragEl);
  914. cloneEl.draggable = false;
  915. cloneEl.style['will-change'] = '';
  916. this._hideClone();
  917. _toggleClass(cloneEl, _this.options.chosenClass, false);
  918. // #1143: IFrame support workaround
  919. _this._cloneId = _nextTick(function () {
  920. if (!_this.options.removeCloneOnHide) {
  921. rootEl.insertBefore(cloneEl, dragEl);
  922. }
  923. _dispatchEvent(_this, rootEl, 'clone', dragEl);
  924. });
  925. !fallback && _toggleClass(dragEl, options.dragClass, true);
  926. // Set proper drop events
  927. if (fallback) {
  928. ignoreNextClick = true;
  929. _this._loopId = setInterval(_this._emulateDragOver, 50);
  930. } else {
  931. // Undo what was set in _prepareDragStart before drag started
  932. _off(document, 'mouseup', _this._onDrop);
  933. _off(document, 'touchend', _this._onDrop);
  934. _off(document, 'touchcancel', _this._onDrop);
  935. if (dataTransfer) {
  936. dataTransfer.effectAllowed = 'move';
  937. options.setData && options.setData.call(_this, dataTransfer, dragEl);
  938. }
  939. _on(document, 'drop', _this);
  940. // #1276 fix:
  941. _css(dragEl, 'transform', 'translateZ(0)');
  942. }
  943. awaitingDragStarted = true;
  944. _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt));
  945. _on(document, 'selectstart', _this);
  946. if (Safari) {
  947. _css(document.body, 'user-select', 'none');
  948. }
  949. },
  950. // Returns true - if no further action is needed (either inserted or another condition)
  951. _onDragOver: function (/**Event*/evt) {
  952. var el = this.el,
  953. target = evt.target,
  954. dragRect,
  955. targetRect,
  956. revert,
  957. options = this.options,
  958. group = options.group,
  959. activeSortable = Sortable.active,
  960. isOwner = (activeGroup === group),
  961. canSort = options.sort,
  962. _this = this;
  963. if (_silent) return;
  964. // IE event order fix
  965. if (IE11OrLess && !evt.rootEl && !evt.artificialBubble && !_isTrueParentSortable(el, target)) {
  966. return;
  967. }
  968. // Return invocation when dragEl is inserted (or completed)
  969. function completed(insertion) {
  970. if (insertion) {
  971. if (isOwner) {
  972. activeSortable._hideClone();
  973. } else {
  974. activeSortable._showClone(_this);
  975. }
  976. if (activeSortable) {
  977. // Set ghost class to new sortable's ghost class
  978. _toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false);
  979. _toggleClass(dragEl, options.ghostClass, true);
  980. }
  981. if (putSortable !== _this && _this !== Sortable.active) {
  982. putSortable = _this;
  983. } else if (_this === Sortable.active) {
  984. putSortable = null;
  985. }
  986. // Animation
  987. dragRect && _this._animate(dragRect, dragEl);
  988. target && targetRect && _this._animate(targetRect, target);
  989. }
  990. // Null lastTarget if it is not inside a previously swapped element
  991. if ((target === dragEl && !dragEl.animated) || (target === el && !target.animated)) {
  992. lastTarget = null;
  993. }
  994. // no bubbling and not fallback
  995. if (!options.dragoverBubble && !evt.rootEl && target !== document) {
  996. _this._handleAutoScroll(evt);
  997. dragEl.parentNode[expando]._computeIsAligned(evt);
  998. }
  999. !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation();
  1000. return true;
  1001. }
  1002. // Call when dragEl has been inserted
  1003. function changed() {
  1004. _dispatchEvent(_this, rootEl, 'change', target, el, rootEl, oldIndex, _index(dragEl, options.draggable), evt);
  1005. }
  1006. if (evt.preventDefault !== void 0) {
  1007. evt.cancelable && evt.preventDefault();
  1008. }
  1009. moved = true;
  1010. target = _closest(target, options.draggable, el, true);
  1011. // target is dragEl or target is animated
  1012. if (!!_closest(evt.target, null, dragEl, true) || target.animated) {
  1013. return completed(false);
  1014. }
  1015. if (target !== dragEl) {
  1016. ignoreNextClick = false;
  1017. }
  1018. if (activeSortable && !options.disabled &&
  1019. (isOwner
  1020. ? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list
  1021. : (
  1022. putSortable === this ||
  1023. (
  1024. (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) &&
  1025. group.checkPut(this, activeSortable, dragEl, evt)
  1026. )
  1027. )
  1028. )
  1029. ) {
  1030. var axis = this._getDirection(evt, target);
  1031. dragRect = _getRect(dragEl);
  1032. if (revert) {
  1033. this._hideClone();
  1034. parentEl = rootEl; // actualization
  1035. if (nextEl) {
  1036. rootEl.insertBefore(dragEl, nextEl);
  1037. } else {
  1038. rootEl.appendChild(dragEl);
  1039. }
  1040. return completed(true);
  1041. }
  1042. var elLastChild = _lastChild(el);
  1043. if (!elLastChild || _ghostIsLast(evt, axis, el) && !elLastChild.animated) {
  1044. // assign target only if condition is true
  1045. if (elLastChild && el === evt.target) {
  1046. target = elLastChild;
  1047. }
  1048. if (target) {
  1049. targetRect = _getRect(target);
  1050. }
  1051. if (isOwner) {
  1052. activeSortable._hideClone();
  1053. } else {
  1054. activeSortable._showClone(this);
  1055. }
  1056. if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) {
  1057. el.appendChild(dragEl);
  1058. parentEl = el; // actualization
  1059. realDragElRect = null;
  1060. changed();
  1061. return completed(true);
  1062. }
  1063. }
  1064. else if (target && target !== dragEl && target.parentNode === el) {
  1065. var direction = 0,
  1066. targetBeforeFirstSwap,
  1067. aligned = target.sortableMouseAligned,
  1068. differentLevel = dragEl.parentNode !== el,
  1069. side1 = axis === 'vertical' ? 'top' : 'left',
  1070. scrolledPastTop = _isScrolledPast(target, 'top') || _isScrolledPast(dragEl, 'top'),
  1071. scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0;
  1072. if (lastTarget !== target) {
  1073. lastMode = null;
  1074. targetBeforeFirstSwap = _getRect(target)[side1];
  1075. pastFirstInvertThresh = false;
  1076. }
  1077. // Reference: https://www.lucidchart.com/documents/view/10fa0e93-e362-4126-aca2-b709ee56bd8b/0
  1078. if (
  1079. _isElInRowColumn(dragEl, target, axis) && aligned ||
  1080. differentLevel ||
  1081. scrolledPastTop ||
  1082. options.invertSwap ||
  1083. lastMode === 'insert' ||
  1084. // Needed, in the case that we are inside target and inserted because not aligned... aligned will stay false while inside
  1085. // and lastMode will change to 'insert', but we must swap
  1086. lastMode === 'swap'
  1087. ) {
  1088. // New target that we will be inside
  1089. if (lastMode !== 'swap') {
  1090. isCircumstantialInvert = options.invertSwap || differentLevel;
  1091. }
  1092. direction = _getSwapDirection(evt, target, axis,
  1093. options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold,
  1094. isCircumstantialInvert,
  1095. lastTarget === target);
  1096. lastMode = 'swap';
  1097. } else {
  1098. // Insert at position
  1099. direction = _getInsertDirection(target);
  1100. lastMode = 'insert';
  1101. }
  1102. if (direction === 0) return completed(false);
  1103. realDragElRect = null;
  1104. lastTarget = target;
  1105. lastDirection = direction;
  1106. targetRect = _getRect(target);
  1107. var nextSibling = target.nextElementSibling,
  1108. after = false;
  1109. after = direction === 1;
  1110. var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);
  1111. if (moveVector !== false) {
  1112. if (moveVector === 1 || moveVector === -1) {
  1113. after = (moveVector === 1);
  1114. }
  1115. _silent = true;
  1116. setTimeout(_unsilent, 30);
  1117. if (isOwner) {
  1118. activeSortable._hideClone();
  1119. } else {
  1120. activeSortable._showClone(this);
  1121. }
  1122. if (after && !nextSibling) {
  1123. el.appendChild(dragEl);
  1124. } else {
  1125. target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
  1126. }
  1127. // Undo chrome's scroll adjustment
  1128. if (scrolledPastTop) {
  1129. _scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop);
  1130. }
  1131. parentEl = dragEl.parentNode; // actualization
  1132. // must be done before animation
  1133. if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) {
  1134. targetMoveDistance = abs(targetBeforeFirstSwap - _getRect(target)[side1]);
  1135. }
  1136. changed();
  1137. return completed(true);
  1138. }
  1139. }
  1140. if (el.contains(dragEl)) {
  1141. return completed(false);
  1142. }
  1143. }
  1144. if (IE11OrLess && !evt.rootEl) {
  1145. _artificalBubble(el, evt, '_onDragOver');
  1146. }
  1147. return false;
  1148. },
  1149. _animate: function (prevRect, target) {
  1150. var ms = this.options.animation;
  1151. if (ms) {
  1152. var currentRect = _getRect(target);
  1153. if (target === dragEl) {
  1154. realDragElRect = currentRect;
  1155. }
  1156. if (prevRect.nodeType === 1) {
  1157. prevRect = _getRect(prevRect);
  1158. }
  1159. // Check if actually moving position
  1160. if ((prevRect.left + prevRect.width / 2) !== (currentRect.left + currentRect.width / 2)
  1161. || (prevRect.top + prevRect.height / 2) !== (currentRect.top + currentRect.height / 2)
  1162. ) {
  1163. var matrix = _matrix(this.el),
  1164. scaleX = matrix && matrix.a,
  1165. scaleY = matrix && matrix.d;
  1166. _css(target, 'transition', 'none');
  1167. _css(target, 'transform', 'translate3d('
  1168. + (prevRect.left - currentRect.left) / (scaleX ? scaleX : 1) + 'px,'
  1169. + (prevRect.top - currentRect.top) / (scaleY ? scaleY : 1) + 'px,0)'
  1170. );
  1171. forRepaintDummy = target.offsetWidth; // repaint
  1172. _css(target, 'transition', 'transform ' + ms + 'ms' + (this.options.easing ? ' ' + this.options.easing : ''));
  1173. _css(target, 'transform', 'translate3d(0,0,0)');
  1174. }
  1175. (typeof target.animated === 'number') && clearTimeout(target.animated);
  1176. target.animated = setTimeout(function () {
  1177. _css(target, 'transition', '');
  1178. _css(target, 'transform', '');
  1179. target.animated = false;
  1180. }, ms);
  1181. }
  1182. },
  1183. _offUpEvents: function () {
  1184. var ownerDocument = this.el.ownerDocument;
  1185. _off(document, 'touchmove', this._onTouchMove);
  1186. _off(document, 'pointermove', this._onTouchMove);
  1187. _off(ownerDocument, 'mouseup', this._onDrop);
  1188. _off(ownerDocument, 'touchend', this._onDrop);
  1189. _off(ownerDocument, 'pointerup', this._onDrop);
  1190. _off(ownerDocument, 'touchcancel', this._onDrop);
  1191. _off(document, 'selectstart', this);
  1192. },
  1193. _onDrop: function (/**Event*/evt) {
  1194. var el = this.el,
  1195. options = this.options;
  1196. awaitingDragStarted = false;
  1197. scrolling = false;
  1198. isCircumstantialInvert = false;
  1199. pastFirstInvertThresh = false;
  1200. clearInterval(this._loopId);
  1201. clearInterval(pointerElemChangedInterval);
  1202. _clearAutoScrolls();
  1203. _cancelThrottle();
  1204. clearTimeout(this._dragStartTimer);
  1205. _cancelNextTick(this._cloneId);
  1206. _cancelNextTick(this._dragStartId);
  1207. // Unbind events
  1208. _off(document, 'mousemove', this._onTouchMove);
  1209. if (this.nativeDraggable) {
  1210. _off(document, 'drop', this);
  1211. _off(el, 'dragstart', this._onDragStart);
  1212. _off(document, 'dragover', this._handleAutoScroll);
  1213. _off(document, 'dragover', _checkAlignment);
  1214. }
  1215. if (Safari) {
  1216. _css(document.body, 'user-select', '');
  1217. }
  1218. this._offUpEvents();
  1219. if (evt) {
  1220. if (moved) {
  1221. evt.cancelable && evt.preventDefault();
  1222. !options.dropBubble && evt.stopPropagation();
  1223. }
  1224. ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);
  1225. if (rootEl === parentEl || (putSortable && putSortable.lastPutMode !== 'clone')) {
  1226. // Remove clone
  1227. cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);
  1228. }
  1229. if (dragEl) {
  1230. if (this.nativeDraggable) {
  1231. _off(dragEl, 'dragend', this);
  1232. }
  1233. _disableDraggable(dragEl);
  1234. dragEl.style['will-change'] = '';
  1235. // Remove class's
  1236. _toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false);
  1237. _toggleClass(dragEl, this.options.chosenClass, false);
  1238. // Drag stop event
  1239. _dispatchEvent(this, rootEl, 'unchoose', dragEl, parentEl, rootEl, oldIndex, null, evt);
  1240. if (rootEl !== parentEl) {
  1241. newIndex = _index(dragEl, options.draggable);
  1242. if (newIndex >= 0) {
  1243. // Add event
  1244. _dispatchEvent(null, parentEl, 'add', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
  1245. // Remove event
  1246. _dispatchEvent(this, rootEl, 'remove', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
  1247. // drag from one list and drop into another
  1248. _dispatchEvent(null, parentEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
  1249. _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
  1250. }
  1251. putSortable && putSortable.save();
  1252. }
  1253. else {
  1254. if (dragEl.nextSibling !== nextEl) {
  1255. // Get the index of the dragged element within its parent
  1256. newIndex = _index(dragEl, options.draggable);
  1257. if (newIndex >= 0) {
  1258. // drag & drop within the same list
  1259. _dispatchEvent(this, rootEl, 'update', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
  1260. _dispatchEvent(this, rootEl, 'sort', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
  1261. }
  1262. }
  1263. }
  1264. if (Sortable.active) {
  1265. /* jshint eqnull:true */
  1266. if (newIndex == null || newIndex === -1) {
  1267. newIndex = oldIndex;
  1268. }
  1269. _dispatchEvent(this, rootEl, 'end', dragEl, parentEl, rootEl, oldIndex, newIndex, evt);
  1270. // Save sorting
  1271. this.save();
  1272. }
  1273. }
  1274. }
  1275. this._nulling();
  1276. },
  1277. _nulling: function() {
  1278. rootEl =
  1279. dragEl =
  1280. parentEl =
  1281. ghostEl =
  1282. nextEl =
  1283. cloneEl =
  1284. lastDownEl =
  1285. scrollEl =
  1286. scrollParentEl =
  1287. autoScrolls.length =
  1288. pointerElemChangedInterval =
  1289. lastPointerElemX =
  1290. lastPointerElemY =
  1291. tapEvt =
  1292. touchEvt =
  1293. moved =
  1294. newIndex =
  1295. oldIndex =
  1296. lastTarget =
  1297. lastDirection =
  1298. forRepaintDummy =
  1299. realDragElRect =
  1300. putSortable =
  1301. activeGroup =
  1302. Sortable.active = null;
  1303. savedInputChecked.forEach(function (el) {
  1304. el.checked = true;
  1305. });
  1306. savedInputChecked.length = 0;
  1307. },
  1308. handleEvent: function (/**Event*/evt) {
  1309. switch (evt.type) {
  1310. case 'drop':
  1311. case 'dragend':
  1312. this._onDrop(evt);
  1313. break;
  1314. case 'dragenter':
  1315. case 'dragover':
  1316. if (dragEl) {
  1317. this._onDragOver(evt);
  1318. _globalDragOver(evt);
  1319. }
  1320. break;
  1321. case 'selectstart':
  1322. evt.preventDefault();
  1323. break;
  1324. }
  1325. },
  1326. /**
  1327. * Serializes the item into an array of string.
  1328. * @returns {String[]}
  1329. */
  1330. toArray: function () {
  1331. var order = [],
  1332. el,
  1333. children = this.el.children,
  1334. i = 0,
  1335. n = children.length,
  1336. options = this.options;
  1337. for (; i < n; i++) {
  1338. el = children[i];
  1339. if (_closest(el, options.draggable, this.el, false)) {
  1340. order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
  1341. }
  1342. }
  1343. return order;
  1344. },
  1345. /**
  1346. * Sorts the elements according to the array.
  1347. * @param {String[]} order order of the items
  1348. */
  1349. sort: function (order) {
  1350. var items = {}, rootEl = this.el;
  1351. this.toArray().forEach(function (id, i) {
  1352. var el = rootEl.children[i];
  1353. if (_closest(el, this.options.draggable, rootEl, false)) {
  1354. items[id] = el;
  1355. }
  1356. }, this);
  1357. order.forEach(function (id) {
  1358. if (items[id]) {
  1359. rootEl.removeChild(items[id]);
  1360. rootEl.appendChild(items[id]);
  1361. }
  1362. });
  1363. },
  1364. /**
  1365. * Save the current sorting
  1366. */
  1367. save: function () {
  1368. var store = this.options.store;
  1369. store && store.set && store.set(this);
  1370. },
  1371. /**
  1372. * 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.
  1373. * @param {HTMLElement} el
  1374. * @param {String} [selector] default: `options.draggable`
  1375. * @returns {HTMLElement|null}
  1376. */
  1377. closest: function (el, selector) {
  1378. return _closest(el, selector || this.options.draggable, this.el, false);
  1379. },
  1380. /**
  1381. * Set/get option
  1382. * @param {string} name
  1383. * @param {*} [value]
  1384. * @returns {*}
  1385. */
  1386. option: function (name, value) {
  1387. var options = this.options;
  1388. if (value === void 0) {
  1389. return options[name];
  1390. } else {
  1391. options[name] = value;
  1392. if (name === 'group') {
  1393. _prepareGroup(options);
  1394. }
  1395. }
  1396. },
  1397. /**
  1398. * Destroy
  1399. */
  1400. destroy: function () {
  1401. var el = this.el;
  1402. el[expando] = null;
  1403. _off(el, 'mousedown', this._onTapStart);
  1404. _off(el, 'touchstart', this._onTapStart);
  1405. _off(el, 'pointerdown', this._onTapStart);
  1406. if (this.nativeDraggable) {
  1407. _off(el, 'dragover', this);
  1408. _off(el, 'dragenter', this);
  1409. }
  1410. // Remove draggable attributes
  1411. Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
  1412. el.removeAttribute('draggable');
  1413. });
  1414. this._onDrop();
  1415. sortables.splice(sortables.indexOf(this.el), 1);
  1416. this.el = el = null;
  1417. },
  1418. _hideClone: function() {
  1419. if (!cloneEl.cloneHidden) {
  1420. _css(cloneEl, 'display', 'none');
  1421. cloneEl.cloneHidden = true;
  1422. if (cloneEl.parentNode && this.options.removeCloneOnHide) {
  1423. cloneEl.parentNode.removeChild(cloneEl);
  1424. }
  1425. }
  1426. },
  1427. _showClone: function(putSortable) {
  1428. if (putSortable.lastPutMode !== 'clone') {
  1429. this._hideClone();
  1430. return;
  1431. }
  1432. if (cloneEl.cloneHidden) {
  1433. // show clone at dragEl or original position
  1434. if (rootEl.contains(dragEl) && !this.options.group.revertClone) {
  1435. rootEl.insertBefore(cloneEl, dragEl);
  1436. } else if (nextEl) {
  1437. rootEl.insertBefore(cloneEl, nextEl);
  1438. } else {
  1439. rootEl.appendChild(cloneEl);
  1440. }
  1441. if (this.options.group.revertClone) {
  1442. this._animate(dragEl, cloneEl);
  1443. }
  1444. _css(cloneEl, 'display', '');
  1445. cloneEl.cloneHidden = false;
  1446. }
  1447. }
  1448. };
  1449. function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx, includeCTX) {
  1450. if (el) {
  1451. ctx = ctx || document;
  1452. do {
  1453. if (
  1454. selector != null &&
  1455. (
  1456. selector[0] === '>' && el.parentNode === ctx && _matches(el, selector.substring(1)) ||
  1457. _matches(el, selector)
  1458. ) ||
  1459. includeCTX && el === ctx
  1460. ) {
  1461. return el;
  1462. }
  1463. if (el === ctx) break;
  1464. /* jshint boss:true */
  1465. } while (el = _getParentOrHost(el));
  1466. }
  1467. return null;
  1468. }
  1469. function _getParentOrHost(el) {
  1470. return (el.host && el !== document && el.host.nodeType)
  1471. ? el.host
  1472. : el.parentNode;
  1473. }
  1474. function _globalDragOver(/**Event*/evt) {
  1475. if (evt.dataTransfer) {
  1476. evt.dataTransfer.dropEffect = 'move';
  1477. }
  1478. evt.cancelable && evt.preventDefault();
  1479. }
  1480. function _on(el, event, fn) {
  1481. el.addEventListener(event, fn, captureMode);
  1482. }
  1483. function _off(el, event, fn) {
  1484. el.removeEventListener(event, fn, captureMode);
  1485. }
  1486. function _toggleClass(el, name, state) {
  1487. if (el && name) {
  1488. if (el.classList) {
  1489. el.classList[state ? 'add' : 'remove'](name);
  1490. }
  1491. else {
  1492. var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');
  1493. el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');
  1494. }
  1495. }
  1496. }
  1497. function _css(el, prop, val) {
  1498. var style = el && el.style;
  1499. if (style) {
  1500. if (val === void 0) {
  1501. if (document.defaultView && document.defaultView.getComputedStyle) {
  1502. val = document.defaultView.getComputedStyle(el, '');
  1503. }
  1504. else if (el.currentStyle) {
  1505. val = el.currentStyle;
  1506. }
  1507. return prop === void 0 ? val : val[prop];
  1508. }
  1509. else {
  1510. if (!(prop in style) && prop.indexOf('webkit') === -1) {
  1511. prop = '-webkit-' + prop;
  1512. }
  1513. style[prop] = val + (typeof val === 'string' ? '' : 'px');
  1514. }
  1515. }
  1516. }
  1517. function _matrix(el) {
  1518. var appliedTransforms = '';
  1519. do {
  1520. var transform = _css(el, 'transform');
  1521. if (transform && transform !== 'none') {
  1522. appliedTransforms = transform + ' ' + appliedTransforms;
  1523. }
  1524. /* jshint boss:true */
  1525. } while (el = el.parentNode);
  1526. if (window.DOMMatrix) {
  1527. return new DOMMatrix(appliedTransforms);
  1528. } else if (window.WebKitCSSMatrix) {
  1529. return new WebKitCSSMatrix(appliedTransforms);
  1530. } else if (window.CSSMatrix) {
  1531. return new CSSMatrix(appliedTransforms);
  1532. }
  1533. }
  1534. function _find(ctx, tagName, iterator) {
  1535. if (ctx) {
  1536. var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
  1537. if (iterator) {
  1538. for (; i < n; i++) {
  1539. iterator(list[i], i);
  1540. }
  1541. }
  1542. return list;
  1543. }
  1544. return [];
  1545. }
  1546. function _dispatchEvent(sortable, rootEl, name, targetEl, toEl, fromEl, startIndex, newIndex, originalEvt) {
  1547. sortable = (sortable || rootEl[expando]);
  1548. var evt,
  1549. options = sortable.options,
  1550. onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);
  1551. // Support for new CustomEvent feature
  1552. if (window.CustomEvent && !IE11OrLess && !Edge) {
  1553. evt = new CustomEvent(name, {
  1554. bubbles: true,
  1555. cancelable: true
  1556. });
  1557. } else {
  1558. evt = document.createEvent('Event');
  1559. evt.initEvent(name, true, true);
  1560. }
  1561. evt.to = toEl || rootEl;
  1562. evt.from = fromEl || rootEl;
  1563. evt.item = targetEl || rootEl;
  1564. evt.clone = cloneEl;
  1565. evt.oldIndex = startIndex;
  1566. evt.newIndex = newIndex;
  1567. evt.originalEvent = originalEvt;
  1568. evt.pullMode = putSortable ? putSortable.lastPutMode : undefined;
  1569. if (rootEl) {
  1570. rootEl.dispatchEvent(evt);
  1571. }
  1572. if (options[onName]) {
  1573. options[onName].call(sortable, evt);
  1574. }
  1575. }
  1576. function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvt, willInsertAfter) {
  1577. var evt,
  1578. sortable = fromEl[expando],
  1579. onMoveFn = sortable.options.onMove,
  1580. retVal;
  1581. // Support for new CustomEvent feature
  1582. if (window.CustomEvent && !IE11OrLess && !Edge) {
  1583. evt = new CustomEvent('move', {
  1584. bubbles: true,
  1585. cancelable: true
  1586. });
  1587. } else {
  1588. evt = document.createEvent('Event');
  1589. evt.initEvent('move', true, true);
  1590. }
  1591. evt.to = toEl;
  1592. evt.from = fromEl;
  1593. evt.dragged = dragEl;
  1594. evt.draggedRect = dragRect;
  1595. evt.related = targetEl || toEl;
  1596. evt.relatedRect = targetRect || _getRect(toEl);
  1597. evt.willInsertAfter = willInsertAfter;
  1598. evt.originalEvent = originalEvt;
  1599. fromEl.dispatchEvent(evt);
  1600. if (onMoveFn) {
  1601. retVal = onMoveFn.call(sortable, evt, originalEvt);
  1602. }
  1603. return retVal;
  1604. }
  1605. function _disableDraggable(el) {
  1606. el.draggable = false;
  1607. }
  1608. function _unsilent() {
  1609. _silent = false;
  1610. }
  1611. /**
  1612. * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible)
  1613. * and non-draggable elements
  1614. * @param {HTMLElement} el The parent element
  1615. * @param {Number} childNum The index of the child
  1616. * @param {Object} options Parent Sortable's options
  1617. * @return {HTMLElement} The child at index childNum, or null if not found
  1618. */
  1619. function _getChild(el, childNum, options) {
  1620. var currentChild = 0,
  1621. i = 0,
  1622. children = el.children;
  1623. while (i < children.length) {
  1624. if (
  1625. children[i].style.display !== 'none' &&
  1626. children[i] !== ghostEl &&
  1627. children[i] !== dragEl &&
  1628. _closest(children[i], options.draggable, el, false)
  1629. ) {
  1630. if (currentChild === childNum) {
  1631. return children[i];
  1632. }
  1633. currentChild++;
  1634. }
  1635. i++;
  1636. }
  1637. return null;
  1638. }
  1639. /**
  1640. * Gets the last child in the el, ignoring ghostEl or invisible elements (clones)
  1641. * @param {HTMLElement} el Parent element
  1642. * @return {HTMLElement} The last child, ignoring ghostEl
  1643. */
  1644. function _lastChild(el) {
  1645. var last = el.lastElementChild;
  1646. while (last && (last === ghostEl || last.style.display === 'none')) {
  1647. last = last.previousElementSibling;
  1648. }
  1649. return last || null;
  1650. }
  1651. function _ghostIsLast(evt, axis, el) {
  1652. var elRect = _getRect(_lastChild(el)),
  1653. mouseOnAxis = axis === 'vertical' ? evt.clientY : evt.clientX,
  1654. mouseOnOppAxis = axis === 'vertical' ? evt.clientX : evt.clientY,
  1655. targetS2 = axis === 'vertical' ? elRect.bottom : elRect.right,
  1656. targetS1Opp = axis === 'vertical' ? elRect.left : elRect.top,
  1657. targetS2Opp = axis === 'vertical' ? elRect.right : elRect.bottom,
  1658. spacer = 10;
  1659. return (
  1660. axis === 'vertical' ?
  1661. (mouseOnOppAxis > targetS2Opp + spacer || mouseOnOppAxis <= targetS2Opp && mouseOnAxis > targetS2 && mouseOnOppAxis >= targetS1Opp) :
  1662. (mouseOnAxis > targetS2 && mouseOnOppAxis > targetS1Opp || mouseOnAxis <= targetS2 && mouseOnOppAxis > targetS2Opp + spacer)
  1663. );
  1664. }
  1665. function _getSwapDirection(evt, target, axis, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) {
  1666. var targetRect = _getRect(target),
  1667. mouseOnAxis = axis === 'vertical' ? evt.clientY : evt.clientX,
  1668. targetLength = axis === 'vertical' ? targetRect.height : targetRect.width,
  1669. targetS1 = axis === 'vertical' ? targetRect.top : targetRect.left,
  1670. targetS2 = axis === 'vertical' ? targetRect.bottom : targetRect.right,
  1671. dragRect = _getRect(dragEl),
  1672. invert = false;
  1673. if (!invertSwap) {
  1674. // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold
  1675. if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) { // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2
  1676. // check if past first invert threshold on side opposite of lastDirection
  1677. if (!pastFirstInvertThresh &&
  1678. (lastDirection === 1 ?
  1679. (
  1680. mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2
  1681. ) :
  1682. (
  1683. mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2
  1684. )
  1685. )
  1686. )
  1687. {
  1688. // past first invert threshold, do not restrict inverted threshold to dragEl shadow
  1689. pastFirstInvertThresh = true;
  1690. }
  1691. if (!pastFirstInvertThresh) {
  1692. var dragS1 = axis === 'vertical' ? dragRect.top : dragRect.left,
  1693. dragS2 = axis === 'vertical' ? dragRect.bottom : dragRect.right;
  1694. // dragEl shadow (target move distance shadow)
  1695. if (
  1696. lastDirection === 1 ?
  1697. (
  1698. mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow
  1699. ) :
  1700. (
  1701. mouseOnAxis > targetS2 - targetMoveDistance
  1702. )
  1703. )
  1704. {
  1705. return lastDirection * -1;
  1706. }
  1707. } else {
  1708. invert = true;
  1709. }
  1710. } else {
  1711. // Regular
  1712. if (
  1713. mouseOnAxis > targetS1 + (targetLength * (1 - swapThreshold) / 2) &&
  1714. mouseOnAxis < targetS2 - (targetLength * (1 - swapThreshold) / 2)
  1715. ) {
  1716. return _getInsertDirection(target);
  1717. }
  1718. }
  1719. }
  1720. invert = invert || invertSwap;
  1721. if (invert) {
  1722. // Invert of regular
  1723. if (
  1724. mouseOnAxis < targetS1 + (targetLength * invertedSwapThreshold / 2) ||
  1725. mouseOnAxis > targetS2 - (targetLength * invertedSwapThreshold / 2)
  1726. )
  1727. {
  1728. return ((mouseOnAxis > targetS1 + targetLength / 2) ? 1 : -1);
  1729. }
  1730. }
  1731. return 0;
  1732. }
  1733. /**
  1734. * Gets the direction dragEl must be swapped relative to target in order to make it
  1735. * seem that dragEl has been "inserted" into that element's position
  1736. * @param {HTMLElement} target The target whose position dragEl is being inserted at
  1737. * @return {Number} Direction dragEl must be swapped
  1738. */
  1739. function _getInsertDirection(target) {
  1740. var dragElIndex = _index(dragEl),
  1741. targetIndex = _index(target);
  1742. if (dragElIndex < targetIndex) {
  1743. return 1;
  1744. } else {
  1745. return -1;
  1746. }
  1747. }
  1748. /**
  1749. * Generate id
  1750. * @param {HTMLElement} el
  1751. * @returns {String}
  1752. * @private
  1753. */
  1754. function _generateId(el) {
  1755. var str = el.tagName + el.className + el.src + el.href + el.textContent,
  1756. i = str.length,
  1757. sum = 0;
  1758. while (i--) {
  1759. sum += str.charCodeAt(i);
  1760. }
  1761. return sum.toString(36);
  1762. }
  1763. /**
  1764. * Returns the index of an element within its parent for a selected set of
  1765. * elements
  1766. * @param {HTMLElement} el
  1767. * @param {selector} selector
  1768. * @return {number}
  1769. */
  1770. function _index(el, selector) {
  1771. var index = 0;
  1772. if (!el || !el.parentNode) {
  1773. return -1;
  1774. }
  1775. while (el && (el = el.previousElementSibling)) {
  1776. if ((el.nodeName.toUpperCase() !== 'TEMPLATE') && el !== cloneEl) {
  1777. index++;
  1778. }
  1779. }
  1780. return index;
  1781. }
  1782. function _matches(/**HTMLElement*/el, /**String*/selector) {
  1783. if (el) {
  1784. try {
  1785. if (el.matches) {
  1786. return el.matches(selector);
  1787. } else if (el.msMatchesSelector) {
  1788. return el.msMatchesSelector(selector);
  1789. } else if (el.webkitMatchesSelector) {
  1790. return el.webkitMatchesSelector(selector);
  1791. }
  1792. } catch(_) {
  1793. return false;
  1794. }
  1795. }
  1796. return false;
  1797. }
  1798. var _throttleTimeout;
  1799. function _throttle(callback, ms) {
  1800. return function () {
  1801. if (!_throttleTimeout) {
  1802. var args = arguments,
  1803. _this = this;
  1804. _throttleTimeout = setTimeout(function () {
  1805. if (args.length === 1) {
  1806. callback.call(_this, args[0]);
  1807. } else {
  1808. callback.apply(_this, args);
  1809. }
  1810. _throttleTimeout = void 0;
  1811. }, ms);
  1812. }
  1813. };
  1814. }
  1815. function _cancelThrottle() {
  1816. clearTimeout(_throttleTimeout);
  1817. _throttleTimeout = void 0;
  1818. }
  1819. function _extend(dst, src) {
  1820. if (dst && src) {
  1821. for (var key in src) {
  1822. if (src.hasOwnProperty(key)) {
  1823. dst[key] = src[key];
  1824. }
  1825. }
  1826. }
  1827. return dst;
  1828. }
  1829. function _clone(el) {
  1830. if (Polymer && Polymer.dom) {
  1831. return Polymer.dom(el).cloneNode(true);
  1832. }
  1833. else if ($) {
  1834. return $(el).clone(true)[0];
  1835. }
  1836. else {
  1837. return el.cloneNode(true);
  1838. }
  1839. }
  1840. function _saveInputCheckedState(root) {
  1841. savedInputChecked.length = 0;
  1842. var inputs = root.getElementsByTagName('input');
  1843. var idx = inputs.length;
  1844. while (idx--) {
  1845. var el = inputs[idx];
  1846. el.checked && savedInputChecked.push(el);
  1847. }
  1848. }
  1849. function _nextTick(fn) {
  1850. return setTimeout(fn, 0);
  1851. }
  1852. function _cancelNextTick(id) {
  1853. return clearTimeout(id);
  1854. }
  1855. /**
  1856. * Returns the "bounding client rect" of given element
  1857. * @param {HTMLElement} el The element whose boundingClientRect is wanted
  1858. * @param {[HTMLElement]} container the parent the element will be placed in
  1859. * @param {[Boolean]} adjustForTransform Whether the rect should compensate for parent's transform
  1860. * @return {Object} The boundingClientRect of el
  1861. */
  1862. function _getRect(el, adjustForTransform, container, adjustForFixed) {
  1863. if (!el.getBoundingClientRect && el !== win) return;
  1864. var elRect,
  1865. top,
  1866. left,
  1867. bottom,
  1868. right,
  1869. height,
  1870. width;
  1871. if (el !== win && el !== _getWindowScrollingElement()) {
  1872. elRect = el.getBoundingClientRect();
  1873. top = elRect.top;
  1874. left = elRect.left;
  1875. bottom = elRect.bottom;
  1876. right = elRect.right;
  1877. height = elRect.height;
  1878. width = elRect.width;
  1879. } else {
  1880. top = 0;
  1881. left = 0;
  1882. bottom = window.innerHeight;
  1883. right = window.innerWidth;
  1884. height = window.innerHeight;
  1885. width = window.innerWidth;
  1886. }
  1887. if (adjustForFixed && el !== win) {
  1888. // Adjust for translate()
  1889. container = container || el.parentNode;
  1890. // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312)
  1891. // Not needed on <= IE11
  1892. if (!IE11OrLess) {
  1893. do {
  1894. if (container && container.getBoundingClientRect && _css(container, 'transform') !== 'none') {
  1895. var containerRect = container.getBoundingClientRect();
  1896. // Set relative to edges of padding box of container
  1897. top -= containerRect.top + parseInt(_css(container, 'border-top-width'));
  1898. left -= containerRect.left + parseInt(_css(container, 'border-left-width'));
  1899. bottom = top + elRect.height;
  1900. right = left + elRect.width;
  1901. break;
  1902. }
  1903. /* jshint boss:true */
  1904. } while (container = container.parentNode);
  1905. }
  1906. }
  1907. if (adjustForTransform && el !== win) {
  1908. // Adjust for scale()
  1909. var matrix = _matrix(container || el),
  1910. scaleX = matrix && matrix.a,
  1911. scaleY = matrix && matrix.d;
  1912. if (matrix) {
  1913. top /= scaleY;
  1914. left /= scaleX;
  1915. width /= scaleX;
  1916. height /= scaleY;
  1917. bottom = top + height;
  1918. right = left + width;
  1919. }
  1920. }
  1921. return {
  1922. top: top,
  1923. left: left,
  1924. bottom: bottom,
  1925. right: right,
  1926. width: width,
  1927. height: height
  1928. };
  1929. }
  1930. /**
  1931. * Checks if a side of an element is scrolled past a side of it's parents
  1932. * @param {HTMLElement} el The element who's side being scrolled out of view is in question
  1933. * @param {String} side Side of the element in question ('top', 'left', 'right', 'bottom')
  1934. * @return {HTMLElement} The parent scroll element that the el's side is scrolled past, or null if there is no such element
  1935. */
  1936. function _isScrolledPast(el, side) {
  1937. var parent = _getParentAutoScrollElement(el, true),
  1938. elSide = _getRect(el)[side];
  1939. /* jshint boss:true */
  1940. while (parent) {
  1941. var parentSide = _getRect(parent)[side],
  1942. visible;
  1943. if (side === 'top' || side === 'left') {
  1944. visible = elSide >= parentSide;
  1945. } else {
  1946. visible = elSide <= parentSide;
  1947. }
  1948. if (!visible) return parent;
  1949. if (parent === _getWindowScrollingElement()) break;
  1950. parent = _getParentAutoScrollElement(parent, false);
  1951. }
  1952. return false;
  1953. }
  1954. /**
  1955. * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements.
  1956. * The value is returned in real pixels.
  1957. * @param {HTMLElement} el
  1958. * @return {Array} Offsets in the format of [left, top]
  1959. */
  1960. function _getRelativeScrollOffset(el) {
  1961. var offsetLeft = 0,
  1962. offsetTop = 0,
  1963. winScroller = _getWindowScrollingElement();
  1964. if (el) {
  1965. do {
  1966. var matrix = _matrix(el),
  1967. scaleX = matrix.a,
  1968. scaleY = matrix.d;
  1969. offsetLeft += el.scrollLeft * scaleX;
  1970. offsetTop += el.scrollTop * scaleY;
  1971. } while (el !== winScroller && (el = el.parentNode));
  1972. }
  1973. return [offsetLeft, offsetTop];
  1974. }
  1975. // Fixed #973:
  1976. _on(document, 'touchmove', function(evt) {
  1977. if ((Sortable.active || awaitingDragStarted) && evt.cancelable) {
  1978. evt.preventDefault();
  1979. }
  1980. });
  1981. // Export utils
  1982. Sortable.utils = {
  1983. on: _on,
  1984. off: _off,
  1985. css: _css,
  1986. find: _find,
  1987. is: function (el, selector) {
  1988. return !!_closest(el, selector, el, false);
  1989. },
  1990. extend: _extend,
  1991. throttle: _throttle,
  1992. closest: _closest,
  1993. toggleClass: _toggleClass,
  1994. clone: _clone,
  1995. index: _index,
  1996. nextTick: _nextTick,
  1997. cancelNextTick: _cancelNextTick,
  1998. detectDirection: _detectDirection,
  1999. getChild: _getChild
  2000. };
  2001. /**
  2002. * Create sortable instance
  2003. * @param {HTMLElement} el
  2004. * @param {Object} [options]
  2005. */
  2006. Sortable.create = function (el, options) {
  2007. return new Sortable(el, options);
  2008. };
  2009. // Export
  2010. Sortable.version = '1.8.4';
  2011. return Sortable;
  2012. });