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.
 
 
 
 
 
 

1056 lines
38 KiB

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