2 * jQuery UI Sortable 1.11.2
5 * Copyright 2014 jQuery Foundation and other contributors
6 * Released under the MIT license.
7 * http://jquery.org/license
9 * http://api.jqueryui.com/sortable/
11 (function( factory ) {
12 if ( typeof define === "function" && define.amd ) {
14 // AMD. Register as an anonymous module.
28 return $.widget("ui.sortable", $.ui.mouse, {
30 widgetEventPrefix: "sort",
40 forcePlaceholderSize: false,
41 forceHelperSize: false,
50 scrollSensitivity: 20,
53 tolerance: "intersect",
71 _isOverAxis: function( x, reference, size ) {
72 return ( x >= reference ) && ( x < ( reference + size ) );
75 _isFloating: function( item ) {
76 return (/left|right/).test(item.css("float")) || (/inline|table-cell/).test(item.css("display"));
82 this.containerCache = {};
83 this.element.addClass("ui-sortable");
88 //Let's determine if the items are being displayed horizontally
89 this.floating = this.items.length ? o.axis === "x" || this._isFloating(this.items[0].item) : false;
91 //Let's determine the parent's offset
92 this.offset = this.element.offset();
94 //Initialize mouse events for interaction
97 this._setHandleClassName();
104 _setOption: function( key, value ) {
105 this._super( key, value );
107 if ( key === "handle" ) {
108 this._setHandleClassName();
112 _setHandleClassName: function() {
113 this.element.find( ".ui-sortable-handle" ).removeClass( "ui-sortable-handle" );
114 $.each( this.items, function() {
115 ( this.instance.options.handle ?
116 this.item.find( this.instance.options.handle ) : this.item )
117 .addClass( "ui-sortable-handle" );
121 _destroy: function() {
123 .removeClass( "ui-sortable ui-sortable-disabled" )
124 .find( ".ui-sortable-handle" )
125 .removeClass( "ui-sortable-handle" );
126 this._mouseDestroy();
128 for ( var i = this.items.length - 1; i >= 0; i-- ) {
129 this.items[i].item.removeData(this.widgetName + "-item");
135 _mouseCapture: function(event, overrideHandle) {
136 var currentItem = null,
140 if (this.reverting) {
144 if(this.options.disabled || this.options.type === "static") {
148 //We have to refresh the items data once first
149 this._refreshItems(event);
151 //Find out if the clicked node (or one of its parents) is a actual item in this.items
152 $(event.target).parents().each(function() {
153 if($.data(this, that.widgetName + "-item") === that) {
154 currentItem = $(this);
158 if($.data(event.target, that.widgetName + "-item") === that) {
159 currentItem = $(event.target);
165 if(this.options.handle && !overrideHandle) {
166 $(this.options.handle, currentItem).find("*").addBack().each(function() {
167 if(this === event.target) {
176 this.currentItem = currentItem;
177 this._removeCurrentsFromItems();
182 _mouseStart: function(event, overrideHandle, noActivation) {
187 this.currentContainer = this;
189 //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture
190 this.refreshPositions();
192 //Create and append the visible helper
193 this.helper = this._createHelper(event);
195 //Cache the helper size
196 this._cacheHelperProportions();
199 * - Position generation -
200 * This block generates everything position related - it's the core of draggables.
203 //Cache the margins of the original element
204 this._cacheMargins();
206 //Get the next scrolling parent
207 this.scrollParent = this.helper.scrollParent();
209 //The element's absolute position on the page minus margins
210 this.offset = this.currentItem.offset();
212 top: this.offset.top - this.margins.top,
213 left: this.offset.left - this.margins.left
216 $.extend(this.offset, {
217 click: { //Where the click happened, relative to the element
218 left: event.pageX - this.offset.left,
219 top: event.pageY - this.offset.top
221 parent: this._getParentOffset(),
222 relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
225 // Only after we got the offset, we can change the helper's position to absolute
226 // TODO: Still need to figure out a way to make relative sorting possible
227 this.helper.css("position", "absolute");
228 this.cssPosition = this.helper.css("position");
230 //Generate the original position
231 this.originalPosition = this._generatePosition(event);
232 this.originalPageX = event.pageX;
233 this.originalPageY = event.pageY;
235 //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
236 (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
238 //Cache the former DOM position
239 this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] };
241 //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
242 if(this.helper[0] !== this.currentItem[0]) {
243 this.currentItem.hide();
246 //Create the placeholder
247 this._createPlaceholder();
249 //Set a containment if given in the options
251 this._setContainment();
254 if( o.cursor && o.cursor !== "auto" ) { // cursor option
255 body = this.document.find( "body" );
258 this.storedCursor = body.css( "cursor" );
259 body.css( "cursor", o.cursor );
261 this.storedStylesheet = $( "<style>*{ cursor: "+o.cursor+" !important; }</style>" ).appendTo( body );
264 if(o.opacity) { // opacity option
265 if (this.helper.css("opacity")) {
266 this._storedOpacity = this.helper.css("opacity");
268 this.helper.css("opacity", o.opacity);
271 if(o.zIndex) { // zIndex option
272 if (this.helper.css("zIndex")) {
273 this._storedZIndex = this.helper.css("zIndex");
275 this.helper.css("zIndex", o.zIndex);
279 if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
280 this.overflowOffset = this.scrollParent.offset();
284 this._trigger("start", event, this._uiHash());
286 //Recache the helper size
287 if(!this._preserveHelperProportions) {
288 this._cacheHelperProportions();
292 //Post "activate" events to possible containers
293 if( !noActivation ) {
294 for ( i = this.containers.length - 1; i >= 0; i-- ) {
295 this.containers[ i ]._trigger( "activate", event, this._uiHash( this ) );
299 //Prepare possible droppables
301 $.ui.ddmanager.current = this;
304 if ($.ui.ddmanager && !o.dropBehaviour) {
305 $.ui.ddmanager.prepareOffsets(this, event);
308 this.dragging = true;
310 this.helper.addClass("ui-sortable-helper");
311 this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position
316 _mouseDrag: function(event) {
317 var i, item, itemElement, intersection,
321 //Compute the helpers position
322 this.position = this._generatePosition(event);
323 this.positionAbs = this._convertPositionTo("absolute");
325 if (!this.lastPositionAbs) {
326 this.lastPositionAbs = this.positionAbs;
330 if(this.options.scroll) {
331 if(this.scrollParent[0] !== document && this.scrollParent[0].tagName !== "HTML") {
333 if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
334 this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed;
335 } else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) {
336 this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed;
339 if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
340 this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed;
341 } else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) {
342 this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed;
347 if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
348 scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
349 } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
350 scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
353 if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
354 scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
355 } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
356 scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
361 if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
362 $.ui.ddmanager.prepareOffsets(this, event);
366 //Regenerate the absolute position used for position checks
367 this.positionAbs = this._convertPositionTo("absolute");
369 //Set the helper position
370 if(!this.options.axis || this.options.axis !== "y") {
371 this.helper[0].style.left = this.position.left+"px";
373 if(!this.options.axis || this.options.axis !== "x") {
374 this.helper[0].style.top = this.position.top+"px";
378 for (i = this.items.length - 1; i >= 0; i--) {
380 //Cache variables and intersection, continue if no intersection
381 item = this.items[i];
382 itemElement = item.item[0];
383 intersection = this._intersectsWithPointer(item);
388 // Only put the placeholder inside the current Container, skip all
389 // items from other containers. This works because when moving
390 // an item from one container to another the
391 // currentContainer is switched before the placeholder is moved.
393 // Without this, moving items in "sub-sortables" can cause
394 // the placeholder to jitter between the outer and inner container.
395 if (item.instance !== this.currentContainer) {
399 // cannot intersect with itself
400 // no useless actions that have been done before
401 // no action if the item moved is the parent of the item checked
402 if (itemElement !== this.currentItem[0] &&
403 this.placeholder[intersection === 1 ? "next" : "prev"]()[0] !== itemElement &&
404 !$.contains(this.placeholder[0], itemElement) &&
405 (this.options.type === "semi-dynamic" ? !$.contains(this.element[0], itemElement) : true)
408 this.direction = intersection === 1 ? "down" : "up";
410 if (this.options.tolerance === "pointer" || this._intersectsWithSides(item)) {
411 this._rearrange(event, item);
416 this._trigger("change", event, this._uiHash());
421 //Post events to containers
422 this._contactContainers(event);
424 //Interconnect with droppables
426 $.ui.ddmanager.drag(this, event);
430 this._trigger("sort", event, this._uiHash());
432 this.lastPositionAbs = this.positionAbs;
437 _mouseStop: function(event, noPropagation) {
443 //If we are using droppables, inform the manager about the drop
444 if ($.ui.ddmanager && !this.options.dropBehaviour) {
445 $.ui.ddmanager.drop(this, event);
448 if(this.options.revert) {
450 cur = this.placeholder.offset(),
451 axis = this.options.axis,
454 if ( !axis || axis === "x" ) {
455 animation.left = cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollLeft);
457 if ( !axis || axis === "y" ) {
458 animation.top = cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] === document.body ? 0 : this.offsetParent[0].scrollTop);
460 this.reverting = true;
461 $(this.helper).animate( animation, parseInt(this.options.revert, 10) || 500, function() {
465 this._clear(event, noPropagation);
476 this._mouseUp({ target: null });
478 if(this.options.helper === "original") {
479 this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
481 this.currentItem.show();
484 //Post deactivating events to containers
485 for (var i = this.containers.length - 1; i >= 0; i--){
486 this.containers[i]._trigger("deactivate", null, this._uiHash(this));
487 if(this.containers[i].containerCache.over) {
488 this.containers[i]._trigger("out", null, this._uiHash(this));
489 this.containers[i].containerCache.over = 0;
495 if (this.placeholder) {
496 //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
497 if(this.placeholder[0].parentNode) {
498 this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
500 if(this.options.helper !== "original" && this.helper && this.helper[0].parentNode) {
501 this.helper.remove();
511 if(this.domPosition.prev) {
512 $(this.domPosition.prev).after(this.currentItem);
514 $(this.domPosition.parent).prepend(this.currentItem);
522 serialize: function(o) {
524 var items = this._getItemsAsjQuery(o && o.connected),
528 $(items).each(function() {
529 var res = ($(o.item || this).attr(o.attribute || "id") || "").match(o.expression || (/(.+)[\-=_](.+)/));
531 str.push((o.key || res[1]+"[]")+"="+(o.key && o.expression ? res[1] : res[2]));
535 if(!str.length && o.key) {
536 str.push(o.key + "=");
539 return str.join("&");
543 toArray: function(o) {
545 var items = this._getItemsAsjQuery(o && o.connected),
550 items.each(function() { ret.push($(o.item || this).attr(o.attribute || "id") || ""); });
555 /* Be careful with the following core functions */
556 _intersectsWith: function(item) {
558 var x1 = this.positionAbs.left,
559 x2 = x1 + this.helperProportions.width,
560 y1 = this.positionAbs.top,
561 y2 = y1 + this.helperProportions.height,
566 dyClick = this.offset.click.top,
567 dxClick = this.offset.click.left,
568 isOverElementHeight = ( this.options.axis === "x" ) || ( ( y1 + dyClick ) > t && ( y1 + dyClick ) < b ),
569 isOverElementWidth = ( this.options.axis === "y" ) || ( ( x1 + dxClick ) > l && ( x1 + dxClick ) < r ),
570 isOverElement = isOverElementHeight && isOverElementWidth;
572 if ( this.options.tolerance === "pointer" ||
573 this.options.forcePointerForContainers ||
574 (this.options.tolerance !== "pointer" && this.helperProportions[this.floating ? "width" : "height"] > item[this.floating ? "width" : "height"])
576 return isOverElement;
579 return (l < x1 + (this.helperProportions.width / 2) && // Right Half
580 x2 - (this.helperProportions.width / 2) < r && // Left Half
581 t < y1 + (this.helperProportions.height / 2) && // Bottom Half
582 y2 - (this.helperProportions.height / 2) < b ); // Top Half
587 _intersectsWithPointer: function(item) {
589 var isOverElementHeight = (this.options.axis === "x") || this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height),
590 isOverElementWidth = (this.options.axis === "y") || this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width),
591 isOverElement = isOverElementHeight && isOverElementWidth,
592 verticalDirection = this._getDragVerticalDirection(),
593 horizontalDirection = this._getDragHorizontalDirection();
595 if (!isOverElement) {
599 return this.floating ?
600 ( ((horizontalDirection && horizontalDirection === "right") || verticalDirection === "down") ? 2 : 1 )
601 : ( verticalDirection && (verticalDirection === "down" ? 2 : 1) );
605 _intersectsWithSides: function(item) {
607 var isOverBottomHalf = this._isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height),
608 isOverRightHalf = this._isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width),
609 verticalDirection = this._getDragVerticalDirection(),
610 horizontalDirection = this._getDragHorizontalDirection();
612 if (this.floating && horizontalDirection) {
613 return ((horizontalDirection === "right" && isOverRightHalf) || (horizontalDirection === "left" && !isOverRightHalf));
615 return verticalDirection && ((verticalDirection === "down" && isOverBottomHalf) || (verticalDirection === "up" && !isOverBottomHalf));
620 _getDragVerticalDirection: function() {
621 var delta = this.positionAbs.top - this.lastPositionAbs.top;
622 return delta !== 0 && (delta > 0 ? "down" : "up");
625 _getDragHorizontalDirection: function() {
626 var delta = this.positionAbs.left - this.lastPositionAbs.left;
627 return delta !== 0 && (delta > 0 ? "right" : "left");
630 refresh: function(event) {
631 this._refreshItems(event);
632 this._setHandleClassName();
633 this.refreshPositions();
637 _connectWith: function() {
638 var options = this.options;
639 return options.connectWith.constructor === String ? [options.connectWith] : options.connectWith;
642 _getItemsAsjQuery: function(connected) {
647 connectWith = this._connectWith();
649 if(connectWith && connected) {
650 for (i = connectWith.length - 1; i >= 0; i--){
651 cur = $(connectWith[i]);
652 for ( j = cur.length - 1; j >= 0; j--){
653 inst = $.data(cur[j], this.widgetFullName);
654 if(inst && inst !== this && !inst.options.disabled) {
655 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]);
661 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]);
663 function addItems() {
666 for (i = queries.length - 1; i >= 0; i--){
667 queries[i][0].each( addItems );
674 _removeCurrentsFromItems: function() {
676 var list = this.currentItem.find(":data(" + this.widgetName + "-item)");
678 this.items = $.grep(this.items, function (item) {
679 for (var j=0; j < list.length; j++) {
680 if(list[j] === item.item[0]) {
689 _refreshItems: function(event) {
692 this.containers = [this];
694 var i, j, cur, inst, targetData, _queries, item, queriesLength,
696 queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]],
697 connectWith = this._connectWith();
699 if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down
700 for (i = connectWith.length - 1; i >= 0; i--){
701 cur = $(connectWith[i]);
702 for (j = cur.length - 1; j >= 0; j--){
703 inst = $.data(cur[j], this.widgetFullName);
704 if(inst && inst !== this && !inst.options.disabled) {
705 queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]);
706 this.containers.push(inst);
712 for (i = queries.length - 1; i >= 0; i--) {
713 targetData = queries[i][1];
714 _queries = queries[i][0];
716 for (j=0, queriesLength = _queries.length; j < queriesLength; j++) {
717 item = $(_queries[j]);
719 item.data(this.widgetName + "-item", targetData); // Data for target checking (mouse manager)
723 instance: targetData,
732 refreshPositions: function(fast) {
734 //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change
735 if(this.offsetParent && this.helper) {
736 this.offset.parent = this._getParentOffset();
741 for (i = this.items.length - 1; i >= 0; i--){
742 item = this.items[i];
744 //We ignore calculating positions of all connected containers when we're not over them
745 if(item.instance !== this.currentContainer && this.currentContainer && item.item[0] !== this.currentItem[0]) {
749 t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item;
752 item.width = t.outerWidth();
753 item.height = t.outerHeight();
761 if(this.options.custom && this.options.custom.refreshContainers) {
762 this.options.custom.refreshContainers.call(this);
764 for (i = this.containers.length - 1; i >= 0; i--){
765 p = this.containers[i].element.offset();
766 this.containers[i].containerCache.left = p.left;
767 this.containers[i].containerCache.top = p.top;
768 this.containers[i].containerCache.width = this.containers[i].element.outerWidth();
769 this.containers[i].containerCache.height = this.containers[i].element.outerHeight();
776 _createPlaceholder: function(that) {
781 if(!o.placeholder || o.placeholder.constructor === String) {
782 className = o.placeholder;
784 element: function() {
786 var nodeName = that.currentItem[0].nodeName.toLowerCase(),
787 element = $( "<" + nodeName + ">", that.document[0] )
788 .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder")
789 .removeClass("ui-sortable-helper");
791 if ( nodeName === "tr" ) {
792 that.currentItem.children().each(function() {
793 $( "<td> </td>", that.document[0] )
794 .attr( "colspan", $( this ).attr( "colspan" ) || 1 )
795 .appendTo( element );
797 } else if ( nodeName === "img" ) {
798 element.attr( "src", that.currentItem.attr( "src" ) );
802 element.css( "visibility", "hidden" );
807 update: function(container, p) {
809 // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that
810 // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified
811 if(className && !o.forcePlaceholderSize) {
815 //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
816 if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css("paddingTop")||0, 10) - parseInt(that.currentItem.css("paddingBottom")||0, 10)); }
817 if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css("paddingLeft")||0, 10) - parseInt(that.currentItem.css("paddingRight")||0, 10)); }
822 //Create the placeholder
823 that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem));
825 //Append it after the actual current item
826 that.currentItem.after(that.placeholder);
828 //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317)
829 o.placeholder.update(that, that.placeholder);
833 _contactContainers: function(event) {
834 var i, j, dist, itemWithLeastDistance, posProperty, sizeProperty, cur, nearBottom, floating, axis,
835 innermostContainer = null,
836 innermostIndex = null;
838 // get innermost container that intersects with item
839 for (i = this.containers.length - 1; i >= 0; i--) {
841 // never consider a container that's located within the item itself
842 if($.contains(this.currentItem[0], this.containers[i].element[0])) {
846 if(this._intersectsWith(this.containers[i].containerCache)) {
848 // if we've already found a container and it's more "inner" than this, then continue
849 if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) {
853 innermostContainer = this.containers[i];
857 // container doesn't intersect. trigger "out" event if necessary
858 if(this.containers[i].containerCache.over) {
859 this.containers[i]._trigger("out", event, this._uiHash(this));
860 this.containers[i].containerCache.over = 0;
866 // if no intersecting containers found, return
867 if(!innermostContainer) {
871 // move the item into the container if it's not there already
872 if(this.containers.length === 1) {
873 if (!this.containers[innermostIndex].containerCache.over) {
874 this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
875 this.containers[innermostIndex].containerCache.over = 1;
879 //When entering a new container, we will find the item with the least distance and append our item near it
881 itemWithLeastDistance = null;
882 floating = innermostContainer.floating || this._isFloating(this.currentItem);
883 posProperty = floating ? "left" : "top";
884 sizeProperty = floating ? "width" : "height";
885 axis = floating ? "clientX" : "clientY";
887 for (j = this.items.length - 1; j >= 0; j--) {
888 if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) {
891 if(this.items[j].item[0] === this.currentItem[0]) {
895 cur = this.items[j].item.offset()[posProperty];
897 if ( event[ axis ] - cur > this.items[ j ][ sizeProperty ] / 2 ) {
901 if ( Math.abs( event[ axis ] - cur ) < dist ) {
902 dist = Math.abs( event[ axis ] - cur );
903 itemWithLeastDistance = this.items[ j ];
904 this.direction = nearBottom ? "up": "down";
908 //Check if dropOnEmpty is enabled
909 if(!itemWithLeastDistance && !this.options.dropOnEmpty) {
913 if(this.currentContainer === this.containers[innermostIndex]) {
914 if ( !this.currentContainer.containerCache.over ) {
915 this.containers[ innermostIndex ]._trigger( "over", event, this._uiHash() );
916 this.currentContainer.containerCache.over = 1;
921 itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true);
922 this._trigger("change", event, this._uiHash());
923 this.containers[innermostIndex]._trigger("change", event, this._uiHash(this));
924 this.currentContainer = this.containers[innermostIndex];
926 //Update the placeholder
927 this.options.placeholder.update(this.currentContainer, this.placeholder);
929 this.containers[innermostIndex]._trigger("over", event, this._uiHash(this));
930 this.containers[innermostIndex].containerCache.over = 1;
936 _createHelper: function(event) {
938 var o = this.options,
939 helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper === "clone" ? this.currentItem.clone() : this.currentItem);
941 //Add the helper to the DOM if that didn't happen already
942 if(!helper.parents("body").length) {
943 $(o.appendTo !== "parent" ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]);
946 if(helper[0] === this.currentItem[0]) {
947 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") };
950 if(!helper[0].style.width || o.forceHelperSize) {
951 helper.width(this.currentItem.width());
953 if(!helper[0].style.height || o.forceHelperSize) {
954 helper.height(this.currentItem.height());
961 _adjustOffsetFromHelper: function(obj) {
962 if (typeof obj === "string") {
963 obj = obj.split(" ");
965 if ($.isArray(obj)) {
966 obj = {left: +obj[0], top: +obj[1] || 0};
969 this.offset.click.left = obj.left + this.margins.left;
971 if ("right" in obj) {
972 this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
975 this.offset.click.top = obj.top + this.margins.top;
977 if ("bottom" in obj) {
978 this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
982 _getParentOffset: function() {
985 //Get the offsetParent and cache its position
986 this.offsetParent = this.helper.offsetParent();
987 var po = this.offsetParent.offset();
989 // This is a special case where we need to modify a offset calculated on start, since the following happened:
990 // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
991 // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
992 // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
993 if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
994 po.left += this.scrollParent.scrollLeft();
995 po.top += this.scrollParent.scrollTop();
998 // This needs to be actually done for all browsers, since pageX/pageY includes this information
999 // with an ugly IE fix
1000 if( this.offsetParent[0] === document.body || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
1001 po = { top: 0, left: 0 };
1005 top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
1006 left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
1011 _getRelativeOffset: function() {
1013 if(this.cssPosition === "relative") {
1014 var p = this.currentItem.position();
1016 top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
1017 left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
1020 return { top: 0, left: 0 };
1025 _cacheMargins: function() {
1027 left: (parseInt(this.currentItem.css("marginLeft"),10) || 0),
1028 top: (parseInt(this.currentItem.css("marginTop"),10) || 0)
1032 _cacheHelperProportions: function() {
1033 this.helperProportions = {
1034 width: this.helper.outerWidth(),
1035 height: this.helper.outerHeight()
1039 _setContainment: function() {
1043 if(o.containment === "parent") {
1044 o.containment = this.helper[0].parentNode;
1046 if(o.containment === "document" || o.containment === "window") {
1047 this.containment = [
1048 0 - this.offset.relative.left - this.offset.parent.left,
1049 0 - this.offset.relative.top - this.offset.parent.top,
1050 $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
1051 ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
1055 if(!(/^(document|window|parent)$/).test(o.containment)) {
1056 ce = $(o.containment)[0];
1057 co = $(o.containment).offset();
1058 over = ($(ce).css("overflow") !== "hidden");
1060 this.containment = [
1061 co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left,
1062 co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top,
1063 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,
1064 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
1070 _convertPositionTo: function(d, pos) {
1073 pos = this.position;
1075 var mod = d === "absolute" ? 1 : -1,
1076 scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
1077 scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
1081 pos.top + // The absolute mouse position
1082 this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
1083 this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
1084 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
1087 pos.left + // The absolute mouse position
1088 this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
1089 this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
1090 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
1096 _generatePosition: function(event) {
1100 pageX = event.pageX,
1101 pageY = event.pageY,
1102 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);
1104 // This is another very weird special case that only happens for relative elements:
1105 // 1. If the css position is relative
1106 // 2. and the scroll parent is the document or similar to the offset parent
1107 // we have to refresh the relative offset during the scroll so there are no jumps
1108 if(this.cssPosition === "relative" && !(this.scrollParent[0] !== document && this.scrollParent[0] !== this.offsetParent[0])) {
1109 this.offset.relative = this._getRelativeOffset();
1113 * - Position constraining -
1114 * Constrain the position to a mix of grid, containment.
1117 if(this.originalPosition) { //If we are not dragging yet, we won't check for options
1119 if(this.containment) {
1120 if(event.pageX - this.offset.click.left < this.containment[0]) {
1121 pageX = this.containment[0] + this.offset.click.left;
1123 if(event.pageY - this.offset.click.top < this.containment[1]) {
1124 pageY = this.containment[1] + this.offset.click.top;
1126 if(event.pageX - this.offset.click.left > this.containment[2]) {
1127 pageX = this.containment[2] + this.offset.click.left;
1129 if(event.pageY - this.offset.click.top > this.containment[3]) {
1130 pageY = this.containment[3] + this.offset.click.top;
1135 top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1];
1136 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;
1138 left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0];
1139 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;
1146 pageY - // The absolute mouse position
1147 this.offset.click.top - // Click offset (relative to the element)
1148 this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
1149 this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
1150 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
1153 pageX - // The absolute mouse position
1154 this.offset.click.left - // Click offset (relative to the element)
1155 this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
1156 this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
1157 ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
1163 _rearrange: function(event, i, a, hardRefresh) {
1165 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));
1167 //Various things done here to improve the performance:
1168 // 1. we create a setTimeout, that calls refreshPositions
1169 // 2. on the instance, we have a counter variable, that get's higher after every append
1170 // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same
1171 // 4. this lets only the last addition to the timeout stack through
1172 this.counter = this.counter ? ++this.counter : 1;
1173 var counter = this.counter;
1175 this._delay(function() {
1176 if(counter === this.counter) {
1177 this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove
1183 _clear: function(event, noPropagation) {
1185 this.reverting = false;
1186 // We delay all events that have to be triggered to after the point where the placeholder has been removed and
1187 // everything else normalized again
1189 delayedTriggers = [];
1191 // We first have to update the dom position of the actual currentItem
1192 // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088)
1193 if(!this._noFinalSort && this.currentItem.parent().length) {
1194 this.placeholder.before(this.currentItem);
1196 this._noFinalSort = null;
1198 if(this.helper[0] === this.currentItem[0]) {
1199 for(i in this._storedCSS) {
1200 if(this._storedCSS[i] === "auto" || this._storedCSS[i] === "static") {
1201 this._storedCSS[i] = "";
1204 this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper");
1206 this.currentItem.show();
1209 if(this.fromOutside && !noPropagation) {
1210 delayedTriggers.push(function(event) { this._trigger("receive", event, this._uiHash(this.fromOutside)); });
1212 if((this.fromOutside || this.domPosition.prev !== this.currentItem.prev().not(".ui-sortable-helper")[0] || this.domPosition.parent !== this.currentItem.parent()[0]) && !noPropagation) {
1213 delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed
1216 // Check if the items Container has Changed and trigger appropriate
1218 if (this !== this.currentContainer) {
1219 if(!noPropagation) {
1220 delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); });
1221 delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
1222 delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer));
1227 //Post events to containers
1228 function delayEvent( type, instance, container ) {
1229 return function( event ) {
1230 container._trigger( type, event, instance._uiHash( instance ) );
1233 for (i = this.containers.length - 1; i >= 0; i--){
1234 if (!noPropagation) {
1235 delayedTriggers.push( delayEvent( "deactivate", this, this.containers[ i ] ) );
1237 if(this.containers[i].containerCache.over) {
1238 delayedTriggers.push( delayEvent( "out", this, this.containers[ i ] ) );
1239 this.containers[i].containerCache.over = 0;
1243 //Do what was originally in plugins
1244 if ( this.storedCursor ) {
1245 this.document.find( "body" ).css( "cursor", this.storedCursor );
1246 this.storedStylesheet.remove();
1248 if(this._storedOpacity) {
1249 this.helper.css("opacity", this._storedOpacity);
1251 if(this._storedZIndex) {
1252 this.helper.css("zIndex", this._storedZIndex === "auto" ? "" : this._storedZIndex);
1255 this.dragging = false;
1257 if(!noPropagation) {
1258 this._trigger("beforeStop", event, this._uiHash());
1261 //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node!
1262 this.placeholder[0].parentNode.removeChild(this.placeholder[0]);
1264 if ( !this.cancelHelperRemoval ) {
1265 if ( this.helper[ 0 ] !== this.currentItem[ 0 ] ) {
1266 this.helper.remove();
1271 if(!noPropagation) {
1272 for (i=0; i < delayedTriggers.length; i++) {
1273 delayedTriggers[i].call(this, event);
1274 } //Trigger all delayed events
1275 this._trigger("stop", event, this._uiHash());
1278 this.fromOutside = false;
1279 return !this.cancelHelperRemoval;
1283 _trigger: function() {
1284 if ($.Widget.prototype._trigger.apply(this, arguments) === false) {
1289 _uiHash: function(_inst) {
1290 var inst = _inst || this;
1292 helper: inst.helper,
1293 placeholder: inst.placeholder || $([]),
1294 position: inst.position,
1295 originalPosition: inst.originalPosition,
1296 offset: inst.positionAbs,
1297 item: inst.currentItem,
1298 sender: _inst ? _inst.element : null