You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

jquery.ui.sortable.js 42KB

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