sortable.esm.js 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026
  1. /*!
  2. * All material copyright ESRI, All Rights Reserved, unless otherwise specified.
  3. * See https://github.com/Esri/calcite-components/blob/master/LICENSE.md for details.
  4. * v1.0.0-beta.97
  5. */
  6. /**!
  7. * Sortable 1.15.0
  8. * @author RubaXa <trash@rubaxa.org>
  9. * @author owenm <owen23355@gmail.com>
  10. * @license MIT
  11. */
  12. function ownKeys(object, enumerableOnly) {
  13. var keys = Object.keys(object);
  14. if (Object.getOwnPropertySymbols) {
  15. var symbols = Object.getOwnPropertySymbols(object);
  16. if (enumerableOnly) {
  17. symbols = symbols.filter(function (sym) {
  18. return Object.getOwnPropertyDescriptor(object, sym).enumerable;
  19. });
  20. }
  21. keys.push.apply(keys, symbols);
  22. }
  23. return keys;
  24. }
  25. function _objectSpread2(target) {
  26. for (var i = 1; i < arguments.length; i++) {
  27. var source = arguments[i] != null ? arguments[i] : {};
  28. if (i % 2) {
  29. ownKeys(Object(source), true).forEach(function (key) {
  30. _defineProperty(target, key, source[key]);
  31. });
  32. } else if (Object.getOwnPropertyDescriptors) {
  33. Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  34. } else {
  35. ownKeys(Object(source)).forEach(function (key) {
  36. Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
  37. });
  38. }
  39. }
  40. return target;
  41. }
  42. function _typeof(obj) {
  43. "@babel/helpers - typeof";
  44. if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
  45. _typeof = function (obj) {
  46. return typeof obj;
  47. };
  48. } else {
  49. _typeof = function (obj) {
  50. return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  51. };
  52. }
  53. return _typeof(obj);
  54. }
  55. function _defineProperty(obj, key, value) {
  56. if (key in obj) {
  57. Object.defineProperty(obj, key, {
  58. value: value,
  59. enumerable: true,
  60. configurable: true,
  61. writable: true
  62. });
  63. } else {
  64. obj[key] = value;
  65. }
  66. return obj;
  67. }
  68. function _extends() {
  69. _extends = Object.assign || function (target) {
  70. for (var i = 1; i < arguments.length; i++) {
  71. var source = arguments[i];
  72. for (var key in source) {
  73. if (Object.prototype.hasOwnProperty.call(source, key)) {
  74. target[key] = source[key];
  75. }
  76. }
  77. }
  78. return target;
  79. };
  80. return _extends.apply(this, arguments);
  81. }
  82. function _objectWithoutPropertiesLoose(source, excluded) {
  83. if (source == null) return {};
  84. var target = {};
  85. var sourceKeys = Object.keys(source);
  86. var key, i;
  87. for (i = 0; i < sourceKeys.length; i++) {
  88. key = sourceKeys[i];
  89. if (excluded.indexOf(key) >= 0) continue;
  90. target[key] = source[key];
  91. }
  92. return target;
  93. }
  94. function _objectWithoutProperties(source, excluded) {
  95. if (source == null) return {};
  96. var target = _objectWithoutPropertiesLoose(source, excluded);
  97. var key, i;
  98. if (Object.getOwnPropertySymbols) {
  99. var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
  100. for (i = 0; i < sourceSymbolKeys.length; i++) {
  101. key = sourceSymbolKeys[i];
  102. if (excluded.indexOf(key) >= 0) continue;
  103. if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
  104. target[key] = source[key];
  105. }
  106. }
  107. return target;
  108. }
  109. var version = "1.15.0";
  110. function userAgent(pattern) {
  111. if (typeof window !== 'undefined' && window.navigator) {
  112. return !! /*@__PURE__*/navigator.userAgent.match(pattern);
  113. }
  114. }
  115. var IE11OrLess = userAgent(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i);
  116. var Edge = userAgent(/Edge/i);
  117. var FireFox = userAgent(/firefox/i);
  118. var Safari = userAgent(/safari/i) && !userAgent(/chrome/i) && !userAgent(/android/i);
  119. var IOS = userAgent(/iP(ad|od|hone)/i);
  120. var ChromeForAndroid = userAgent(/chrome/i) && userAgent(/android/i);
  121. var captureMode = {
  122. capture: false,
  123. passive: false
  124. };
  125. function on(el, event, fn) {
  126. el.addEventListener(event, fn, !IE11OrLess && captureMode);
  127. }
  128. function off(el, event, fn) {
  129. el.removeEventListener(event, fn, !IE11OrLess && captureMode);
  130. }
  131. function matches(
  132. /**HTMLElement*/
  133. el,
  134. /**String*/
  135. selector) {
  136. if (!selector) return;
  137. selector[0] === '>' && (selector = selector.substring(1));
  138. if (el) {
  139. try {
  140. if (el.matches) {
  141. return el.matches(selector);
  142. } else if (el.msMatchesSelector) {
  143. return el.msMatchesSelector(selector);
  144. } else if (el.webkitMatchesSelector) {
  145. return el.webkitMatchesSelector(selector);
  146. }
  147. } catch (_) {
  148. return false;
  149. }
  150. }
  151. return false;
  152. }
  153. function getParentOrHost(el) {
  154. return el.host && el !== document && el.host.nodeType ? el.host : el.parentNode;
  155. }
  156. function closest(
  157. /**HTMLElement*/
  158. el,
  159. /**String*/
  160. selector,
  161. /**HTMLElement*/
  162. ctx, includeCTX) {
  163. if (el) {
  164. ctx = ctx || document;
  165. do {
  166. if (selector != null && (selector[0] === '>' ? el.parentNode === ctx && matches(el, selector) : matches(el, selector)) || includeCTX && el === ctx) {
  167. return el;
  168. }
  169. if (el === ctx) break;
  170. /* jshint boss:true */
  171. } while (el = getParentOrHost(el));
  172. }
  173. return null;
  174. }
  175. var R_SPACE = /\s+/g;
  176. function toggleClass(el, name, state) {
  177. if (el && name) {
  178. if (el.classList) {
  179. el.classList[state ? 'add' : 'remove'](name);
  180. } else {
  181. var className = (' ' + el.className + ' ').replace(R_SPACE, ' ').replace(' ' + name + ' ', ' ');
  182. el.className = (className + (state ? ' ' + name : '')).replace(R_SPACE, ' ');
  183. }
  184. }
  185. }
  186. function css(el, prop, val) {
  187. var style = el && el.style;
  188. if (style) {
  189. if (val === void 0) {
  190. if (document.defaultView && document.defaultView.getComputedStyle) {
  191. val = document.defaultView.getComputedStyle(el, '');
  192. } else if (el.currentStyle) {
  193. val = el.currentStyle;
  194. }
  195. return prop === void 0 ? val : val[prop];
  196. } else {
  197. if (!(prop in style) && prop.indexOf('webkit') === -1) {
  198. prop = '-webkit-' + prop;
  199. }
  200. style[prop] = val + (typeof val === 'string' ? '' : 'px');
  201. }
  202. }
  203. }
  204. function matrix(el, selfOnly) {
  205. var appliedTransforms = '';
  206. if (typeof el === 'string') {
  207. appliedTransforms = el;
  208. } else {
  209. do {
  210. var transform = css(el, 'transform');
  211. if (transform && transform !== 'none') {
  212. appliedTransforms = transform + ' ' + appliedTransforms;
  213. }
  214. /* jshint boss:true */
  215. } while (!selfOnly && (el = el.parentNode));
  216. }
  217. var matrixFn = window.DOMMatrix || window.WebKitCSSMatrix || window.CSSMatrix || window.MSCSSMatrix;
  218. /*jshint -W056 */
  219. return matrixFn && new matrixFn(appliedTransforms);
  220. }
  221. function find(ctx, tagName, iterator) {
  222. if (ctx) {
  223. var list = ctx.getElementsByTagName(tagName),
  224. i = 0,
  225. n = list.length;
  226. if (iterator) {
  227. for (; i < n; i++) {
  228. iterator(list[i], i);
  229. }
  230. }
  231. return list;
  232. }
  233. return [];
  234. }
  235. function getWindowScrollingElement() {
  236. var scrollingElement = document.scrollingElement;
  237. if (scrollingElement) {
  238. return scrollingElement;
  239. } else {
  240. return document.documentElement;
  241. }
  242. }
  243. /**
  244. * Returns the "bounding client rect" of given element
  245. * @param {HTMLElement} el The element whose boundingClientRect is wanted
  246. * @param {[Boolean]} relativeToContainingBlock Whether the rect should be relative to the containing block of (including) the container
  247. * @param {[Boolean]} relativeToNonStaticParent Whether the rect should be relative to the relative parent of (including) the contaienr
  248. * @param {[Boolean]} undoScale Whether the container's scale() should be undone
  249. * @param {[HTMLElement]} container The parent the element will be placed in
  250. * @return {Object} The boundingClientRect of el, with specified adjustments
  251. */
  252. function getRect(el, relativeToContainingBlock, relativeToNonStaticParent, undoScale, container) {
  253. if (!el.getBoundingClientRect && el !== window) return;
  254. var elRect, top, left, bottom, right, height, width;
  255. if (el !== window && el.parentNode && el !== getWindowScrollingElement()) {
  256. elRect = el.getBoundingClientRect();
  257. top = elRect.top;
  258. left = elRect.left;
  259. bottom = elRect.bottom;
  260. right = elRect.right;
  261. height = elRect.height;
  262. width = elRect.width;
  263. } else {
  264. top = 0;
  265. left = 0;
  266. bottom = window.innerHeight;
  267. right = window.innerWidth;
  268. height = window.innerHeight;
  269. width = window.innerWidth;
  270. }
  271. if ((relativeToContainingBlock || relativeToNonStaticParent) && el !== window) {
  272. // Adjust for translate()
  273. container = container || el.parentNode; // solves #1123 (see: https://stackoverflow.com/a/37953806/6088312)
  274. // Not needed on <= IE11
  275. if (!IE11OrLess) {
  276. do {
  277. if (container && container.getBoundingClientRect && (css(container, 'transform') !== 'none' || relativeToNonStaticParent && css(container, 'position') !== 'static')) {
  278. var containerRect = container.getBoundingClientRect(); // Set relative to edges of padding box of container
  279. top -= containerRect.top + parseInt(css(container, 'border-top-width'));
  280. left -= containerRect.left + parseInt(css(container, 'border-left-width'));
  281. bottom = top + elRect.height;
  282. right = left + elRect.width;
  283. break;
  284. }
  285. /* jshint boss:true */
  286. } while (container = container.parentNode);
  287. }
  288. }
  289. if (undoScale && el !== window) {
  290. // Adjust for scale()
  291. var elMatrix = matrix(container || el),
  292. scaleX = elMatrix && elMatrix.a,
  293. scaleY = elMatrix && elMatrix.d;
  294. if (elMatrix) {
  295. top /= scaleY;
  296. left /= scaleX;
  297. width /= scaleX;
  298. height /= scaleY;
  299. bottom = top + height;
  300. right = left + width;
  301. }
  302. }
  303. return {
  304. top: top,
  305. left: left,
  306. bottom: bottom,
  307. right: right,
  308. width: width,
  309. height: height
  310. };
  311. }
  312. /**
  313. * Checks if a side of an element is scrolled past a side of its parents
  314. * @param {HTMLElement} el The element who's side being scrolled out of view is in question
  315. * @param {String} elSide Side of the element in question ('top', 'left', 'right', 'bottom')
  316. * @param {String} parentSide Side of the parent in question ('top', 'left', 'right', 'bottom')
  317. * @return {HTMLElement} The parent scroll element that the el's side is scrolled past, or null if there is no such element
  318. */
  319. function isScrolledPast(el, elSide, parentSide) {
  320. var parent = getParentAutoScrollElement(el, true),
  321. elSideVal = getRect(el)[elSide];
  322. /* jshint boss:true */
  323. while (parent) {
  324. var parentSideVal = getRect(parent)[parentSide],
  325. visible = void 0;
  326. if (parentSide === 'top' || parentSide === 'left') {
  327. visible = elSideVal >= parentSideVal;
  328. } else {
  329. visible = elSideVal <= parentSideVal;
  330. }
  331. if (!visible) return parent;
  332. if (parent === getWindowScrollingElement()) break;
  333. parent = getParentAutoScrollElement(parent, false);
  334. }
  335. return false;
  336. }
  337. /**
  338. * Gets nth child of el, ignoring hidden children, sortable's elements (does not ignore clone if it's visible)
  339. * and non-draggable elements
  340. * @param {HTMLElement} el The parent element
  341. * @param {Number} childNum The index of the child
  342. * @param {Object} options Parent Sortable's options
  343. * @return {HTMLElement} The child at index childNum, or null if not found
  344. */
  345. function getChild(el, childNum, options, includeDragEl) {
  346. var currentChild = 0,
  347. i = 0,
  348. children = el.children;
  349. while (i < children.length) {
  350. if (children[i].style.display !== 'none' && children[i] !== Sortable.ghost && (includeDragEl || children[i] !== Sortable.dragged) && closest(children[i], options.draggable, el, false)) {
  351. if (currentChild === childNum) {
  352. return children[i];
  353. }
  354. currentChild++;
  355. }
  356. i++;
  357. }
  358. return null;
  359. }
  360. /**
  361. * Gets the last child in the el, ignoring ghostEl or invisible elements (clones)
  362. * @param {HTMLElement} el Parent element
  363. * @param {selector} selector Any other elements that should be ignored
  364. * @return {HTMLElement} The last child, ignoring ghostEl
  365. */
  366. function lastChild(el, selector) {
  367. var last = el.lastElementChild;
  368. while (last && (last === Sortable.ghost || css(last, 'display') === 'none' || selector && !matches(last, selector))) {
  369. last = last.previousElementSibling;
  370. }
  371. return last || null;
  372. }
  373. /**
  374. * Returns the index of an element within its parent for a selected set of
  375. * elements
  376. * @param {HTMLElement} el
  377. * @param {selector} selector
  378. * @return {number}
  379. */
  380. function index(el, selector) {
  381. var index = 0;
  382. if (!el || !el.parentNode) {
  383. return -1;
  384. }
  385. /* jshint boss:true */
  386. while (el = el.previousElementSibling) {
  387. if (el.nodeName.toUpperCase() !== 'TEMPLATE' && el !== Sortable.clone && (!selector || matches(el, selector))) {
  388. index++;
  389. }
  390. }
  391. return index;
  392. }
  393. /**
  394. * Returns the scroll offset of the given element, added with all the scroll offsets of parent elements.
  395. * The value is returned in real pixels.
  396. * @param {HTMLElement} el
  397. * @return {Array} Offsets in the format of [left, top]
  398. */
  399. function getRelativeScrollOffset(el) {
  400. var offsetLeft = 0,
  401. offsetTop = 0,
  402. winScroller = getWindowScrollingElement();
  403. if (el) {
  404. do {
  405. var elMatrix = matrix(el),
  406. scaleX = elMatrix.a,
  407. scaleY = elMatrix.d;
  408. offsetLeft += el.scrollLeft * scaleX;
  409. offsetTop += el.scrollTop * scaleY;
  410. } while (el !== winScroller && (el = el.parentNode));
  411. }
  412. return [offsetLeft, offsetTop];
  413. }
  414. /**
  415. * Returns the index of the object within the given array
  416. * @param {Array} arr Array that may or may not hold the object
  417. * @param {Object} obj An object that has a key-value pair unique to and identical to a key-value pair in the object you want to find
  418. * @return {Number} The index of the object in the array, or -1
  419. */
  420. function indexOfObject(arr, obj) {
  421. for (var i in arr) {
  422. if (!arr.hasOwnProperty(i)) continue;
  423. for (var key in obj) {
  424. if (obj.hasOwnProperty(key) && obj[key] === arr[i][key]) return Number(i);
  425. }
  426. }
  427. return -1;
  428. }
  429. function getParentAutoScrollElement(el, includeSelf) {
  430. // skip to window
  431. if (!el || !el.getBoundingClientRect) return getWindowScrollingElement();
  432. var elem = el;
  433. var gotSelf = false;
  434. do {
  435. // we don't need to get elem css if it isn't even overflowing in the first place (performance)
  436. if (elem.clientWidth < elem.scrollWidth || elem.clientHeight < elem.scrollHeight) {
  437. var elemCSS = css(elem);
  438. if (elem.clientWidth < elem.scrollWidth && (elemCSS.overflowX == 'auto' || elemCSS.overflowX == 'scroll') || elem.clientHeight < elem.scrollHeight && (elemCSS.overflowY == 'auto' || elemCSS.overflowY == 'scroll')) {
  439. if (!elem.getBoundingClientRect || elem === document.body) return getWindowScrollingElement();
  440. if (gotSelf || includeSelf) return elem;
  441. gotSelf = true;
  442. }
  443. }
  444. /* jshint boss:true */
  445. } while (elem = elem.parentNode);
  446. return getWindowScrollingElement();
  447. }
  448. function extend(dst, src) {
  449. if (dst && src) {
  450. for (var key in src) {
  451. if (src.hasOwnProperty(key)) {
  452. dst[key] = src[key];
  453. }
  454. }
  455. }
  456. return dst;
  457. }
  458. function isRectEqual(rect1, rect2) {
  459. return Math.round(rect1.top) === Math.round(rect2.top) && Math.round(rect1.left) === Math.round(rect2.left) && Math.round(rect1.height) === Math.round(rect2.height) && Math.round(rect1.width) === Math.round(rect2.width);
  460. }
  461. var _throttleTimeout;
  462. function throttle(callback, ms) {
  463. return function () {
  464. if (!_throttleTimeout) {
  465. var args = arguments,
  466. _this = this;
  467. if (args.length === 1) {
  468. callback.call(_this, args[0]);
  469. } else {
  470. callback.apply(_this, args);
  471. }
  472. _throttleTimeout = setTimeout(function () {
  473. _throttleTimeout = void 0;
  474. }, ms);
  475. }
  476. };
  477. }
  478. function cancelThrottle() {
  479. clearTimeout(_throttleTimeout);
  480. _throttleTimeout = void 0;
  481. }
  482. function scrollBy(el, x, y) {
  483. el.scrollLeft += x;
  484. el.scrollTop += y;
  485. }
  486. function clone(el) {
  487. var Polymer = window.Polymer;
  488. var $ = window.jQuery || window.Zepto;
  489. if (Polymer && Polymer.dom) {
  490. return Polymer.dom(el).cloneNode(true);
  491. } else if ($) {
  492. return $(el).clone(true)[0];
  493. } else {
  494. return el.cloneNode(true);
  495. }
  496. }
  497. var expando = 'Sortable' + new Date().getTime();
  498. function AnimationStateManager() {
  499. var animationStates = [],
  500. animationCallbackId;
  501. return {
  502. captureAnimationState: function captureAnimationState() {
  503. animationStates = [];
  504. if (!this.options.animation) return;
  505. var children = [].slice.call(this.el.children);
  506. children.forEach(function (child) {
  507. if (css(child, 'display') === 'none' || child === Sortable.ghost) return;
  508. animationStates.push({
  509. target: child,
  510. rect: getRect(child)
  511. });
  512. var fromRect = _objectSpread2({}, animationStates[animationStates.length - 1].rect); // If animating: compensate for current animation
  513. if (child.thisAnimationDuration) {
  514. var childMatrix = matrix(child, true);
  515. if (childMatrix) {
  516. fromRect.top -= childMatrix.f;
  517. fromRect.left -= childMatrix.e;
  518. }
  519. }
  520. child.fromRect = fromRect;
  521. });
  522. },
  523. addAnimationState: function addAnimationState(state) {
  524. animationStates.push(state);
  525. },
  526. removeAnimationState: function removeAnimationState(target) {
  527. animationStates.splice(indexOfObject(animationStates, {
  528. target: target
  529. }), 1);
  530. },
  531. animateAll: function animateAll(callback) {
  532. var _this = this;
  533. if (!this.options.animation) {
  534. clearTimeout(animationCallbackId);
  535. if (typeof callback === 'function') callback();
  536. return;
  537. }
  538. var animating = false,
  539. animationTime = 0;
  540. animationStates.forEach(function (state) {
  541. var time = 0,
  542. target = state.target,
  543. fromRect = target.fromRect,
  544. toRect = getRect(target),
  545. prevFromRect = target.prevFromRect,
  546. prevToRect = target.prevToRect,
  547. animatingRect = state.rect,
  548. targetMatrix = matrix(target, true);
  549. if (targetMatrix) {
  550. // Compensate for current animation
  551. toRect.top -= targetMatrix.f;
  552. toRect.left -= targetMatrix.e;
  553. }
  554. target.toRect = toRect;
  555. if (target.thisAnimationDuration) {
  556. // Could also check if animatingRect is between fromRect and toRect
  557. if (isRectEqual(prevFromRect, toRect) && !isRectEqual(fromRect, toRect) && // Make sure animatingRect is on line between toRect & fromRect
  558. (animatingRect.top - toRect.top) / (animatingRect.left - toRect.left) === (fromRect.top - toRect.top) / (fromRect.left - toRect.left)) {
  559. // If returning to same place as started from animation and on same axis
  560. time = calculateRealTime(animatingRect, prevFromRect, prevToRect, _this.options);
  561. }
  562. } // if fromRect != toRect: animate
  563. if (!isRectEqual(toRect, fromRect)) {
  564. target.prevFromRect = fromRect;
  565. target.prevToRect = toRect;
  566. if (!time) {
  567. time = _this.options.animation;
  568. }
  569. _this.animate(target, animatingRect, toRect, time);
  570. }
  571. if (time) {
  572. animating = true;
  573. animationTime = Math.max(animationTime, time);
  574. clearTimeout(target.animationResetTimer);
  575. target.animationResetTimer = setTimeout(function () {
  576. target.animationTime = 0;
  577. target.prevFromRect = null;
  578. target.fromRect = null;
  579. target.prevToRect = null;
  580. target.thisAnimationDuration = null;
  581. }, time);
  582. target.thisAnimationDuration = time;
  583. }
  584. });
  585. clearTimeout(animationCallbackId);
  586. if (!animating) {
  587. if (typeof callback === 'function') callback();
  588. } else {
  589. animationCallbackId = setTimeout(function () {
  590. if (typeof callback === 'function') callback();
  591. }, animationTime);
  592. }
  593. animationStates = [];
  594. },
  595. animate: function animate(target, currentRect, toRect, duration) {
  596. if (duration) {
  597. css(target, 'transition', '');
  598. css(target, 'transform', '');
  599. var elMatrix = matrix(this.el),
  600. scaleX = elMatrix && elMatrix.a,
  601. scaleY = elMatrix && elMatrix.d,
  602. translateX = (currentRect.left - toRect.left) / (scaleX || 1),
  603. translateY = (currentRect.top - toRect.top) / (scaleY || 1);
  604. target.animatingX = !!translateX;
  605. target.animatingY = !!translateY;
  606. css(target, 'transform', 'translate3d(' + translateX + 'px,' + translateY + 'px,0)');
  607. this.forRepaintDummy = repaint(target); // repaint
  608. css(target, 'transition', 'transform ' + duration + 'ms' + (this.options.easing ? ' ' + this.options.easing : ''));
  609. css(target, 'transform', 'translate3d(0,0,0)');
  610. typeof target.animated === 'number' && clearTimeout(target.animated);
  611. target.animated = setTimeout(function () {
  612. css(target, 'transition', '');
  613. css(target, 'transform', '');
  614. target.animated = false;
  615. target.animatingX = false;
  616. target.animatingY = false;
  617. }, duration);
  618. }
  619. }
  620. };
  621. }
  622. function repaint(target) {
  623. return target.offsetWidth;
  624. }
  625. function calculateRealTime(animatingRect, fromRect, toRect, options) {
  626. return Math.sqrt(Math.pow(fromRect.top - animatingRect.top, 2) + Math.pow(fromRect.left - animatingRect.left, 2)) / Math.sqrt(Math.pow(fromRect.top - toRect.top, 2) + Math.pow(fromRect.left - toRect.left, 2)) * options.animation;
  627. }
  628. var plugins = [];
  629. var defaults = {
  630. initializeByDefault: true
  631. };
  632. var PluginManager = {
  633. mount: function mount(plugin) {
  634. // Set default static properties
  635. for (var option in defaults) {
  636. if (defaults.hasOwnProperty(option) && !(option in plugin)) {
  637. plugin[option] = defaults[option];
  638. }
  639. }
  640. plugins.forEach(function (p) {
  641. if (p.pluginName === plugin.pluginName) {
  642. throw "Sortable: Cannot mount plugin ".concat(plugin.pluginName, " more than once");
  643. }
  644. });
  645. plugins.push(plugin);
  646. },
  647. pluginEvent: function pluginEvent(eventName, sortable, evt) {
  648. var _this = this;
  649. this.eventCanceled = false;
  650. evt.cancel = function () {
  651. _this.eventCanceled = true;
  652. };
  653. var eventNameGlobal = eventName + 'Global';
  654. plugins.forEach(function (plugin) {
  655. if (!sortable[plugin.pluginName]) return; // Fire global events if it exists in this sortable
  656. if (sortable[plugin.pluginName][eventNameGlobal]) {
  657. sortable[plugin.pluginName][eventNameGlobal](_objectSpread2({
  658. sortable: sortable
  659. }, evt));
  660. } // Only fire plugin event if plugin is enabled in this sortable,
  661. // and plugin has event defined
  662. if (sortable.options[plugin.pluginName] && sortable[plugin.pluginName][eventName]) {
  663. sortable[plugin.pluginName][eventName](_objectSpread2({
  664. sortable: sortable
  665. }, evt));
  666. }
  667. });
  668. },
  669. initializePlugins: function initializePlugins(sortable, el, defaults, options) {
  670. plugins.forEach(function (plugin) {
  671. var pluginName = plugin.pluginName;
  672. if (!sortable.options[pluginName] && !plugin.initializeByDefault) return;
  673. var initialized = new plugin(sortable, el, sortable.options);
  674. initialized.sortable = sortable;
  675. initialized.options = sortable.options;
  676. sortable[pluginName] = initialized; // Add default options from plugin
  677. _extends(defaults, initialized.defaults);
  678. });
  679. for (var option in sortable.options) {
  680. if (!sortable.options.hasOwnProperty(option)) continue;
  681. var modified = this.modifyOption(sortable, option, sortable.options[option]);
  682. if (typeof modified !== 'undefined') {
  683. sortable.options[option] = modified;
  684. }
  685. }
  686. },
  687. getEventProperties: function getEventProperties(name, sortable) {
  688. var eventProperties = {};
  689. plugins.forEach(function (plugin) {
  690. if (typeof plugin.eventProperties !== 'function') return;
  691. _extends(eventProperties, plugin.eventProperties.call(sortable[plugin.pluginName], name));
  692. });
  693. return eventProperties;
  694. },
  695. modifyOption: function modifyOption(sortable, name, value) {
  696. var modifiedValue;
  697. plugins.forEach(function (plugin) {
  698. // Plugin must exist on the Sortable
  699. if (!sortable[plugin.pluginName]) return; // If static option listener exists for this option, call in the context of the Sortable's instance of this plugin
  700. if (plugin.optionListeners && typeof plugin.optionListeners[name] === 'function') {
  701. modifiedValue = plugin.optionListeners[name].call(sortable[plugin.pluginName], value);
  702. }
  703. });
  704. return modifiedValue;
  705. }
  706. };
  707. function dispatchEvent(_ref) {
  708. var sortable = _ref.sortable,
  709. rootEl = _ref.rootEl,
  710. name = _ref.name,
  711. targetEl = _ref.targetEl,
  712. cloneEl = _ref.cloneEl,
  713. toEl = _ref.toEl,
  714. fromEl = _ref.fromEl,
  715. oldIndex = _ref.oldIndex,
  716. newIndex = _ref.newIndex,
  717. oldDraggableIndex = _ref.oldDraggableIndex,
  718. newDraggableIndex = _ref.newDraggableIndex,
  719. originalEvent = _ref.originalEvent,
  720. putSortable = _ref.putSortable,
  721. extraEventProperties = _ref.extraEventProperties;
  722. sortable = sortable || rootEl && rootEl[expando];
  723. if (!sortable) return;
  724. var evt,
  725. options = sortable.options,
  726. onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1); // Support for new CustomEvent feature
  727. if (window.CustomEvent && !IE11OrLess && !Edge) {
  728. evt = new CustomEvent(name, {
  729. bubbles: true,
  730. cancelable: true
  731. });
  732. } else {
  733. evt = document.createEvent('Event');
  734. evt.initEvent(name, true, true);
  735. }
  736. evt.to = toEl || rootEl;
  737. evt.from = fromEl || rootEl;
  738. evt.item = targetEl || rootEl;
  739. evt.clone = cloneEl;
  740. evt.oldIndex = oldIndex;
  741. evt.newIndex = newIndex;
  742. evt.oldDraggableIndex = oldDraggableIndex;
  743. evt.newDraggableIndex = newDraggableIndex;
  744. evt.originalEvent = originalEvent;
  745. evt.pullMode = putSortable ? putSortable.lastPutMode : undefined;
  746. var allEventProperties = _objectSpread2(_objectSpread2({}, extraEventProperties), PluginManager.getEventProperties(name, sortable));
  747. for (var option in allEventProperties) {
  748. evt[option] = allEventProperties[option];
  749. }
  750. if (rootEl) {
  751. rootEl.dispatchEvent(evt);
  752. }
  753. if (options[onName]) {
  754. options[onName].call(sortable, evt);
  755. }
  756. }
  757. var _excluded = ["evt"];
  758. var pluginEvent = function pluginEvent(eventName, sortable) {
  759. var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
  760. originalEvent = _ref.evt,
  761. data = _objectWithoutProperties(_ref, _excluded);
  762. PluginManager.pluginEvent.bind(Sortable)(eventName, sortable, _objectSpread2({
  763. dragEl: dragEl,
  764. parentEl: parentEl,
  765. ghostEl: ghostEl,
  766. rootEl: rootEl,
  767. nextEl: nextEl,
  768. lastDownEl: lastDownEl,
  769. cloneEl: cloneEl,
  770. cloneHidden: cloneHidden,
  771. dragStarted: moved,
  772. putSortable: putSortable,
  773. activeSortable: Sortable.active,
  774. originalEvent: originalEvent,
  775. oldIndex: oldIndex,
  776. oldDraggableIndex: oldDraggableIndex,
  777. newIndex: newIndex,
  778. newDraggableIndex: newDraggableIndex,
  779. hideGhostForTarget: _hideGhostForTarget,
  780. unhideGhostForTarget: _unhideGhostForTarget,
  781. cloneNowHidden: function cloneNowHidden() {
  782. cloneHidden = true;
  783. },
  784. cloneNowShown: function cloneNowShown() {
  785. cloneHidden = false;
  786. },
  787. dispatchSortableEvent: function dispatchSortableEvent(name) {
  788. _dispatchEvent({
  789. sortable: sortable,
  790. name: name,
  791. originalEvent: originalEvent
  792. });
  793. }
  794. }, data));
  795. };
  796. function _dispatchEvent(info) {
  797. dispatchEvent(_objectSpread2({
  798. putSortable: putSortable,
  799. cloneEl: cloneEl,
  800. targetEl: dragEl,
  801. rootEl: rootEl,
  802. oldIndex: oldIndex,
  803. oldDraggableIndex: oldDraggableIndex,
  804. newIndex: newIndex,
  805. newDraggableIndex: newDraggableIndex
  806. }, info));
  807. }
  808. var dragEl,
  809. parentEl,
  810. ghostEl,
  811. rootEl,
  812. nextEl,
  813. lastDownEl,
  814. cloneEl,
  815. cloneHidden,
  816. oldIndex,
  817. newIndex,
  818. oldDraggableIndex,
  819. newDraggableIndex,
  820. activeGroup,
  821. putSortable,
  822. awaitingDragStarted = false,
  823. ignoreNextClick = false,
  824. sortables = [],
  825. tapEvt,
  826. touchEvt,
  827. lastDx,
  828. lastDy,
  829. tapDistanceLeft,
  830. tapDistanceTop,
  831. moved,
  832. lastTarget,
  833. lastDirection,
  834. pastFirstInvertThresh = false,
  835. isCircumstantialInvert = false,
  836. targetMoveDistance,
  837. // For positioning ghost absolutely
  838. ghostRelativeParent,
  839. ghostRelativeParentInitialScroll = [],
  840. // (left, top)
  841. _silent = false,
  842. savedInputChecked = [];
  843. /** @const */
  844. var documentExists = typeof document !== 'undefined',
  845. PositionGhostAbsolutely = IOS,
  846. CSSFloatProperty = Edge || IE11OrLess ? 'cssFloat' : 'float',
  847. // This will not pass for IE9, because IE9 DnD only works on anchors
  848. supportDraggable = documentExists && !ChromeForAndroid && !IOS && 'draggable' in document.createElement('div'),
  849. supportCssPointerEvents = function () {
  850. if (!documentExists) return; // false when <= IE11
  851. if (IE11OrLess) {
  852. return false;
  853. }
  854. var el = document.createElement('x');
  855. el.style.cssText = 'pointer-events:auto';
  856. return el.style.pointerEvents === 'auto';
  857. }(),
  858. _detectDirection = function _detectDirection(el, options) {
  859. var elCSS = css(el),
  860. elWidth = parseInt(elCSS.width) - parseInt(elCSS.paddingLeft) - parseInt(elCSS.paddingRight) - parseInt(elCSS.borderLeftWidth) - parseInt(elCSS.borderRightWidth),
  861. child1 = getChild(el, 0, options),
  862. child2 = getChild(el, 1, options),
  863. firstChildCSS = child1 && css(child1),
  864. secondChildCSS = child2 && css(child2),
  865. firstChildWidth = firstChildCSS && parseInt(firstChildCSS.marginLeft) + parseInt(firstChildCSS.marginRight) + getRect(child1).width,
  866. secondChildWidth = secondChildCSS && parseInt(secondChildCSS.marginLeft) + parseInt(secondChildCSS.marginRight) + getRect(child2).width;
  867. if (elCSS.display === 'flex') {
  868. return elCSS.flexDirection === 'column' || elCSS.flexDirection === 'column-reverse' ? 'vertical' : 'horizontal';
  869. }
  870. if (elCSS.display === 'grid') {
  871. return elCSS.gridTemplateColumns.split(' ').length <= 1 ? 'vertical' : 'horizontal';
  872. }
  873. if (child1 && firstChildCSS["float"] && firstChildCSS["float"] !== 'none') {
  874. var touchingSideChild2 = firstChildCSS["float"] === 'left' ? 'left' : 'right';
  875. return child2 && (secondChildCSS.clear === 'both' || secondChildCSS.clear === touchingSideChild2) ? 'vertical' : 'horizontal';
  876. }
  877. return child1 && (firstChildCSS.display === 'block' || firstChildCSS.display === 'flex' || firstChildCSS.display === 'table' || firstChildCSS.display === 'grid' || firstChildWidth >= elWidth && elCSS[CSSFloatProperty] === 'none' || child2 && elCSS[CSSFloatProperty] === 'none' && firstChildWidth + secondChildWidth > elWidth) ? 'vertical' : 'horizontal';
  878. },
  879. _dragElInRowColumn = function _dragElInRowColumn(dragRect, targetRect, vertical) {
  880. var dragElS1Opp = vertical ? dragRect.left : dragRect.top,
  881. dragElS2Opp = vertical ? dragRect.right : dragRect.bottom,
  882. dragElOppLength = vertical ? dragRect.width : dragRect.height,
  883. targetS1Opp = vertical ? targetRect.left : targetRect.top,
  884. targetS2Opp = vertical ? targetRect.right : targetRect.bottom,
  885. targetOppLength = vertical ? targetRect.width : targetRect.height;
  886. return dragElS1Opp === targetS1Opp || dragElS2Opp === targetS2Opp || dragElS1Opp + dragElOppLength / 2 === targetS1Opp + targetOppLength / 2;
  887. },
  888. /**
  889. * Detects first nearest empty sortable to X and Y position using emptyInsertThreshold.
  890. * @param {Number} x X position
  891. * @param {Number} y Y position
  892. * @return {HTMLElement} Element of the first found nearest Sortable
  893. */
  894. _detectNearestEmptySortable = function _detectNearestEmptySortable(x, y) {
  895. var ret;
  896. sortables.some(function (sortable) {
  897. var threshold = sortable[expando].options.emptyInsertThreshold;
  898. if (!threshold || lastChild(sortable)) return;
  899. var rect = getRect(sortable),
  900. insideHorizontally = x >= rect.left - threshold && x <= rect.right + threshold,
  901. insideVertically = y >= rect.top - threshold && y <= rect.bottom + threshold;
  902. if (insideHorizontally && insideVertically) {
  903. return ret = sortable;
  904. }
  905. });
  906. return ret;
  907. },
  908. _prepareGroup = function _prepareGroup(options) {
  909. function toFn(value, pull) {
  910. return function (to, from, dragEl, evt) {
  911. var sameGroup = to.options.group.name && from.options.group.name && to.options.group.name === from.options.group.name;
  912. if (value == null && (pull || sameGroup)) {
  913. // Default pull value
  914. // Default pull and put value if same group
  915. return true;
  916. } else if (value == null || value === false) {
  917. return false;
  918. } else if (pull && value === 'clone') {
  919. return value;
  920. } else if (typeof value === 'function') {
  921. return toFn(value(to, from, dragEl, evt), pull)(to, from, dragEl, evt);
  922. } else {
  923. var otherGroup = (pull ? to : from).options.group.name;
  924. return value === true || typeof value === 'string' && value === otherGroup || value.join && value.indexOf(otherGroup) > -1;
  925. }
  926. };
  927. }
  928. var group = {};
  929. var originalGroup = options.group;
  930. if (!originalGroup || _typeof(originalGroup) != 'object') {
  931. originalGroup = {
  932. name: originalGroup
  933. };
  934. }
  935. group.name = originalGroup.name;
  936. group.checkPull = toFn(originalGroup.pull, true);
  937. group.checkPut = toFn(originalGroup.put);
  938. group.revertClone = originalGroup.revertClone;
  939. options.group = group;
  940. },
  941. _hideGhostForTarget = function _hideGhostForTarget() {
  942. if (!supportCssPointerEvents && ghostEl) {
  943. css(ghostEl, 'display', 'none');
  944. }
  945. },
  946. _unhideGhostForTarget = function _unhideGhostForTarget() {
  947. if (!supportCssPointerEvents && ghostEl) {
  948. css(ghostEl, 'display', '');
  949. }
  950. }; // #1184 fix - Prevent click event on fallback if dragged but item not changed position
  951. if (documentExists && !ChromeForAndroid) {
  952. document.addEventListener('click', function (evt) {
  953. if (ignoreNextClick) {
  954. evt.preventDefault();
  955. evt.stopPropagation && evt.stopPropagation();
  956. evt.stopImmediatePropagation && evt.stopImmediatePropagation();
  957. ignoreNextClick = false;
  958. return false;
  959. }
  960. }, true);
  961. }
  962. var nearestEmptyInsertDetectEvent = function nearestEmptyInsertDetectEvent(evt) {
  963. if (dragEl) {
  964. evt = evt.touches ? evt.touches[0] : evt;
  965. var nearest = _detectNearestEmptySortable(evt.clientX, evt.clientY);
  966. if (nearest) {
  967. // Create imitation event
  968. var event = {};
  969. for (var i in evt) {
  970. if (evt.hasOwnProperty(i)) {
  971. event[i] = evt[i];
  972. }
  973. }
  974. event.target = event.rootEl = nearest;
  975. event.preventDefault = void 0;
  976. event.stopPropagation = void 0;
  977. nearest[expando]._onDragOver(event);
  978. }
  979. }
  980. };
  981. var _checkOutsideTargetEl = function _checkOutsideTargetEl(evt) {
  982. if (dragEl) {
  983. dragEl.parentNode[expando]._isOutsideThisEl(evt.target);
  984. }
  985. };
  986. /**
  987. * @class Sortable
  988. * @param {HTMLElement} el
  989. * @param {Object} [options]
  990. */
  991. function Sortable(el, options) {
  992. if (!(el && el.nodeType && el.nodeType === 1)) {
  993. throw "Sortable: `el` must be an HTMLElement, not ".concat({}.toString.call(el));
  994. }
  995. this.el = el; // root element
  996. this.options = options = _extends({}, options); // Export instance
  997. el[expando] = this;
  998. var defaults = {
  999. group: null,
  1000. sort: true,
  1001. disabled: false,
  1002. store: null,
  1003. handle: null,
  1004. draggable: /^[uo]l$/i.test(el.nodeName) ? '>li' : '>*',
  1005. swapThreshold: 1,
  1006. // percentage; 0 <= x <= 1
  1007. invertSwap: false,
  1008. // invert always
  1009. invertedSwapThreshold: null,
  1010. // will be set to same as swapThreshold if default
  1011. removeCloneOnHide: true,
  1012. direction: function direction() {
  1013. return _detectDirection(el, this.options);
  1014. },
  1015. ghostClass: 'sortable-ghost',
  1016. chosenClass: 'sortable-chosen',
  1017. dragClass: 'sortable-drag',
  1018. ignore: 'a, img',
  1019. filter: null,
  1020. preventOnFilter: true,
  1021. animation: 0,
  1022. easing: null,
  1023. setData: function setData(dataTransfer, dragEl) {
  1024. dataTransfer.setData('Text', dragEl.textContent);
  1025. },
  1026. dropBubble: false,
  1027. dragoverBubble: false,
  1028. dataIdAttr: 'data-id',
  1029. delay: 0,
  1030. delayOnTouchOnly: false,
  1031. touchStartThreshold: (Number.parseInt ? Number : window).parseInt(window.devicePixelRatio, 10) || 1,
  1032. forceFallback: false,
  1033. fallbackClass: 'sortable-fallback',
  1034. fallbackOnBody: false,
  1035. fallbackTolerance: 0,
  1036. fallbackOffset: {
  1037. x: 0,
  1038. y: 0
  1039. },
  1040. supportPointer: Sortable.supportPointer !== false && 'PointerEvent' in window && !Safari,
  1041. emptyInsertThreshold: 5
  1042. };
  1043. PluginManager.initializePlugins(this, el, defaults); // Set default options
  1044. for (var name in defaults) {
  1045. !(name in options) && (options[name] = defaults[name]);
  1046. }
  1047. _prepareGroup(options); // Bind all private methods
  1048. for (var fn in this) {
  1049. if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
  1050. this[fn] = this[fn].bind(this);
  1051. }
  1052. } // Setup drag mode
  1053. this.nativeDraggable = options.forceFallback ? false : supportDraggable;
  1054. if (this.nativeDraggable) {
  1055. // Touch start threshold cannot be greater than the native dragstart threshold
  1056. this.options.touchStartThreshold = 1;
  1057. } // Bind events
  1058. if (options.supportPointer) {
  1059. on(el, 'pointerdown', this._onTapStart);
  1060. } else {
  1061. on(el, 'mousedown', this._onTapStart);
  1062. on(el, 'touchstart', this._onTapStart);
  1063. }
  1064. if (this.nativeDraggable) {
  1065. on(el, 'dragover', this);
  1066. on(el, 'dragenter', this);
  1067. }
  1068. sortables.push(this.el); // Restore sorting
  1069. options.store && options.store.get && this.sort(options.store.get(this) || []); // Add animation state manager
  1070. _extends(this, AnimationStateManager());
  1071. }
  1072. Sortable.prototype =
  1073. /** @lends Sortable.prototype */
  1074. {
  1075. constructor: Sortable,
  1076. _isOutsideThisEl: function _isOutsideThisEl(target) {
  1077. if (!this.el.contains(target) && target !== this.el) {
  1078. lastTarget = null;
  1079. }
  1080. },
  1081. _getDirection: function _getDirection(evt, target) {
  1082. return typeof this.options.direction === 'function' ? this.options.direction.call(this, evt, target, dragEl) : this.options.direction;
  1083. },
  1084. _onTapStart: function _onTapStart(
  1085. /** Event|TouchEvent */
  1086. evt) {
  1087. if (!evt.cancelable) return;
  1088. var _this = this,
  1089. el = this.el,
  1090. options = this.options,
  1091. preventOnFilter = options.preventOnFilter,
  1092. type = evt.type,
  1093. touch = evt.touches && evt.touches[0] || evt.pointerType && evt.pointerType === 'touch' && evt,
  1094. target = (touch || evt).target,
  1095. originalTarget = evt.target.shadowRoot && (evt.path && evt.path[0] || evt.composedPath && evt.composedPath()[0]) || target,
  1096. filter = options.filter;
  1097. _saveInputCheckedState(el); // Don't trigger start event when an element is been dragged, otherwise the evt.oldindex always wrong when set option.group.
  1098. if (dragEl) {
  1099. return;
  1100. }
  1101. if (/mousedown|pointerdown/.test(type) && evt.button !== 0 || options.disabled) {
  1102. return; // only left button and enabled
  1103. } // cancel dnd if original target is content editable
  1104. if (originalTarget.isContentEditable) {
  1105. return;
  1106. } // Safari ignores further event handling after mousedown
  1107. if (!this.nativeDraggable && Safari && target && target.tagName.toUpperCase() === 'SELECT') {
  1108. return;
  1109. }
  1110. target = closest(target, options.draggable, el, false);
  1111. if (target && target.animated) {
  1112. return;
  1113. }
  1114. if (lastDownEl === target) {
  1115. // Ignoring duplicate `down`
  1116. return;
  1117. } // Get the index of the dragged element within its parent
  1118. oldIndex = index(target);
  1119. oldDraggableIndex = index(target, options.draggable); // Check filter
  1120. if (typeof filter === 'function') {
  1121. if (filter.call(this, evt, target, this)) {
  1122. _dispatchEvent({
  1123. sortable: _this,
  1124. rootEl: originalTarget,
  1125. name: 'filter',
  1126. targetEl: target,
  1127. toEl: el,
  1128. fromEl: el
  1129. });
  1130. pluginEvent('filter', _this, {
  1131. evt: evt
  1132. });
  1133. preventOnFilter && evt.cancelable && evt.preventDefault();
  1134. return; // cancel dnd
  1135. }
  1136. } else if (filter) {
  1137. filter = filter.split(',').some(function (criteria) {
  1138. criteria = closest(originalTarget, criteria.trim(), el, false);
  1139. if (criteria) {
  1140. _dispatchEvent({
  1141. sortable: _this,
  1142. rootEl: criteria,
  1143. name: 'filter',
  1144. targetEl: target,
  1145. fromEl: el,
  1146. toEl: el
  1147. });
  1148. pluginEvent('filter', _this, {
  1149. evt: evt
  1150. });
  1151. return true;
  1152. }
  1153. });
  1154. if (filter) {
  1155. preventOnFilter && evt.cancelable && evt.preventDefault();
  1156. return; // cancel dnd
  1157. }
  1158. }
  1159. if (options.handle && !closest(originalTarget, options.handle, el, false)) {
  1160. return;
  1161. } // Prepare `dragstart`
  1162. this._prepareDragStart(evt, touch, target);
  1163. },
  1164. _prepareDragStart: function _prepareDragStart(
  1165. /** Event */
  1166. evt,
  1167. /** Touch */
  1168. touch,
  1169. /** HTMLElement */
  1170. target) {
  1171. var _this = this,
  1172. el = _this.el,
  1173. options = _this.options,
  1174. ownerDocument = el.ownerDocument,
  1175. dragStartFn;
  1176. if (target && !dragEl && target.parentNode === el) {
  1177. var dragRect = getRect(target);
  1178. rootEl = el;
  1179. dragEl = target;
  1180. parentEl = dragEl.parentNode;
  1181. nextEl = dragEl.nextSibling;
  1182. lastDownEl = target;
  1183. activeGroup = options.group;
  1184. Sortable.dragged = dragEl;
  1185. tapEvt = {
  1186. target: dragEl,
  1187. clientX: (touch || evt).clientX,
  1188. clientY: (touch || evt).clientY
  1189. };
  1190. tapDistanceLeft = tapEvt.clientX - dragRect.left;
  1191. tapDistanceTop = tapEvt.clientY - dragRect.top;
  1192. this._lastX = (touch || evt).clientX;
  1193. this._lastY = (touch || evt).clientY;
  1194. dragEl.style['will-change'] = 'all';
  1195. dragStartFn = function dragStartFn() {
  1196. pluginEvent('delayEnded', _this, {
  1197. evt: evt
  1198. });
  1199. if (Sortable.eventCanceled) {
  1200. _this._onDrop();
  1201. return;
  1202. } // Delayed drag has been triggered
  1203. // we can re-enable the events: touchmove/mousemove
  1204. _this._disableDelayedDragEvents();
  1205. if (!FireFox && _this.nativeDraggable) {
  1206. dragEl.draggable = true;
  1207. } // Bind the events: dragstart/dragend
  1208. _this._triggerDragStart(evt, touch); // Drag start event
  1209. _dispatchEvent({
  1210. sortable: _this,
  1211. name: 'choose',
  1212. originalEvent: evt
  1213. }); // Chosen item
  1214. toggleClass(dragEl, options.chosenClass, true);
  1215. }; // Disable "draggable"
  1216. options.ignore.split(',').forEach(function (criteria) {
  1217. find(dragEl, criteria.trim(), _disableDraggable);
  1218. });
  1219. on(ownerDocument, 'dragover', nearestEmptyInsertDetectEvent);
  1220. on(ownerDocument, 'mousemove', nearestEmptyInsertDetectEvent);
  1221. on(ownerDocument, 'touchmove', nearestEmptyInsertDetectEvent);
  1222. on(ownerDocument, 'mouseup', _this._onDrop);
  1223. on(ownerDocument, 'touchend', _this._onDrop);
  1224. on(ownerDocument, 'touchcancel', _this._onDrop); // Make dragEl draggable (must be before delay for FireFox)
  1225. if (FireFox && this.nativeDraggable) {
  1226. this.options.touchStartThreshold = 4;
  1227. dragEl.draggable = true;
  1228. }
  1229. pluginEvent('delayStart', this, {
  1230. evt: evt
  1231. }); // Delay is impossible for native DnD in Edge or IE
  1232. if (options.delay && (!options.delayOnTouchOnly || touch) && (!this.nativeDraggable || !(Edge || IE11OrLess))) {
  1233. if (Sortable.eventCanceled) {
  1234. this._onDrop();
  1235. return;
  1236. } // If the user moves the pointer or let go the click or touch
  1237. // before the delay has been reached:
  1238. // disable the delayed drag
  1239. on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
  1240. on(ownerDocument, 'touchend', _this._disableDelayedDrag);
  1241. on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
  1242. on(ownerDocument, 'mousemove', _this._delayedDragTouchMoveHandler);
  1243. on(ownerDocument, 'touchmove', _this._delayedDragTouchMoveHandler);
  1244. options.supportPointer && on(ownerDocument, 'pointermove', _this._delayedDragTouchMoveHandler);
  1245. _this._dragStartTimer = setTimeout(dragStartFn, options.delay);
  1246. } else {
  1247. dragStartFn();
  1248. }
  1249. }
  1250. },
  1251. _delayedDragTouchMoveHandler: function _delayedDragTouchMoveHandler(
  1252. /** TouchEvent|PointerEvent **/
  1253. e) {
  1254. var touch = e.touches ? e.touches[0] : e;
  1255. if (Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) >= Math.floor(this.options.touchStartThreshold / (this.nativeDraggable && window.devicePixelRatio || 1))) {
  1256. this._disableDelayedDrag();
  1257. }
  1258. },
  1259. _disableDelayedDrag: function _disableDelayedDrag() {
  1260. dragEl && _disableDraggable(dragEl);
  1261. clearTimeout(this._dragStartTimer);
  1262. this._disableDelayedDragEvents();
  1263. },
  1264. _disableDelayedDragEvents: function _disableDelayedDragEvents() {
  1265. var ownerDocument = this.el.ownerDocument;
  1266. off(ownerDocument, 'mouseup', this._disableDelayedDrag);
  1267. off(ownerDocument, 'touchend', this._disableDelayedDrag);
  1268. off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
  1269. off(ownerDocument, 'mousemove', this._delayedDragTouchMoveHandler);
  1270. off(ownerDocument, 'touchmove', this._delayedDragTouchMoveHandler);
  1271. off(ownerDocument, 'pointermove', this._delayedDragTouchMoveHandler);
  1272. },
  1273. _triggerDragStart: function _triggerDragStart(
  1274. /** Event */
  1275. evt,
  1276. /** Touch */
  1277. touch) {
  1278. touch = touch || evt.pointerType == 'touch' && evt;
  1279. if (!this.nativeDraggable || touch) {
  1280. if (this.options.supportPointer) {
  1281. on(document, 'pointermove', this._onTouchMove);
  1282. } else if (touch) {
  1283. on(document, 'touchmove', this._onTouchMove);
  1284. } else {
  1285. on(document, 'mousemove', this._onTouchMove);
  1286. }
  1287. } else {
  1288. on(dragEl, 'dragend', this);
  1289. on(rootEl, 'dragstart', this._onDragStart);
  1290. }
  1291. try {
  1292. if (document.selection) {
  1293. // Timeout neccessary for IE9
  1294. _nextTick(function () {
  1295. document.selection.empty();
  1296. });
  1297. } else {
  1298. window.getSelection().removeAllRanges();
  1299. }
  1300. } catch (err) {}
  1301. },
  1302. _dragStarted: function _dragStarted(fallback, evt) {
  1303. awaitingDragStarted = false;
  1304. if (rootEl && dragEl) {
  1305. pluginEvent('dragStarted', this, {
  1306. evt: evt
  1307. });
  1308. if (this.nativeDraggable) {
  1309. on(document, 'dragover', _checkOutsideTargetEl);
  1310. }
  1311. var options = this.options; // Apply effect
  1312. !fallback && toggleClass(dragEl, options.dragClass, false);
  1313. toggleClass(dragEl, options.ghostClass, true);
  1314. Sortable.active = this;
  1315. fallback && this._appendGhost(); // Drag start event
  1316. _dispatchEvent({
  1317. sortable: this,
  1318. name: 'start',
  1319. originalEvent: evt
  1320. });
  1321. } else {
  1322. this._nulling();
  1323. }
  1324. },
  1325. _emulateDragOver: function _emulateDragOver() {
  1326. if (touchEvt) {
  1327. this._lastX = touchEvt.clientX;
  1328. this._lastY = touchEvt.clientY;
  1329. _hideGhostForTarget();
  1330. var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
  1331. var parent = target;
  1332. while (target && target.shadowRoot) {
  1333. target = target.shadowRoot.elementFromPoint(touchEvt.clientX, touchEvt.clientY);
  1334. if (target === parent) break;
  1335. parent = target;
  1336. }
  1337. dragEl.parentNode[expando]._isOutsideThisEl(target);
  1338. if (parent) {
  1339. do {
  1340. if (parent[expando]) {
  1341. var inserted = void 0;
  1342. inserted = parent[expando]._onDragOver({
  1343. clientX: touchEvt.clientX,
  1344. clientY: touchEvt.clientY,
  1345. target: target,
  1346. rootEl: parent
  1347. });
  1348. if (inserted && !this.options.dragoverBubble) {
  1349. break;
  1350. }
  1351. }
  1352. target = parent; // store last element
  1353. }
  1354. /* jshint boss:true */
  1355. while (parent = parent.parentNode);
  1356. }
  1357. _unhideGhostForTarget();
  1358. }
  1359. },
  1360. _onTouchMove: function _onTouchMove(
  1361. /**TouchEvent*/
  1362. evt) {
  1363. if (tapEvt) {
  1364. var options = this.options,
  1365. fallbackTolerance = options.fallbackTolerance,
  1366. fallbackOffset = options.fallbackOffset,
  1367. touch = evt.touches ? evt.touches[0] : evt,
  1368. ghostMatrix = ghostEl && matrix(ghostEl, true),
  1369. scaleX = ghostEl && ghostMatrix && ghostMatrix.a,
  1370. scaleY = ghostEl && ghostMatrix && ghostMatrix.d,
  1371. relativeScrollOffset = PositionGhostAbsolutely && ghostRelativeParent && getRelativeScrollOffset(ghostRelativeParent),
  1372. dx = (touch.clientX - tapEvt.clientX + fallbackOffset.x) / (scaleX || 1) + (relativeScrollOffset ? relativeScrollOffset[0] - ghostRelativeParentInitialScroll[0] : 0) / (scaleX || 1),
  1373. dy = (touch.clientY - tapEvt.clientY + fallbackOffset.y) / (scaleY || 1) + (relativeScrollOffset ? relativeScrollOffset[1] - ghostRelativeParentInitialScroll[1] : 0) / (scaleY || 1); // only set the status to dragging, when we are actually dragging
  1374. if (!Sortable.active && !awaitingDragStarted) {
  1375. if (fallbackTolerance && Math.max(Math.abs(touch.clientX - this._lastX), Math.abs(touch.clientY - this._lastY)) < fallbackTolerance) {
  1376. return;
  1377. }
  1378. this._onDragStart(evt, true);
  1379. }
  1380. if (ghostEl) {
  1381. if (ghostMatrix) {
  1382. ghostMatrix.e += dx - (lastDx || 0);
  1383. ghostMatrix.f += dy - (lastDy || 0);
  1384. } else {
  1385. ghostMatrix = {
  1386. a: 1,
  1387. b: 0,
  1388. c: 0,
  1389. d: 1,
  1390. e: dx,
  1391. f: dy
  1392. };
  1393. }
  1394. var cssMatrix = "matrix(".concat(ghostMatrix.a, ",").concat(ghostMatrix.b, ",").concat(ghostMatrix.c, ",").concat(ghostMatrix.d, ",").concat(ghostMatrix.e, ",").concat(ghostMatrix.f, ")");
  1395. css(ghostEl, 'webkitTransform', cssMatrix);
  1396. css(ghostEl, 'mozTransform', cssMatrix);
  1397. css(ghostEl, 'msTransform', cssMatrix);
  1398. css(ghostEl, 'transform', cssMatrix);
  1399. lastDx = dx;
  1400. lastDy = dy;
  1401. touchEvt = touch;
  1402. }
  1403. evt.cancelable && evt.preventDefault();
  1404. }
  1405. },
  1406. _appendGhost: function _appendGhost() {
  1407. // Bug if using scale(): https://stackoverflow.com/questions/2637058
  1408. // Not being adjusted for
  1409. if (!ghostEl) {
  1410. var container = this.options.fallbackOnBody ? document.body : rootEl,
  1411. rect = getRect(dragEl, true, PositionGhostAbsolutely, true, container),
  1412. options = this.options; // Position absolutely
  1413. if (PositionGhostAbsolutely) {
  1414. // Get relatively positioned parent
  1415. ghostRelativeParent = container;
  1416. while (css(ghostRelativeParent, 'position') === 'static' && css(ghostRelativeParent, 'transform') === 'none' && ghostRelativeParent !== document) {
  1417. ghostRelativeParent = ghostRelativeParent.parentNode;
  1418. }
  1419. if (ghostRelativeParent !== document.body && ghostRelativeParent !== document.documentElement) {
  1420. if (ghostRelativeParent === document) ghostRelativeParent = getWindowScrollingElement();
  1421. rect.top += ghostRelativeParent.scrollTop;
  1422. rect.left += ghostRelativeParent.scrollLeft;
  1423. } else {
  1424. ghostRelativeParent = getWindowScrollingElement();
  1425. }
  1426. ghostRelativeParentInitialScroll = getRelativeScrollOffset(ghostRelativeParent);
  1427. }
  1428. ghostEl = dragEl.cloneNode(true);
  1429. toggleClass(ghostEl, options.ghostClass, false);
  1430. toggleClass(ghostEl, options.fallbackClass, true);
  1431. toggleClass(ghostEl, options.dragClass, true);
  1432. css(ghostEl, 'transition', '');
  1433. css(ghostEl, 'transform', '');
  1434. css(ghostEl, 'box-sizing', 'border-box');
  1435. css(ghostEl, 'margin', 0);
  1436. css(ghostEl, 'top', rect.top);
  1437. css(ghostEl, 'left', rect.left);
  1438. css(ghostEl, 'width', rect.width);
  1439. css(ghostEl, 'height', rect.height);
  1440. css(ghostEl, 'opacity', '0.8');
  1441. css(ghostEl, 'position', PositionGhostAbsolutely ? 'absolute' : 'fixed');
  1442. css(ghostEl, 'zIndex', '100000');
  1443. css(ghostEl, 'pointerEvents', 'none');
  1444. Sortable.ghost = ghostEl;
  1445. container.appendChild(ghostEl); // Set transform-origin
  1446. css(ghostEl, 'transform-origin', tapDistanceLeft / parseInt(ghostEl.style.width) * 100 + '% ' + tapDistanceTop / parseInt(ghostEl.style.height) * 100 + '%');
  1447. }
  1448. },
  1449. _onDragStart: function _onDragStart(
  1450. /**Event*/
  1451. evt,
  1452. /**boolean*/
  1453. fallback) {
  1454. var _this = this;
  1455. var dataTransfer = evt.dataTransfer;
  1456. var options = _this.options;
  1457. pluginEvent('dragStart', this, {
  1458. evt: evt
  1459. });
  1460. if (Sortable.eventCanceled) {
  1461. this._onDrop();
  1462. return;
  1463. }
  1464. pluginEvent('setupClone', this);
  1465. if (!Sortable.eventCanceled) {
  1466. cloneEl = clone(dragEl);
  1467. cloneEl.removeAttribute("id");
  1468. cloneEl.draggable = false;
  1469. cloneEl.style['will-change'] = '';
  1470. this._hideClone();
  1471. toggleClass(cloneEl, this.options.chosenClass, false);
  1472. Sortable.clone = cloneEl;
  1473. } // #1143: IFrame support workaround
  1474. _this.cloneId = _nextTick(function () {
  1475. pluginEvent('clone', _this);
  1476. if (Sortable.eventCanceled) return;
  1477. if (!_this.options.removeCloneOnHide) {
  1478. rootEl.insertBefore(cloneEl, dragEl);
  1479. }
  1480. _this._hideClone();
  1481. _dispatchEvent({
  1482. sortable: _this,
  1483. name: 'clone'
  1484. });
  1485. });
  1486. !fallback && toggleClass(dragEl, options.dragClass, true); // Set proper drop events
  1487. if (fallback) {
  1488. ignoreNextClick = true;
  1489. _this._loopId = setInterval(_this._emulateDragOver, 50);
  1490. } else {
  1491. // Undo what was set in _prepareDragStart before drag started
  1492. off(document, 'mouseup', _this._onDrop);
  1493. off(document, 'touchend', _this._onDrop);
  1494. off(document, 'touchcancel', _this._onDrop);
  1495. if (dataTransfer) {
  1496. dataTransfer.effectAllowed = 'move';
  1497. options.setData && options.setData.call(_this, dataTransfer, dragEl);
  1498. }
  1499. on(document, 'drop', _this); // #1276 fix:
  1500. css(dragEl, 'transform', 'translateZ(0)');
  1501. }
  1502. awaitingDragStarted = true;
  1503. _this._dragStartId = _nextTick(_this._dragStarted.bind(_this, fallback, evt));
  1504. on(document, 'selectstart', _this);
  1505. moved = true;
  1506. if (Safari) {
  1507. css(document.body, 'user-select', 'none');
  1508. }
  1509. },
  1510. // Returns true - if no further action is needed (either inserted or another condition)
  1511. _onDragOver: function _onDragOver(
  1512. /**Event*/
  1513. evt) {
  1514. var el = this.el,
  1515. target = evt.target,
  1516. dragRect,
  1517. targetRect,
  1518. revert,
  1519. options = this.options,
  1520. group = options.group,
  1521. activeSortable = Sortable.active,
  1522. isOwner = activeGroup === group,
  1523. canSort = options.sort,
  1524. fromSortable = putSortable || activeSortable,
  1525. vertical,
  1526. _this = this,
  1527. completedFired = false;
  1528. if (_silent) return;
  1529. function dragOverEvent(name, extra) {
  1530. pluginEvent(name, _this, _objectSpread2({
  1531. evt: evt,
  1532. isOwner: isOwner,
  1533. axis: vertical ? 'vertical' : 'horizontal',
  1534. revert: revert,
  1535. dragRect: dragRect,
  1536. targetRect: targetRect,
  1537. canSort: canSort,
  1538. fromSortable: fromSortable,
  1539. target: target,
  1540. completed: completed,
  1541. onMove: function onMove(target, after) {
  1542. return _onMove(rootEl, el, dragEl, dragRect, target, getRect(target), evt, after);
  1543. },
  1544. changed: changed
  1545. }, extra));
  1546. } // Capture animation state
  1547. function capture() {
  1548. dragOverEvent('dragOverAnimationCapture');
  1549. _this.captureAnimationState();
  1550. if (_this !== fromSortable) {
  1551. fromSortable.captureAnimationState();
  1552. }
  1553. } // Return invocation when dragEl is inserted (or completed)
  1554. function completed(insertion) {
  1555. dragOverEvent('dragOverCompleted', {
  1556. insertion: insertion
  1557. });
  1558. if (insertion) {
  1559. // Clones must be hidden before folding animation to capture dragRectAbsolute properly
  1560. if (isOwner) {
  1561. activeSortable._hideClone();
  1562. } else {
  1563. activeSortable._showClone(_this);
  1564. }
  1565. if (_this !== fromSortable) {
  1566. // Set ghost class to new sortable's ghost class
  1567. toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : activeSortable.options.ghostClass, false);
  1568. toggleClass(dragEl, options.ghostClass, true);
  1569. }
  1570. if (putSortable !== _this && _this !== Sortable.active) {
  1571. putSortable = _this;
  1572. } else if (_this === Sortable.active && putSortable) {
  1573. putSortable = null;
  1574. } // Animation
  1575. if (fromSortable === _this) {
  1576. _this._ignoreWhileAnimating = target;
  1577. }
  1578. _this.animateAll(function () {
  1579. dragOverEvent('dragOverAnimationComplete');
  1580. _this._ignoreWhileAnimating = null;
  1581. });
  1582. if (_this !== fromSortable) {
  1583. fromSortable.animateAll();
  1584. fromSortable._ignoreWhileAnimating = null;
  1585. }
  1586. } // Null lastTarget if it is not inside a previously swapped element
  1587. if (target === dragEl && !dragEl.animated || target === el && !target.animated) {
  1588. lastTarget = null;
  1589. } // no bubbling and not fallback
  1590. if (!options.dragoverBubble && !evt.rootEl && target !== document) {
  1591. dragEl.parentNode[expando]._isOutsideThisEl(evt.target); // Do not detect for empty insert if already inserted
  1592. !insertion && nearestEmptyInsertDetectEvent(evt);
  1593. }
  1594. !options.dragoverBubble && evt.stopPropagation && evt.stopPropagation();
  1595. return completedFired = true;
  1596. } // Call when dragEl has been inserted
  1597. function changed() {
  1598. newIndex = index(dragEl);
  1599. newDraggableIndex = index(dragEl, options.draggable);
  1600. _dispatchEvent({
  1601. sortable: _this,
  1602. name: 'change',
  1603. toEl: el,
  1604. newIndex: newIndex,
  1605. newDraggableIndex: newDraggableIndex,
  1606. originalEvent: evt
  1607. });
  1608. }
  1609. if (evt.preventDefault !== void 0) {
  1610. evt.cancelable && evt.preventDefault();
  1611. }
  1612. target = closest(target, options.draggable, el, true);
  1613. dragOverEvent('dragOver');
  1614. if (Sortable.eventCanceled) return completedFired;
  1615. if (dragEl.contains(evt.target) || target.animated && target.animatingX && target.animatingY || _this._ignoreWhileAnimating === target) {
  1616. return completed(false);
  1617. }
  1618. ignoreNextClick = false;
  1619. if (activeSortable && !options.disabled && (isOwner ? canSort || (revert = parentEl !== rootEl) // Reverting item into the original list
  1620. : putSortable === this || (this.lastPutMode = activeGroup.checkPull(this, activeSortable, dragEl, evt)) && group.checkPut(this, activeSortable, dragEl, evt))) {
  1621. vertical = this._getDirection(evt, target) === 'vertical';
  1622. dragRect = getRect(dragEl);
  1623. dragOverEvent('dragOverValid');
  1624. if (Sortable.eventCanceled) return completedFired;
  1625. if (revert) {
  1626. parentEl = rootEl; // actualization
  1627. capture();
  1628. this._hideClone();
  1629. dragOverEvent('revert');
  1630. if (!Sortable.eventCanceled) {
  1631. if (nextEl) {
  1632. rootEl.insertBefore(dragEl, nextEl);
  1633. } else {
  1634. rootEl.appendChild(dragEl);
  1635. }
  1636. }
  1637. return completed(true);
  1638. }
  1639. var elLastChild = lastChild(el, options.draggable);
  1640. if (!elLastChild || _ghostIsLast(evt, vertical, this) && !elLastChild.animated) {
  1641. // Insert to end of list
  1642. // If already at end of list: Do not insert
  1643. if (elLastChild === dragEl) {
  1644. return completed(false);
  1645. } // if there is a last element, it is the target
  1646. if (elLastChild && el === evt.target) {
  1647. target = elLastChild;
  1648. }
  1649. if (target) {
  1650. targetRect = getRect(target);
  1651. }
  1652. if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, !!target) !== false) {
  1653. capture();
  1654. if (elLastChild && elLastChild.nextSibling) {
  1655. // the last draggable element is not the last node
  1656. el.insertBefore(dragEl, elLastChild.nextSibling);
  1657. } else {
  1658. el.appendChild(dragEl);
  1659. }
  1660. parentEl = el; // actualization
  1661. changed();
  1662. return completed(true);
  1663. }
  1664. } else if (elLastChild && _ghostIsFirst(evt, vertical, this)) {
  1665. // Insert to start of list
  1666. var firstChild = getChild(el, 0, options, true);
  1667. if (firstChild === dragEl) {
  1668. return completed(false);
  1669. }
  1670. target = firstChild;
  1671. targetRect = getRect(target);
  1672. if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, false) !== false) {
  1673. capture();
  1674. el.insertBefore(dragEl, firstChild);
  1675. parentEl = el; // actualization
  1676. changed();
  1677. return completed(true);
  1678. }
  1679. } else if (target.parentNode === el) {
  1680. targetRect = getRect(target);
  1681. var direction = 0,
  1682. targetBeforeFirstSwap,
  1683. differentLevel = dragEl.parentNode !== el,
  1684. differentRowCol = !_dragElInRowColumn(dragEl.animated && dragEl.toRect || dragRect, target.animated && target.toRect || targetRect, vertical),
  1685. side1 = vertical ? 'top' : 'left',
  1686. scrolledPastTop = isScrolledPast(target, 'top', 'top') || isScrolledPast(dragEl, 'top', 'top'),
  1687. scrollBefore = scrolledPastTop ? scrolledPastTop.scrollTop : void 0;
  1688. if (lastTarget !== target) {
  1689. targetBeforeFirstSwap = targetRect[side1];
  1690. pastFirstInvertThresh = false;
  1691. isCircumstantialInvert = !differentRowCol && options.invertSwap || differentLevel;
  1692. }
  1693. direction = _getSwapDirection(evt, target, targetRect, vertical, differentRowCol ? 1 : options.swapThreshold, options.invertedSwapThreshold == null ? options.swapThreshold : options.invertedSwapThreshold, isCircumstantialInvert, lastTarget === target);
  1694. var sibling;
  1695. if (direction !== 0) {
  1696. // Check if target is beside dragEl in respective direction (ignoring hidden elements)
  1697. var dragIndex = index(dragEl);
  1698. do {
  1699. dragIndex -= direction;
  1700. sibling = parentEl.children[dragIndex];
  1701. } while (sibling && (css(sibling, 'display') === 'none' || sibling === ghostEl));
  1702. } // If dragEl is already beside target: Do not insert
  1703. if (direction === 0 || sibling === target) {
  1704. return completed(false);
  1705. }
  1706. lastTarget = target;
  1707. lastDirection = direction;
  1708. var nextSibling = target.nextElementSibling,
  1709. after = false;
  1710. after = direction === 1;
  1711. var moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect, evt, after);
  1712. if (moveVector !== false) {
  1713. if (moveVector === 1 || moveVector === -1) {
  1714. after = moveVector === 1;
  1715. }
  1716. _silent = true;
  1717. setTimeout(_unsilent, 30);
  1718. capture();
  1719. if (after && !nextSibling) {
  1720. el.appendChild(dragEl);
  1721. } else {
  1722. target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
  1723. } // Undo chrome's scroll adjustment (has no effect on other browsers)
  1724. if (scrolledPastTop) {
  1725. scrollBy(scrolledPastTop, 0, scrollBefore - scrolledPastTop.scrollTop);
  1726. }
  1727. parentEl = dragEl.parentNode; // actualization
  1728. // must be done before animation
  1729. if (targetBeforeFirstSwap !== undefined && !isCircumstantialInvert) {
  1730. targetMoveDistance = Math.abs(targetBeforeFirstSwap - getRect(target)[side1]);
  1731. }
  1732. changed();
  1733. return completed(true);
  1734. }
  1735. }
  1736. if (el.contains(dragEl)) {
  1737. return completed(false);
  1738. }
  1739. }
  1740. return false;
  1741. },
  1742. _ignoreWhileAnimating: null,
  1743. _offMoveEvents: function _offMoveEvents() {
  1744. off(document, 'mousemove', this._onTouchMove);
  1745. off(document, 'touchmove', this._onTouchMove);
  1746. off(document, 'pointermove', this._onTouchMove);
  1747. off(document, 'dragover', nearestEmptyInsertDetectEvent);
  1748. off(document, 'mousemove', nearestEmptyInsertDetectEvent);
  1749. off(document, 'touchmove', nearestEmptyInsertDetectEvent);
  1750. },
  1751. _offUpEvents: function _offUpEvents() {
  1752. var ownerDocument = this.el.ownerDocument;
  1753. off(ownerDocument, 'mouseup', this._onDrop);
  1754. off(ownerDocument, 'touchend', this._onDrop);
  1755. off(ownerDocument, 'pointerup', this._onDrop);
  1756. off(ownerDocument, 'touchcancel', this._onDrop);
  1757. off(document, 'selectstart', this);
  1758. },
  1759. _onDrop: function _onDrop(
  1760. /**Event*/
  1761. evt) {
  1762. var el = this.el,
  1763. options = this.options; // Get the index of the dragged element within its parent
  1764. newIndex = index(dragEl);
  1765. newDraggableIndex = index(dragEl, options.draggable);
  1766. pluginEvent('drop', this, {
  1767. evt: evt
  1768. });
  1769. parentEl = dragEl && dragEl.parentNode; // Get again after plugin event
  1770. newIndex = index(dragEl);
  1771. newDraggableIndex = index(dragEl, options.draggable);
  1772. if (Sortable.eventCanceled) {
  1773. this._nulling();
  1774. return;
  1775. }
  1776. awaitingDragStarted = false;
  1777. isCircumstantialInvert = false;
  1778. pastFirstInvertThresh = false;
  1779. clearInterval(this._loopId);
  1780. clearTimeout(this._dragStartTimer);
  1781. _cancelNextTick(this.cloneId);
  1782. _cancelNextTick(this._dragStartId); // Unbind events
  1783. if (this.nativeDraggable) {
  1784. off(document, 'drop', this);
  1785. off(el, 'dragstart', this._onDragStart);
  1786. }
  1787. this._offMoveEvents();
  1788. this._offUpEvents();
  1789. if (Safari) {
  1790. css(document.body, 'user-select', '');
  1791. }
  1792. css(dragEl, 'transform', '');
  1793. if (evt) {
  1794. if (moved) {
  1795. evt.cancelable && evt.preventDefault();
  1796. !options.dropBubble && evt.stopPropagation();
  1797. }
  1798. ghostEl && ghostEl.parentNode && ghostEl.parentNode.removeChild(ghostEl);
  1799. if (rootEl === parentEl || putSortable && putSortable.lastPutMode !== 'clone') {
  1800. // Remove clone(s)
  1801. cloneEl && cloneEl.parentNode && cloneEl.parentNode.removeChild(cloneEl);
  1802. }
  1803. if (dragEl) {
  1804. if (this.nativeDraggable) {
  1805. off(dragEl, 'dragend', this);
  1806. }
  1807. _disableDraggable(dragEl);
  1808. dragEl.style['will-change'] = ''; // Remove classes
  1809. // ghostClass is added in dragStarted
  1810. if (moved && !awaitingDragStarted) {
  1811. toggleClass(dragEl, putSortable ? putSortable.options.ghostClass : this.options.ghostClass, false);
  1812. }
  1813. toggleClass(dragEl, this.options.chosenClass, false); // Drag stop event
  1814. _dispatchEvent({
  1815. sortable: this,
  1816. name: 'unchoose',
  1817. toEl: parentEl,
  1818. newIndex: null,
  1819. newDraggableIndex: null,
  1820. originalEvent: evt
  1821. });
  1822. if (rootEl !== parentEl) {
  1823. if (newIndex >= 0) {
  1824. // Add event
  1825. _dispatchEvent({
  1826. rootEl: parentEl,
  1827. name: 'add',
  1828. toEl: parentEl,
  1829. fromEl: rootEl,
  1830. originalEvent: evt
  1831. }); // Remove event
  1832. _dispatchEvent({
  1833. sortable: this,
  1834. name: 'remove',
  1835. toEl: parentEl,
  1836. originalEvent: evt
  1837. }); // drag from one list and drop into another
  1838. _dispatchEvent({
  1839. rootEl: parentEl,
  1840. name: 'sort',
  1841. toEl: parentEl,
  1842. fromEl: rootEl,
  1843. originalEvent: evt
  1844. });
  1845. _dispatchEvent({
  1846. sortable: this,
  1847. name: 'sort',
  1848. toEl: parentEl,
  1849. originalEvent: evt
  1850. });
  1851. }
  1852. putSortable && putSortable.save();
  1853. } else {
  1854. if (newIndex !== oldIndex) {
  1855. if (newIndex >= 0) {
  1856. // drag & drop within the same list
  1857. _dispatchEvent({
  1858. sortable: this,
  1859. name: 'update',
  1860. toEl: parentEl,
  1861. originalEvent: evt
  1862. });
  1863. _dispatchEvent({
  1864. sortable: this,
  1865. name: 'sort',
  1866. toEl: parentEl,
  1867. originalEvent: evt
  1868. });
  1869. }
  1870. }
  1871. }
  1872. if (Sortable.active) {
  1873. /* jshint eqnull:true */
  1874. if (newIndex == null || newIndex === -1) {
  1875. newIndex = oldIndex;
  1876. newDraggableIndex = oldDraggableIndex;
  1877. }
  1878. _dispatchEvent({
  1879. sortable: this,
  1880. name: 'end',
  1881. toEl: parentEl,
  1882. originalEvent: evt
  1883. }); // Save sorting
  1884. this.save();
  1885. }
  1886. }
  1887. }
  1888. this._nulling();
  1889. },
  1890. _nulling: function _nulling() {
  1891. pluginEvent('nulling', this);
  1892. rootEl = dragEl = parentEl = ghostEl = nextEl = cloneEl = lastDownEl = cloneHidden = tapEvt = touchEvt = moved = newIndex = newDraggableIndex = oldIndex = oldDraggableIndex = lastTarget = lastDirection = putSortable = activeGroup = Sortable.dragged = Sortable.ghost = Sortable.clone = Sortable.active = null;
  1893. savedInputChecked.forEach(function (el) {
  1894. el.checked = true;
  1895. });
  1896. savedInputChecked.length = lastDx = lastDy = 0;
  1897. },
  1898. handleEvent: function handleEvent(
  1899. /**Event*/
  1900. evt) {
  1901. switch (evt.type) {
  1902. case 'drop':
  1903. case 'dragend':
  1904. this._onDrop(evt);
  1905. break;
  1906. case 'dragenter':
  1907. case 'dragover':
  1908. if (dragEl) {
  1909. this._onDragOver(evt);
  1910. _globalDragOver(evt);
  1911. }
  1912. break;
  1913. case 'selectstart':
  1914. evt.preventDefault();
  1915. break;
  1916. }
  1917. },
  1918. /**
  1919. * Serializes the item into an array of string.
  1920. * @returns {String[]}
  1921. */
  1922. toArray: function toArray() {
  1923. var order = [],
  1924. el,
  1925. children = this.el.children,
  1926. i = 0,
  1927. n = children.length,
  1928. options = this.options;
  1929. for (; i < n; i++) {
  1930. el = children[i];
  1931. if (closest(el, options.draggable, this.el, false)) {
  1932. order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
  1933. }
  1934. }
  1935. return order;
  1936. },
  1937. /**
  1938. * Sorts the elements according to the array.
  1939. * @param {String[]} order order of the items
  1940. */
  1941. sort: function sort(order, useAnimation) {
  1942. var items = {},
  1943. rootEl = this.el;
  1944. this.toArray().forEach(function (id, i) {
  1945. var el = rootEl.children[i];
  1946. if (closest(el, this.options.draggable, rootEl, false)) {
  1947. items[id] = el;
  1948. }
  1949. }, this);
  1950. useAnimation && this.captureAnimationState();
  1951. order.forEach(function (id) {
  1952. if (items[id]) {
  1953. rootEl.removeChild(items[id]);
  1954. rootEl.appendChild(items[id]);
  1955. }
  1956. });
  1957. useAnimation && this.animateAll();
  1958. },
  1959. /**
  1960. * Save the current sorting
  1961. */
  1962. save: function save() {
  1963. var store = this.options.store;
  1964. store && store.set && store.set(this);
  1965. },
  1966. /**
  1967. * 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.
  1968. * @param {HTMLElement} el
  1969. * @param {String} [selector] default: `options.draggable`
  1970. * @returns {HTMLElement|null}
  1971. */
  1972. closest: function closest$1(el, selector) {
  1973. return closest(el, selector || this.options.draggable, this.el, false);
  1974. },
  1975. /**
  1976. * Set/get option
  1977. * @param {string} name
  1978. * @param {*} [value]
  1979. * @returns {*}
  1980. */
  1981. option: function option(name, value) {
  1982. var options = this.options;
  1983. if (value === void 0) {
  1984. return options[name];
  1985. } else {
  1986. var modifiedValue = PluginManager.modifyOption(this, name, value);
  1987. if (typeof modifiedValue !== 'undefined') {
  1988. options[name] = modifiedValue;
  1989. } else {
  1990. options[name] = value;
  1991. }
  1992. if (name === 'group') {
  1993. _prepareGroup(options);
  1994. }
  1995. }
  1996. },
  1997. /**
  1998. * Destroy
  1999. */
  2000. destroy: function destroy() {
  2001. pluginEvent('destroy', this);
  2002. var el = this.el;
  2003. el[expando] = null;
  2004. off(el, 'mousedown', this._onTapStart);
  2005. off(el, 'touchstart', this._onTapStart);
  2006. off(el, 'pointerdown', this._onTapStart);
  2007. if (this.nativeDraggable) {
  2008. off(el, 'dragover', this);
  2009. off(el, 'dragenter', this);
  2010. } // Remove draggable attributes
  2011. Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
  2012. el.removeAttribute('draggable');
  2013. });
  2014. this._onDrop();
  2015. this._disableDelayedDragEvents();
  2016. sortables.splice(sortables.indexOf(this.el), 1);
  2017. this.el = el = null;
  2018. },
  2019. _hideClone: function _hideClone() {
  2020. if (!cloneHidden) {
  2021. pluginEvent('hideClone', this);
  2022. if (Sortable.eventCanceled) return;
  2023. css(cloneEl, 'display', 'none');
  2024. if (this.options.removeCloneOnHide && cloneEl.parentNode) {
  2025. cloneEl.parentNode.removeChild(cloneEl);
  2026. }
  2027. cloneHidden = true;
  2028. }
  2029. },
  2030. _showClone: function _showClone(putSortable) {
  2031. if (putSortable.lastPutMode !== 'clone') {
  2032. this._hideClone();
  2033. return;
  2034. }
  2035. if (cloneHidden) {
  2036. pluginEvent('showClone', this);
  2037. if (Sortable.eventCanceled) return; // show clone at dragEl or original position
  2038. if (dragEl.parentNode == rootEl && !this.options.group.revertClone) {
  2039. rootEl.insertBefore(cloneEl, dragEl);
  2040. } else if (nextEl) {
  2041. rootEl.insertBefore(cloneEl, nextEl);
  2042. } else {
  2043. rootEl.appendChild(cloneEl);
  2044. }
  2045. if (this.options.group.revertClone) {
  2046. this.animate(dragEl, cloneEl);
  2047. }
  2048. css(cloneEl, 'display', '');
  2049. cloneHidden = false;
  2050. }
  2051. }
  2052. };
  2053. function _globalDragOver(
  2054. /**Event*/
  2055. evt) {
  2056. if (evt.dataTransfer) {
  2057. evt.dataTransfer.dropEffect = 'move';
  2058. }
  2059. evt.cancelable && evt.preventDefault();
  2060. }
  2061. function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect, originalEvent, willInsertAfter) {
  2062. var evt,
  2063. sortable = fromEl[expando],
  2064. onMoveFn = sortable.options.onMove,
  2065. retVal; // Support for new CustomEvent feature
  2066. if (window.CustomEvent && !IE11OrLess && !Edge) {
  2067. evt = new CustomEvent('move', {
  2068. bubbles: true,
  2069. cancelable: true
  2070. });
  2071. } else {
  2072. evt = document.createEvent('Event');
  2073. evt.initEvent('move', true, true);
  2074. }
  2075. evt.to = toEl;
  2076. evt.from = fromEl;
  2077. evt.dragged = dragEl;
  2078. evt.draggedRect = dragRect;
  2079. evt.related = targetEl || toEl;
  2080. evt.relatedRect = targetRect || getRect(toEl);
  2081. evt.willInsertAfter = willInsertAfter;
  2082. evt.originalEvent = originalEvent;
  2083. fromEl.dispatchEvent(evt);
  2084. if (onMoveFn) {
  2085. retVal = onMoveFn.call(sortable, evt, originalEvent);
  2086. }
  2087. return retVal;
  2088. }
  2089. function _disableDraggable(el) {
  2090. el.draggable = false;
  2091. }
  2092. function _unsilent() {
  2093. _silent = false;
  2094. }
  2095. function _ghostIsFirst(evt, vertical, sortable) {
  2096. var rect = getRect(getChild(sortable.el, 0, sortable.options, true));
  2097. var spacer = 10;
  2098. return vertical ? evt.clientX < rect.left - spacer || evt.clientY < rect.top && evt.clientX < rect.right : evt.clientY < rect.top - spacer || evt.clientY < rect.bottom && evt.clientX < rect.left;
  2099. }
  2100. function _ghostIsLast(evt, vertical, sortable) {
  2101. var rect = getRect(lastChild(sortable.el, sortable.options.draggable));
  2102. var spacer = 10;
  2103. return vertical ? evt.clientX > rect.right + spacer || evt.clientX <= rect.right && evt.clientY > rect.bottom && evt.clientX >= rect.left : evt.clientX > rect.right && evt.clientY > rect.top || evt.clientX <= rect.right && evt.clientY > rect.bottom + spacer;
  2104. }
  2105. function _getSwapDirection(evt, target, targetRect, vertical, swapThreshold, invertedSwapThreshold, invertSwap, isLastTarget) {
  2106. var mouseOnAxis = vertical ? evt.clientY : evt.clientX,
  2107. targetLength = vertical ? targetRect.height : targetRect.width,
  2108. targetS1 = vertical ? targetRect.top : targetRect.left,
  2109. targetS2 = vertical ? targetRect.bottom : targetRect.right,
  2110. invert = false;
  2111. if (!invertSwap) {
  2112. // Never invert or create dragEl shadow when target movemenet causes mouse to move past the end of regular swapThreshold
  2113. if (isLastTarget && targetMoveDistance < targetLength * swapThreshold) {
  2114. // multiplied only by swapThreshold because mouse will already be inside target by (1 - threshold) * targetLength / 2
  2115. // check if past first invert threshold on side opposite of lastDirection
  2116. if (!pastFirstInvertThresh && (lastDirection === 1 ? mouseOnAxis > targetS1 + targetLength * invertedSwapThreshold / 2 : mouseOnAxis < targetS2 - targetLength * invertedSwapThreshold / 2)) {
  2117. // past first invert threshold, do not restrict inverted threshold to dragEl shadow
  2118. pastFirstInvertThresh = true;
  2119. }
  2120. if (!pastFirstInvertThresh) {
  2121. // dragEl shadow (target move distance shadow)
  2122. if (lastDirection === 1 ? mouseOnAxis < targetS1 + targetMoveDistance // over dragEl shadow
  2123. : mouseOnAxis > targetS2 - targetMoveDistance) {
  2124. return -lastDirection;
  2125. }
  2126. } else {
  2127. invert = true;
  2128. }
  2129. } else {
  2130. // Regular
  2131. if (mouseOnAxis > targetS1 + targetLength * (1 - swapThreshold) / 2 && mouseOnAxis < targetS2 - targetLength * (1 - swapThreshold) / 2) {
  2132. return _getInsertDirection(target);
  2133. }
  2134. }
  2135. }
  2136. invert = invert || invertSwap;
  2137. if (invert) {
  2138. // Invert of regular
  2139. if (mouseOnAxis < targetS1 + targetLength * invertedSwapThreshold / 2 || mouseOnAxis > targetS2 - targetLength * invertedSwapThreshold / 2) {
  2140. return mouseOnAxis > targetS1 + targetLength / 2 ? 1 : -1;
  2141. }
  2142. }
  2143. return 0;
  2144. }
  2145. /**
  2146. * Gets the direction dragEl must be swapped relative to target in order to make it
  2147. * seem that dragEl has been "inserted" into that element's position
  2148. * @param {HTMLElement} target The target whose position dragEl is being inserted at
  2149. * @return {Number} Direction dragEl must be swapped
  2150. */
  2151. function _getInsertDirection(target) {
  2152. if (index(dragEl) < index(target)) {
  2153. return 1;
  2154. } else {
  2155. return -1;
  2156. }
  2157. }
  2158. /**
  2159. * Generate id
  2160. * @param {HTMLElement} el
  2161. * @returns {String}
  2162. * @private
  2163. */
  2164. function _generateId(el) {
  2165. var str = el.tagName + el.className + el.src + el.href + el.textContent,
  2166. i = str.length,
  2167. sum = 0;
  2168. while (i--) {
  2169. sum += str.charCodeAt(i);
  2170. }
  2171. return sum.toString(36);
  2172. }
  2173. function _saveInputCheckedState(root) {
  2174. savedInputChecked.length = 0;
  2175. var inputs = root.getElementsByTagName('input');
  2176. var idx = inputs.length;
  2177. while (idx--) {
  2178. var el = inputs[idx];
  2179. el.checked && savedInputChecked.push(el);
  2180. }
  2181. }
  2182. function _nextTick(fn) {
  2183. return setTimeout(fn, 0);
  2184. }
  2185. function _cancelNextTick(id) {
  2186. return clearTimeout(id);
  2187. } // Fixed #973:
  2188. if (documentExists) {
  2189. on(document, 'touchmove', function (evt) {
  2190. if ((Sortable.active || awaitingDragStarted) && evt.cancelable) {
  2191. evt.preventDefault();
  2192. }
  2193. });
  2194. } // Export utils
  2195. Sortable.utils = {
  2196. on: on,
  2197. off: off,
  2198. css: css,
  2199. find: find,
  2200. is: function is(el, selector) {
  2201. return !!closest(el, selector, el, false);
  2202. },
  2203. extend: extend,
  2204. throttle: throttle,
  2205. closest: closest,
  2206. toggleClass: toggleClass,
  2207. clone: clone,
  2208. index: index,
  2209. nextTick: _nextTick,
  2210. cancelNextTick: _cancelNextTick,
  2211. detectDirection: _detectDirection,
  2212. getChild: getChild
  2213. };
  2214. /**
  2215. * Get the Sortable instance of an element
  2216. * @param {HTMLElement} element The element
  2217. * @return {Sortable|undefined} The instance of Sortable
  2218. */
  2219. Sortable.get = function (element) {
  2220. return element[expando];
  2221. };
  2222. /**
  2223. * Mount a plugin to Sortable
  2224. * @param {...SortablePlugin|SortablePlugin[]} plugins Plugins being mounted
  2225. */
  2226. Sortable.mount = function () {
  2227. for (var _len = arguments.length, plugins = new Array(_len), _key = 0; _key < _len; _key++) {
  2228. plugins[_key] = arguments[_key];
  2229. }
  2230. if (plugins[0].constructor === Array) plugins = plugins[0];
  2231. plugins.forEach(function (plugin) {
  2232. if (!plugin.prototype || !plugin.prototype.constructor) {
  2233. throw "Sortable: Mounted plugin must be a constructor function, not ".concat({}.toString.call(plugin));
  2234. }
  2235. if (plugin.utils) Sortable.utils = _objectSpread2(_objectSpread2({}, Sortable.utils), plugin.utils);
  2236. PluginManager.mount(plugin);
  2237. });
  2238. };
  2239. /**
  2240. * Create sortable instance
  2241. * @param {HTMLElement} el
  2242. * @param {Object} [options]
  2243. */
  2244. Sortable.create = function (el, options) {
  2245. return new Sortable(el, options);
  2246. }; // Export
  2247. Sortable.version = version;
  2248. var autoScrolls = [],
  2249. scrollEl,
  2250. scrollRootEl,
  2251. scrolling = false,
  2252. lastAutoScrollX,
  2253. lastAutoScrollY,
  2254. touchEvt$1,
  2255. pointerElemChangedInterval;
  2256. function AutoScrollPlugin() {
  2257. function AutoScroll() {
  2258. this.defaults = {
  2259. scroll: true,
  2260. forceAutoScrollFallback: false,
  2261. scrollSensitivity: 30,
  2262. scrollSpeed: 10,
  2263. bubbleScroll: true
  2264. }; // Bind all private methods
  2265. for (var fn in this) {
  2266. if (fn.charAt(0) === '_' && typeof this[fn] === 'function') {
  2267. this[fn] = this[fn].bind(this);
  2268. }
  2269. }
  2270. }
  2271. AutoScroll.prototype = {
  2272. dragStarted: function dragStarted(_ref) {
  2273. var originalEvent = _ref.originalEvent;
  2274. if (this.sortable.nativeDraggable) {
  2275. on(document, 'dragover', this._handleAutoScroll);
  2276. } else {
  2277. if (this.options.supportPointer) {
  2278. on(document, 'pointermove', this._handleFallbackAutoScroll);
  2279. } else if (originalEvent.touches) {
  2280. on(document, 'touchmove', this._handleFallbackAutoScroll);
  2281. } else {
  2282. on(document, 'mousemove', this._handleFallbackAutoScroll);
  2283. }
  2284. }
  2285. },
  2286. dragOverCompleted: function dragOverCompleted(_ref2) {
  2287. var originalEvent = _ref2.originalEvent;
  2288. // For when bubbling is canceled and using fallback (fallback 'touchmove' always reached)
  2289. if (!this.options.dragOverBubble && !originalEvent.rootEl) {
  2290. this._handleAutoScroll(originalEvent);
  2291. }
  2292. },
  2293. drop: function drop() {
  2294. if (this.sortable.nativeDraggable) {
  2295. off(document, 'dragover', this._handleAutoScroll);
  2296. } else {
  2297. off(document, 'pointermove', this._handleFallbackAutoScroll);
  2298. off(document, 'touchmove', this._handleFallbackAutoScroll);
  2299. off(document, 'mousemove', this._handleFallbackAutoScroll);
  2300. }
  2301. clearPointerElemChangedInterval();
  2302. clearAutoScrolls();
  2303. cancelThrottle();
  2304. },
  2305. nulling: function nulling() {
  2306. touchEvt$1 = scrollRootEl = scrollEl = scrolling = pointerElemChangedInterval = lastAutoScrollX = lastAutoScrollY = null;
  2307. autoScrolls.length = 0;
  2308. },
  2309. _handleFallbackAutoScroll: function _handleFallbackAutoScroll(evt) {
  2310. this._handleAutoScroll(evt, true);
  2311. },
  2312. _handleAutoScroll: function _handleAutoScroll(evt, fallback) {
  2313. var _this = this;
  2314. var x = (evt.touches ? evt.touches[0] : evt).clientX,
  2315. y = (evt.touches ? evt.touches[0] : evt).clientY,
  2316. elem = document.elementFromPoint(x, y);
  2317. touchEvt$1 = evt; // IE does not seem to have native autoscroll,
  2318. // Edge's autoscroll seems too conditional,
  2319. // MACOS Safari does not have autoscroll,
  2320. // Firefox and Chrome are good
  2321. if (fallback || this.options.forceAutoScrollFallback || Edge || IE11OrLess || Safari) {
  2322. autoScroll(evt, this.options, elem, fallback); // Listener for pointer element change
  2323. var ogElemScroller = getParentAutoScrollElement(elem, true);
  2324. if (scrolling && (!pointerElemChangedInterval || x !== lastAutoScrollX || y !== lastAutoScrollY)) {
  2325. pointerElemChangedInterval && clearPointerElemChangedInterval(); // Detect for pointer elem change, emulating native DnD behaviour
  2326. pointerElemChangedInterval = setInterval(function () {
  2327. var newElem = getParentAutoScrollElement(document.elementFromPoint(x, y), true);
  2328. if (newElem !== ogElemScroller) {
  2329. ogElemScroller = newElem;
  2330. clearAutoScrolls();
  2331. }
  2332. autoScroll(evt, _this.options, newElem, fallback);
  2333. }, 10);
  2334. lastAutoScrollX = x;
  2335. lastAutoScrollY = y;
  2336. }
  2337. } else {
  2338. // if DnD is enabled (and browser has good autoscrolling), first autoscroll will already scroll, so get parent autoscroll of first autoscroll
  2339. if (!this.options.bubbleScroll || getParentAutoScrollElement(elem, true) === getWindowScrollingElement()) {
  2340. clearAutoScrolls();
  2341. return;
  2342. }
  2343. autoScroll(evt, this.options, getParentAutoScrollElement(elem, false), false);
  2344. }
  2345. }
  2346. };
  2347. return _extends(AutoScroll, {
  2348. pluginName: 'scroll',
  2349. initializeByDefault: true
  2350. });
  2351. }
  2352. function clearAutoScrolls() {
  2353. autoScrolls.forEach(function (autoScroll) {
  2354. clearInterval(autoScroll.pid);
  2355. });
  2356. autoScrolls = [];
  2357. }
  2358. function clearPointerElemChangedInterval() {
  2359. clearInterval(pointerElemChangedInterval);
  2360. }
  2361. var autoScroll = throttle(function (evt, options, rootEl, isFallback) {
  2362. // Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
  2363. if (!options.scroll) return;
  2364. var x = (evt.touches ? evt.touches[0] : evt).clientX,
  2365. y = (evt.touches ? evt.touches[0] : evt).clientY,
  2366. sens = options.scrollSensitivity,
  2367. speed = options.scrollSpeed,
  2368. winScroller = getWindowScrollingElement();
  2369. var scrollThisInstance = false,
  2370. scrollCustomFn; // New scroll root, set scrollEl
  2371. if (scrollRootEl !== rootEl) {
  2372. scrollRootEl = rootEl;
  2373. clearAutoScrolls();
  2374. scrollEl = options.scroll;
  2375. scrollCustomFn = options.scrollFn;
  2376. if (scrollEl === true) {
  2377. scrollEl = getParentAutoScrollElement(rootEl, true);
  2378. }
  2379. }
  2380. var layersOut = 0;
  2381. var currentParent = scrollEl;
  2382. do {
  2383. var el = currentParent,
  2384. rect = getRect(el),
  2385. top = rect.top,
  2386. bottom = rect.bottom,
  2387. left = rect.left,
  2388. right = rect.right,
  2389. width = rect.width,
  2390. height = rect.height,
  2391. canScrollX = void 0,
  2392. canScrollY = void 0,
  2393. scrollWidth = el.scrollWidth,
  2394. scrollHeight = el.scrollHeight,
  2395. elCSS = css(el),
  2396. scrollPosX = el.scrollLeft,
  2397. scrollPosY = el.scrollTop;
  2398. if (el === winScroller) {
  2399. canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll' || elCSS.overflowX === 'visible');
  2400. canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll' || elCSS.overflowY === 'visible');
  2401. } else {
  2402. canScrollX = width < scrollWidth && (elCSS.overflowX === 'auto' || elCSS.overflowX === 'scroll');
  2403. canScrollY = height < scrollHeight && (elCSS.overflowY === 'auto' || elCSS.overflowY === 'scroll');
  2404. }
  2405. var vx = canScrollX && (Math.abs(right - x) <= sens && scrollPosX + width < scrollWidth) - (Math.abs(left - x) <= sens && !!scrollPosX);
  2406. var vy = canScrollY && (Math.abs(bottom - y) <= sens && scrollPosY + height < scrollHeight) - (Math.abs(top - y) <= sens && !!scrollPosY);
  2407. if (!autoScrolls[layersOut]) {
  2408. for (var i = 0; i <= layersOut; i++) {
  2409. if (!autoScrolls[i]) {
  2410. autoScrolls[i] = {};
  2411. }
  2412. }
  2413. }
  2414. if (autoScrolls[layersOut].vx != vx || autoScrolls[layersOut].vy != vy || autoScrolls[layersOut].el !== el) {
  2415. autoScrolls[layersOut].el = el;
  2416. autoScrolls[layersOut].vx = vx;
  2417. autoScrolls[layersOut].vy = vy;
  2418. clearInterval(autoScrolls[layersOut].pid);
  2419. if (vx != 0 || vy != 0) {
  2420. scrollThisInstance = true;
  2421. /* jshint loopfunc:true */
  2422. autoScrolls[layersOut].pid = setInterval(function () {
  2423. // emulate drag over during autoscroll (fallback), emulating native DnD behaviour
  2424. if (isFallback && this.layer === 0) {
  2425. Sortable.active._onTouchMove(touchEvt$1); // To move ghost if it is positioned absolutely
  2426. }
  2427. var scrollOffsetY = autoScrolls[this.layer].vy ? autoScrolls[this.layer].vy * speed : 0;
  2428. var scrollOffsetX = autoScrolls[this.layer].vx ? autoScrolls[this.layer].vx * speed : 0;
  2429. if (typeof scrollCustomFn === 'function') {
  2430. if (scrollCustomFn.call(Sortable.dragged.parentNode[expando], scrollOffsetX, scrollOffsetY, evt, touchEvt$1, autoScrolls[this.layer].el) !== 'continue') {
  2431. return;
  2432. }
  2433. }
  2434. scrollBy(autoScrolls[this.layer].el, scrollOffsetX, scrollOffsetY);
  2435. }.bind({
  2436. layer: layersOut
  2437. }), 24);
  2438. }
  2439. }
  2440. layersOut++;
  2441. } while (options.bubbleScroll && currentParent !== winScroller && (currentParent = getParentAutoScrollElement(currentParent, false)));
  2442. scrolling = scrollThisInstance; // in case another function catches scrolling as false in between when it is not
  2443. }, 30);
  2444. var drop = function drop(_ref) {
  2445. var originalEvent = _ref.originalEvent,
  2446. putSortable = _ref.putSortable,
  2447. dragEl = _ref.dragEl,
  2448. activeSortable = _ref.activeSortable,
  2449. dispatchSortableEvent = _ref.dispatchSortableEvent,
  2450. hideGhostForTarget = _ref.hideGhostForTarget,
  2451. unhideGhostForTarget = _ref.unhideGhostForTarget;
  2452. if (!originalEvent) return;
  2453. var toSortable = putSortable || activeSortable;
  2454. hideGhostForTarget();
  2455. var touch = originalEvent.changedTouches && originalEvent.changedTouches.length ? originalEvent.changedTouches[0] : originalEvent;
  2456. var target = document.elementFromPoint(touch.clientX, touch.clientY);
  2457. unhideGhostForTarget();
  2458. if (toSortable && !toSortable.el.contains(target)) {
  2459. dispatchSortableEvent('spill');
  2460. this.onSpill({
  2461. dragEl: dragEl,
  2462. putSortable: putSortable
  2463. });
  2464. }
  2465. };
  2466. function Revert() {}
  2467. Revert.prototype = {
  2468. startIndex: null,
  2469. dragStart: function dragStart(_ref2) {
  2470. var oldDraggableIndex = _ref2.oldDraggableIndex;
  2471. this.startIndex = oldDraggableIndex;
  2472. },
  2473. onSpill: function onSpill(_ref3) {
  2474. var dragEl = _ref3.dragEl,
  2475. putSortable = _ref3.putSortable;
  2476. this.sortable.captureAnimationState();
  2477. if (putSortable) {
  2478. putSortable.captureAnimationState();
  2479. }
  2480. var nextSibling = getChild(this.sortable.el, this.startIndex, this.options);
  2481. if (nextSibling) {
  2482. this.sortable.el.insertBefore(dragEl, nextSibling);
  2483. } else {
  2484. this.sortable.el.appendChild(dragEl);
  2485. }
  2486. this.sortable.animateAll();
  2487. if (putSortable) {
  2488. putSortable.animateAll();
  2489. }
  2490. },
  2491. drop: drop
  2492. };
  2493. _extends(Revert, {
  2494. pluginName: 'revertOnSpill'
  2495. });
  2496. function Remove() {}
  2497. Remove.prototype = {
  2498. onSpill: function onSpill(_ref4) {
  2499. var dragEl = _ref4.dragEl,
  2500. putSortable = _ref4.putSortable;
  2501. var parentSortable = putSortable || this.sortable;
  2502. parentSortable.captureAnimationState();
  2503. dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);
  2504. parentSortable.animateAll();
  2505. },
  2506. drop: drop
  2507. };
  2508. _extends(Remove, {
  2509. pluginName: 'removeOnSpill'
  2510. });
  2511. Sortable.mount(new AutoScrollPlugin());
  2512. Sortable.mount(Remove, Revert);
  2513. export { Sortable as S };