jquery.ui.sortable.js 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  1. /*!
  2. * jQuery UI Sortable 1.9.2
  3. * http://jqueryui.com
  4. *
  5. * Copyright 2012 jQuery Foundation and other contributors
  6. * Released under the MIT license.
  7. * http://jquery.org/license
  8. *
  9. * http://api.jqueryui.com/sortable/
  10. *
  11. * Depends:
  12. * jquery.ui.core.js
  13. * jquery.ui.mouse.js
  14. * jquery.ui.widget.js
  15. */
  16. (function( $, undefined ) {
  17. $.widget("ui.sortable", $.ui.mouse, {
  18. version: "1.9.2",
  19. widgetEventPrefix: "sort",
  20. ready: false,
  21. options: {
  22. appendTo: "parent",
  23. axis: false,
  24. connectWith: false,
  25. containment: false,
  26. cursor: 'auto',
  27. cursorAt: false,
  28. dropOnEmpty: true,
  29. forcePlaceholderSize: false,
  30. forceHelperSize: false,
  31. grid: false,
  32. handle: false,
  33. helper: "original",
  34. items: '> *',
  35. opacity: false,
  36. placeholder: false,
  37. revert: false,
  38. scroll: true,
  39. scrollSensitivity: 20,
  40. scrollSpeed: 20,
  41. scope: "default",
  42. tolerance: "intersect",
  43. zIndex: 1000
  44. },
  45. _create: function() {
  46. var o = this.options;
  47. this.containerCache = {};
  48. this.element.addClass("ui-sortable");
  49. //Get the items
  50. this.refresh();
  51. //Let's determine if the items are being displayed horizontally
  52. this.floating = this.items.length ? o.axis === 'x' || (/left|right/).test(this.items[0].item.css('float')) || (/inline|table-cell/).test(this.items[0].item.css('display')) : false;
  53. //Let's determine the parent's offset
  54. this.offset = this.element.offset();
  55. //Initialize mouse events for interaction
  56. this._mouseInit();
  57. //We're ready to go
  58. this.ready = true
  59. },
  60. _destroy: function() {
  61. this.element
  62. .removeClass("ui-sortable ui-sortable-disabled");
  63. this._mouseDestroy();
  64. for ( var i = this.items.length - 1; i >= 0; i-- )
  65. this.items[i].item.removeData(this.widgetName + "-item");
  66. return this;
  67. },
  68. _setOption: function(key, value){
  69. if ( key === "disabled" ) {
  70. this.options[ key ] = value;
  71. this.widget().toggleClass( "ui-sortable-disabled", !!value );
  72. } else {
  73. // Don't call widget base _setOption for disable as it adds ui-state-disabled class
  74. $.Widget.prototype._setOption.apply(this, arguments);
  75. }
  76. },
  77. _mouseCapture: function(event, overrideHandle) {
  78. var that = this;
  79. if (this.reverting) {
  80. return false;
  81. }
  82. if(this.options.disabled || this.options.type == 'static') return false;
  83. //We have to refresh the items data once first
  84. this._refreshItems(event);
  85. //Find out if the clicked node (or one of its parents) is a actual item in this.items
  86. var currentItem = null, nodes = $(event.target).parents().each(function() {
  87. if($.data(this, that.widgetName + '-item') == that) {
  88. currentItem = $(this);
  89. return false;
  90. }
  91. });
  92. if($.data(event.target, that.widgetName + '-item') == that) currentItem = $(event.target);
  93. if(!currentItem) return false;
  94. if(this.options.handle && !overrideHandle) {
  95. var validHandle = false;
  96. $(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; });
  97. if(!validHandle) return false;
  98. }
  99. this.currentItem = currentItem;
  100. this._removeCurrentsFromItems();
  101. return true;
  102. },
  103. _mouseStart: function(event, overrideHandle, noActivation) {
  104. var o = this.options;
  105. this.currentContainer = this;
  106. //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
  107. this.refreshPositions();
  108. //Create and append the visible helper
  109. this.helper = this._createHelper(event);
  110. //Cache the helper size
  111. this._cacheHelperProportions();
  112. /*
  113. * - Position generation -
  114. * This block generates everything position related - it's the core of draggables.
  115. */
  116. //Cache the margins of the original element
  117. this._cacheMargins();
  118. //Get the next scrolling parent
  119. this.scrollParent = this.helper.scrollParent();
  120. //The element's absolute position on the page minus margins
  121. this.offset = this.currentItem.offset();
  122. this.offset = {
  123. top: this.offset.top - this.margins.top,
  124. left: this.offset.left - this.margins.left
  125. };
  126. $.extend(this.offset, {
  127. click: { //Where the click happened, relative to the element
  128. left: event.pageX - this.offset.left,
  129. top: event.pageY - this.offset.top
  130. },
  131. parent: this._getParentOffset(),
  132. relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
  133. });
  134. // Only after we got the offset, we can change the helper's position to absolute
  135. // TODO: Still need to figure out a way to make relative sorting possible
  136. this.helper.css("position", "absolute");
  137. this.cssPosition = this.helper.css("position");
  138. //Generate the original position
  139. this.originalPosition = this._generatePosition(event);
  140. this.originalPageX = event.pageX;
  141. this.originalPageY = event.pageY;
  142. //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied
  143. (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
  144. //Cache the former DOM position
  145. this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
  146. //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way
  147. if(this.helper[0] != this.currentItem[0]) {
  148. this.currentItem.hide();
  149. }
  150. //Create the placeholder
  151. this._createPlaceholder();
  152. //Set a containment if given in the options
  153. if(o.containment)
  154. this._setContainment();
  155. if(o.cursor) { // cursor option
  156. if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor");
  157. $('body').css("cursor", o.cursor);
  158. }
  159. if(o.opacity) { // opacity option
  160. if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity");
  161. this.helper.css("opacity", o.opacity);
  162. }
  163. if(o.zIndex) { // zIndex option
  164. if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex");
  165. this.helper.css("zIndex", o.zIndex);
  166. }
  167. //Prepare scrolling
  168. if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML')
  169. this.overflowOffset = this.scrollParent.offset();
  170. //Call callbacks
  171. this._trigger("start", event, this._uiHash());
  172. //Recache the helper size
  173. if(!this._preserveHelperProportions)
  174. this._cacheHelperProportions();
  175. //Post 'activate' events to possible containers
  176. if(!noActivation) {
  177. for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, this._uiHash(this)); }
  178. }
  179. //Prepare possible droppables
  180. if($.ui.ddmanager)
  181. $.ui.ddmanager.current = this;
  182. if ($.ui.ddmanager && !o.dropBehaviour)
  183. $.ui.ddmanager.prepareOffsets(this, event);
  184. this.dragging = true;
  185. this.helper.addClass("ui-sortable-helper");
  186. this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
  187. return true;
  188. },
  189. _mouseDrag: function(event) {
  190. //Compute the helpers position
  191. this.position = this._generatePosition(event);
  192. this.positionAbs = this._convertPositionTo("absolute");
  193. if (!this.lastPositionAbs) {
  194. this.lastPositionAbs = this.positionAbs;
  195. }
  196. //Do scrolling
  197. if(this.options.scroll) {
  198. var o = this.options, scrolled = false;
  199. if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') {
  200. if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity)
  201. this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
  202. else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity)
  203. this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
  204. if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity)
  205. this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
  206. else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity)
  207. this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
  208. } else {
  209. if(event.pageY - $(document).scrollTop() < o.scrollSensitivity)
  210. scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
  211. else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity)
  212. scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
  213. if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity)
  214. scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
  215. else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity)
  216. scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
  217. }
  218. if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour)
  219. $.ui.ddmanager.prepareOffsets(this, event);
  220. }
  221. //Regenerate the absolute position used for position checks
  222. this.positionAbs = this._convertPositionTo("absolute");
  223. //Set the helper position
  224. if(!this.options.axis || this.options.axis != "y") this.helper[0].style.left = this.position.left+'px';
  225. if(!this.options.axis || this.options.axis != "x") this.helper[0].style.top = this.position.top+'px';
  226. //Rearrange
  227. for (var i = this.items.length - 1; i >= 0; i--) {
  228. //Cache variables and intersection, continue if no intersection
  229. var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item);
  230. if (!intersection) continue;
  231. // Only put the placeholder inside the current Container, skip all
  232. // items form other containers. This works because when moving
  233. // an item from one container to another the
  234. // currentContainer is switched before the placeholder is moved.
  235. //
  236. // Without this moving items in "sub-sortables" can cause the placeholder to jitter
  237. // beetween the outer and inner container.
  238. if (item.instance !== this.currentContainer) continue;
  239. if (itemElement != this.currentItem[0] //cannot intersect with itself
  240. && this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before
  241. && !$.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked
  242. && (this.options.type == 'semi-dynamic' ? !$.contains(this.element[0], itemElement) : true)
  243. //&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container
  244. ) {
  245. this.direction = intersection == 1 ? "down" : "up";
  246. if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) {
  247. this._rearrange(event, item);
  248. } else {
  249. break;
  250. }
  251. this._trigger("change", event, this._uiHash());
  252. break;
  253. }
  254. }
  255. //Post events to containers
  256. this._contactContainers(event);
  257. //Interconnect with droppables
  258. if($.ui.ddmanager) $.ui.ddmanager.drag(this, event);
  259. //Call callbacks
  260. this._trigger('sort', event, this._uiHash());
  261. this.lastPositionAbs = this.positionAbs;
  262. return false;
  263. },
  264. _mouseStop: function(event, noPropagation) {
  265. if(!event) return;
  266. //If we are using droppables, inform the manager about the drop
  267. if ($.ui.ddmanager && !this.options.dropBehaviour)
  268. $.ui.ddmanager.drop(this, event);
  269. if(this.options.revert) {
  270. var that = this;
  271. var cur = this.placeholder.offset();
  272. this.reverting = true;
  273. $(this.helper).animate({
  274. left: cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
  275. top: cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
  276. }, parseInt(this.options.revert, 10) || 500, function() {
  277. that._clear(event);
  278. });
  279. } else {
  280. this._clear(event, noPropagation);
  281. }
  282. return false;
  283. },
  284. cancel: function() {
  285. if(this.dragging) {
  286. this._mouseUp({ target: null });
  287. if(this.options.helper == "original")
  288. this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
  289. else
  290. this.currentItem.show();
  291. //Post deactivating events to containers
  292. for (var i = this.containers.length - 1; i >= 0; i--){
  293. this.containers[i]._trigger("deactivate", null, this._uiHash(this));
  294. if(this.containers[i].containerCache.over) {
  295. this.containers[i]._trigger("out", null, this._uiHash(this));
  296. this.containers[i].containerCache.over = 0;
  297. }
  298. }
  299. }
  300. if (this.placeholder) {
  301. //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
  302. if(this.placeholder[0].parentNode) this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
  303. if(this.options.helper != "original" && this.helper && this.helper[0].parentNode) this.helper.remove();
  304. $.extend(this, {
  305. helper: null,
  306. dragging: false,
  307. reverting: false,
  308. _noFinalSort: null
  309. });
  310. if(this.domPosition.prev) {
  311. $(this.domPosition.prev).after(this.currentItem);
  312. } else {
  313. $(this.domPosition.parent).prepend(this.currentItem);
  314. }
  315. }
  316. return this;
  317. },
  318. serialize: function(o) {
  319. var items = this._getItemsAsjQuery(o && o.connected);
  320. var str = []; o = o || {};
  321. $(items).each(function() {
  322. var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/));
  323. if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2]));
  324. });
  325. if(!str.length && o.key) {
  326. str.push(o.key + '=');
  327. }
  328. return str.join('&');
  329. },
  330. toArray: function(o) {
  331. var items = this._getItemsAsjQuery(o && o.connected);
  332. var ret = []; o = o || {};
  333. items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); });
  334. return ret;
  335. },
  336. /* Be careful with the following core functions */
  337. _intersectsWith: function(item) {
  338. var x1 = this.positionAbs.left,
  339. x2 = x1 + this.helperProportions.width,
  340. y1 = this.positionAbs.top,
  341. y2 = y1 + this.helperProportions.height;
  342. var l = item.left,
  343. r = l + item.width,
  344. t = item.top,
  345. b = t + item.height;
  346. var dyClick = this.offset.click.top,
  347. dxClick = this.offset.click.left;
  348. var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r;
  349. if( this.options.tolerance == "pointer"
  350. || this.options.forcePointerForContainers
  351. || (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height'])
  352. ) {
  353. return isOverElement;
  354. } else {
  355. return (l < x1 + (this.helperProportions.width / 2) // Right Half
  356. && x2 - (this.helperProportions.width / 2) < r // Left Half
  357. && t < y1 + (this.helperProportions.height / 2) // Bottom Half
  358. && y2 - (this.helperProportions.height / 2) < b ); // Top Half
  359. }
  360. },
  361. _intersectsWithPointer: function(item) {
  362. var isOverElementHeight = (this.options.axis === 'x') || $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
  363. isOverElementWidth = (this.options.axis === 'y') || $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
  364. isOverElement = isOverElementHeight && isOverElementWidth,
  365. verticalDirection = this._getDragVerticalDirection(),
  366. horizontalDirection = this._getDragHorizontalDirection();
  367. if (!isOverElement)
  368. return false;
  369. return this.floating ?
  370. ( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 )
  371. : ( verticalDirection && (verticalDirection == "down" ? 2 : 1) );
  372. },
  373. _intersectsWithSides: function(item) {
  374. var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
  375. isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
  376. verticalDirection = this._getDragVerticalDirection(),
  377. horizontalDirection = this._getDragHorizontalDirection();
  378. if (this.floating && horizontalDirection) {
  379. return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf));
  380. } else {
  381. return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf));
  382. }
  383. },
  384. _getDragVerticalDirection: function() {
  385. var delta = this.positionAbs.top - this.lastPositionAbs.top;
  386. return delta != 0 && (delta > 0 ? "down" : "up");
  387. },
  388. _getDragHorizontalDirection: function() {
  389. var delta = this.positionAbs.left - this.lastPositionAbs.left;
  390. return delta != 0 && (delta > 0 ? "right" : "left");
  391. },
  392. refresh: function(event) {
  393. this._refreshItems(event);
  394. this.refreshPositions();
  395. return this;
  396. },
  397. _connectWith: function() {
  398. var options = this.options;
  399. return options.connectWith.constructor == String
  400. ? [options.connectWith]
  401. : options.connectWith;
  402. },
  403. _getItemsAsjQuery: function(connected) {
  404. var items = [];
  405. var queries = [];
  406. var connectWith = this._connectWith();
  407. if(connectWith && connected) {
  408. for (var i = connectWith.length - 1; i >= 0; i--){
  409. var cur = $(connectWith[i]);
  410. for (var j = cur.length - 1; j >= 0; j--){
  411. var inst = $.data(cur[j], this.widgetName);
  412. if(inst && inst != this && !inst.options.disabled) {
  413. queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), inst]);
  414. }
  415. };
  416. };
  417. }
  418. queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), this]);
  419. for (var i = queries.length - 1; i >= 0; i--){
  420. queries[i][0].each(function() {
  421. items.push(this);
  422. });
  423. };
  424. return $(items);
  425. },
  426. _removeCurrentsFromItems: function() {
  427. var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
  428. this.items = $.grep(this.items, function (item) {
  429. for (var j=0; j < list.length; j++) {
  430. if(list[j] == item.item[0])
  431. return false;
  432. };
  433. return true;
  434. });
  435. },
  436. _refreshItems: function(event) {
  437. this.items = [];
  438. this.containers = [this];
  439. var items = this.items;
  440. var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]];
  441. var connectWith = this._connectWith();
  442. if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
  443. for (var i = connectWith.length - 1; i >= 0; i--){
  444. var cur = $(connectWith[i]);
  445. for (var j = cur.length - 1; j >= 0; j--){
  446. var inst = $.data(cur[j], this.widgetName);
  447. if(inst && inst != this && !inst.options.disabled) {
  448. queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
  449. this.containers.push(inst);
  450. }
  451. };
  452. };
  453. }
  454. for (var i = queries.length - 1; i >= 0; i--) {
  455. var targetData = queries[i][1];
  456. var _queries = queries[i][0];
  457. for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
  458. var item = $(_queries[j]);
  459. item.data(this.widgetName + '-item', targetData); // Data for target checking (mouse manager)
  460. items.push({
  461. item: item,
  462. instance: targetData,
  463. width: 0, height: 0,
  464. left: 0, top: 0
  465. });
  466. };
  467. };
  468. },
  469. refreshPositions: function(fast) {
  470. //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
  471. if(this.offsetParent && this.helper) {
  472. this.offset.parent = this._getParentOffset();
  473. }
  474. for (var i = this.items.length - 1; i >= 0; i--){
  475. var item = this.items[i];
  476. //We ignore calculating positions of all connected containers when we're not over them
  477. if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0])
  478. continue;
  479. var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
  480. if (!fast) {
  481. item.width = t.outerWidth();
  482. item.height = t.outerHeight();
  483. }
  484. var p = t.offset();
  485. item.left = p.left;
  486. item.top = p.top;
  487. };
  488. if(this.options.custom && this.options.custom.refreshContainers) {
  489. this.options.custom.refreshContainers.call(this);
  490. } else {
  491. for (var i = this.containers.length - 1; i >= 0; i--){
  492. var p = this.containers[i].element.offset();
  493. this.containers[i].containerCache.left = p.left;
  494. this.containers[i].containerCache.top = p.top;
  495. this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
  496. this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
  497. };
  498. }
  499. return this;
  500. },
  501. _createPlaceholder: function(that) {
  502. that = that || this;
  503. var o = that.options;
  504. if(!o.placeholder || o.placeholder.constructor == String) {
  505. var className = o.placeholder;
  506. o.placeholder = {
  507. element: function() {
  508. var el = $(document.createElement(that.currentItem[0].nodeName))
  509. .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
  510. .removeClass("ui-sortable-helper")[0];
  511. if(!className)
  512. el.style.visibility = "hidden";
  513. return el;
  514. },
  515. update: function(container, p) {
  516. // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
  517. // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
  518. if(className && !o.forcePlaceholderSize) return;
  519. //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item
  520. if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css('paddingTop')||0, 10) - parseInt(that.currentItem.css('paddingBottom')||0, 10)); };
  521. if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css('paddingLeft')||0, 10) - parseInt(that.currentItem.css('paddingRight')||0, 10)); };
  522. }
  523. };
  524. }
  525. //Create the placeholder
  526. that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
  527. //Append it after the actual current item
  528. that.currentItem.after(that.placeholder);
  529. //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
  530. o.placeholder.update(that, that.placeholder);
  531. },
  532. _contactContainers: function(event) {
  533. // get innermost container that intersects with item
  534. var innermostContainer = null, innermostIndex = null;
  535. for (var i = this.containers.length - 1; i >= 0; i--){
  536. // never consider a container that's located within the item itself
  537. if($.contains(this.currentItem[0], this.containers[i].element[0]))
  538. continue;
  539. if(this._intersectsWith(this.containers[i].containerCache)) {
  540. // if we've already found a container and it's more "inner" than this, then continue
  541. if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0]))
  542. continue;
  543. innermostContainer = this.containers[i];
  544. innermostIndex = i;
  545. } else {
  546. // container doesn't intersect. trigger "out" event if necessary
  547. if(this.containers[i].containerCache.over) {
  548. this.containers[i]._trigger("out", event, this._uiHash(this));
  549. this.containers[i].containerCache.over = 0;
  550. }
  551. }
  552. }
  553. // if no intersecting containers found, return
  554. if(!innermostContainer) return;
  555. // move the item into the container if it's not there already
  556. if(this.containers.length === 1) {
  557. this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
  558. this.containers[innermostIndex].containerCache.over = 1;
  559. } else {
  560. //When entering a new container, we will find the item with the least distance and append our item near it
  561. var dist = 10000; var itemWithLeastDistance = null;
  562. var posProperty = this.containers[innermostIndex].floating ? 'left' : 'top';
  563. var sizeProperty = this.containers[innermostIndex].floating ? 'width' : 'height';
  564. var base = this.positionAbs[posProperty] + this.offset.click[posProperty];
  565. for (var j = this.items.length - 1; j >= 0; j--) {
  566. if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) continue;
  567. if(this.items[j].item[0] == this.currentItem[0]) continue;
  568. var cur = this.items[j].item.offset()[posProperty];
  569. var nearBottom = false;
  570. if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){
  571. nearBottom = true;
  572. cur += this.items[j][sizeProperty];
  573. }
  574. if(Math.abs(cur - base) < dist) {
  575. dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j];
  576. this.direction = nearBottom ? "up": "down";
  577. }
  578. }
  579. if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled
  580. return;
  581. this.currentContainer = this.containers[innermostIndex];
  582. itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
  583. this._trigger("change", event, this._uiHash());
  584. this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
  585. //Update the placeholder
  586. this.options.placeholder.update(this.currentContainer, this.placeholder);
  587. this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
  588. this.containers[innermostIndex].containerCache.over = 1;
  589. }
  590. },
  591. _createHelper: function(event) {
  592. var o = this.options;
  593. var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem);
  594. if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already
  595. $(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
  596. if(helper[0] == this.currentItem[0])
  597. this._storedCSS = { width: this.currentItem[0].style.width, height: this.currentItem[0].style.height, position: this.currentItem.css("position"), top: this.currentItem.css("top"), left: this.currentItem.css("left") };
  598. if(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width());
  599. if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height());
  600. return helper;
  601. },
  602. _adjustOffsetFromHelper: function(obj) {
  603. if (typeof obj == 'string') {
  604. obj = obj.split(' ');
  605. }
  606. if ($.isArray(obj)) {
  607. obj = {left: +obj[0], top: +obj[1] || 0};
  608. }
  609. if ('left' in obj) {
  610. this.offset.click.left = obj.left + this.margins.left;
  611. }
  612. if ('right' in obj) {
  613. this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
  614. }
  615. if ('top' in obj) {
  616. this.offset.click.top = obj.top + this.margins.top;
  617. }
  618. if ('bottom' in obj) {
  619. this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
  620. }
  621. },
  622. _getParentOffset: function() {
  623. //Get the offsetParent and cache its position
  624. this.offsetParent = this.helper.offsetParent();
  625. var po = this.offsetParent.offset();
  626. // This is a special case where we need to modify a offset calculated on start, since the following happened:
  627. // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
  628. // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
  629. // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
  630. if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
  631. po.left += this.scrollParent.scrollLeft();
  632. po.top += this.scrollParent.scrollTop();
  633. }
  634. if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information
  635. || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.ui.ie)) //Ugly IE fix
  636. po = { top: 0, left: 0 };
  637. return {
  638. top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
  639. left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
  640. };
  641. },
  642. _getRelativeOffset: function() {
  643. if(this.cssPosition == "relative") {
  644. var p = this.currentItem.position();
  645. return {
  646. top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
  647. left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
  648. };
  649. } else {
  650. return { top: 0, left: 0 };
  651. }
  652. },
  653. _cacheMargins: function() {
  654. this.margins = {
  655. left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
  656. top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
  657. };
  658. },
  659. _cacheHelperProportions: function() {
  660. this.helperProportions = {
  661. width: this.helper.outerWidth(),
  662. height: this.helper.outerHeight()
  663. };
  664. },
  665. _setContainment: function() {
  666. var o = this.options;
  667. if(o.containment == 'parent') o.containment = this.helper[0].parentNode;
  668. if(o.containment == 'document' || o.containment == 'window') this.containment = [
  669. 0 - this.offset.relative.left - this.offset.parent.left,
  670. 0 - this.offset.relative.top - this.offset.parent.top,
  671. $(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left,
  672. ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
  673. ];
  674. if(!(/^(document|window|parent)$/).test(o.containment)) {
  675. var ce = $(o.containment)[0];
  676. var co = $(o.containment).offset();
  677. var over = ($(ce).css("overflow") != 'hidden');
  678. this.containment = [
  679. co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
  680. co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
  681. co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left,
  682. co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top
  683. ];
  684. }
  685. },
  686. _convertPositionTo: function(d, pos) {
  687. if(!pos) pos = this.position;
  688. var mod = d == "absolute" ? 1 : -1;
  689. var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
  690. return {
  691. top: (
  692. pos.top // The absolute mouse position
  693. + this.offset.relative.top * mod // Only for relative positioned nodes: Relative offset from element to offset parent
  694. + this.offset.parent.top * mod // The offsetParent's offset without borders (offset + border)
  695. - ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
  696. ),
  697. left: (
  698. pos.left // The absolute mouse position
  699. + this.offset.relative.left * mod // Only for relative positioned nodes: Relative offset from element to offset parent
  700. + this.offset.parent.left * mod // The offsetParent's offset without borders (offset + border)
  701. - ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
  702. )
  703. };
  704. },
  705. _generatePosition: function(event) {
  706. var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
  707. // This is another very weird special case that only happens for relative elements:
  708. // 1. If the css position is relative
  709. // 2. and the scroll parent is the document or similar to the offset parent
  710. // we have to refresh the relative offset during the scroll so there are no jumps
  711. if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) {
  712. this.offset.relative = this._getRelativeOffset();
  713. }
  714. var pageX = event.pageX;
  715. var pageY = event.pageY;
  716. /*
  717. * - Position constraining -
  718. * Constrain the position to a mix of grid, containment.
  719. */
  720. if(this.originalPosition) { //If we are not dragging yet, we won't check for options
  721. if(this.containment) {
  722. if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left;
  723. if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top;
  724. if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left;
  725. if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top;
  726. }
  727. if(o.grid) {
  728. var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
  729. pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
  730. var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
  731. pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
  732. }
  733. }
  734. return {
  735. top: (
  736. pageY // The absolute mouse position
  737. - this.offset.click.top // Click offset (relative to the element)
  738. - this.offset.relative.top // Only for relative positioned nodes: Relative offset from element to offset parent
  739. - this.offset.parent.top // The offsetParent's offset without borders (offset + border)
  740. + ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
  741. ),
  742. left: (
  743. pageX // The absolute mouse position
  744. - this.offset.click.left // Click offset (relative to the element)
  745. - this.offset.relative.left // Only for relative positioned nodes: Relative offset from element to offset parent
  746. - this.offset.parent.left // The offsetParent's offset without borders (offset + border)
  747. + ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
  748. )
  749. };
  750. },
  751. _rearrange: function(event, i, a, hardRefresh) {
  752. a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling));
  753. //Various things done here to improve the performance:
  754. // 1. we create a setTimeout, that calls refreshPositions
  755. // 2. on the instance, we have a counter variable, that get's higher after every append
  756. // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
  757. // 4. this lets only the last addition to the timeout stack through
  758. this.counter = this.counter ? ++this.counter : 1;
  759. var counter = this.counter;
  760. this._delay(function() {
  761. if(counter == this.counter) this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
  762. });
  763. },
  764. _clear: function(event, noPropagation) {
  765. this.reverting = false;
  766. // We delay all events that have to be triggered to after the point where the placeholder has been removed and
  767. // everything else normalized again
  768. var delayedTriggers = [];
  769. // We first have to update the dom position of the actual currentItem
  770. // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
  771. if(!this._noFinalSort && this.currentItem.parent().length) this.placeholder.before(this.currentItem);
  772. this._noFinalSort = null;
  773. if(this.helper[0] == this.currentItem[0]) {
  774. for(var i in this._storedCSS) {
  775. if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = '';
  776. }
  777. this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
  778. } else {
  779. this.currentItem.show();
  780. }
  781. if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
  782. if((this.fromOutside || this.domPosition.prev != this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent != this.currentItem.parent()[0]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
  783. // Check if the items Container has Changed and trigger appropriate
  784. // events.
  785. if (this !== this.currentContainer) {
  786. if(!noPropagation) {
  787. delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
  788. delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
  789. delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
  790. }
  791. }
  792. //Post events to containers
  793. for (var i = this.containers.length - 1; i >= 0; i--){
  794. if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i]));
  795. if(this.containers[i].containerCache.over) {
  796. delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i]));
  797. this.containers[i].containerCache.over = 0;
  798. }
  799. }
  800. //Do what was originally in plugins
  801. if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor
  802. if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset opacity
  803. if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index
  804. this.dragging = false;
  805. if(this.cancelHelperRemoval) {
  806. if(!noPropagation) {
  807. this._trigger("beforeStop", event, this._uiHash());
  808. for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
  809. this._trigger("stop", event, this._uiHash());
  810. }
  811. this.fromOutside = false;
  812. return false;
  813. }
  814. if(!noPropagation) this._trigger("beforeStop", event, this._uiHash());
  815. //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
  816. this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
  817. if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null;
  818. if(!noPropagation) {
  819. for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events
  820. this._trigger("stop", event, this._uiHash());
  821. }
  822. this.fromOutside = false;
  823. return true;
  824. },
  825. _trigger: function() {
  826. if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
  827. this.cancel();
  828. }
  829. },
  830. _uiHash: function(_inst) {
  831. var inst = _inst || this;
  832. return {
  833. helper: inst.helper,
  834. placeholder: inst.placeholder || $([]),
  835. position: inst.position,
  836. originalPosition: inst.originalPosition,
  837. offset: inst.positionAbs,
  838. item: inst.currentItem,
  839. sender: _inst ? _inst.element : null
  840. };
  841. }
  842. });
  843. })(jQuery);