Sortable.js 28.7 KB
Newer Older
R
RubaXa 已提交
1 2 3 4 5 6 7
/**!
 * Sortable
 * @author	RubaXa   <trash@rubaxa.org>
 * @license MIT
 */


R
RubaXa 已提交
8
(function (factory) {
R
RubaXa 已提交
9 10
	"use strict";

R
RubaXa 已提交
11
	if (typeof define === "function" && define.amd) {
R
RubaXa 已提交
12
		define(factory);
R
RubaXa 已提交
13
	}
R
RubaXa 已提交
14
	else if (typeof module != "undefined" && typeof module.exports != "undefined") {
S
Scott Nelson 已提交
15 16
		module.exports = factory();
	}
R
RubaXa 已提交
17
	else if (typeof Package !== "undefined") {
18 19
		Sortable = factory();  // export for Meteor.js
	}
R
RubaXa 已提交
20
	else {
R
RubaXa 已提交
21
		/* jshint sub:true */
R
RubaXa 已提交
22 23
		window["Sortable"] = factory();
	}
R
RubaXa 已提交
24
})(function () {
R
RubaXa 已提交
25
	"use strict";
O
Onoshko Dan 已提交
26 27 28 29 30 31
	
	if (typeof window == "undefined" || typeof window.document == "undefined") {
		return function() {
			throw new Error( "Sortable.js requires a window with a document" );
		}
	}
R
RubaXa 已提交
32

R
RubaXa 已提交
33
	var dragEl,
34
		parentEl,
R
RubaXa 已提交
35 36 37 38
		ghostEl,
		cloneEl,
		rootEl,
		nextEl,
R
RubaXa 已提交
39

40 41 42
		scrollEl,
		scrollParentEl,

R
RubaXa 已提交
43 44
		lastEl,
		lastCSS,
S
sp-kilobug 已提交
45
		lastParentCSS,
R
RubaXa 已提交
46

R
RubaXa 已提交
47 48 49
		oldIndex,
		newIndex,

R
RubaXa 已提交
50
		activeGroup,
R
RubaXa 已提交
51
		autoScroll = {},
R
RubaXa 已提交
52

R
RubaXa 已提交
53 54
		tapEvt,
		touchEvt,
R
RubaXa 已提交
55

C
ChiefORZ 已提交
56 57
		moved,

R
RubaXa 已提交
58 59 60
		/** @const */
		RSPACE = /\s+/g,

R
RubaXa 已提交
61
		expando = 'Sortable' + (new Date).getTime(),
R
RubaXa 已提交
62

R
RubaXa 已提交
63 64 65
		win = window,
		document = win.document,
		parseInt = win.parseInt,
R
RubaXa 已提交
66

R
RubaXa 已提交
67
		supportDraggable = !!('draggable' in document.createElement('div')),
68 69 70 71 72
		supportCssPointerEvents = (function (el) {
			el = document.createElement('x');
			el.style.cssText = 'pointer-events:auto';
			return el.style.pointerEvents === 'auto';
		})(),
R
RubaXa 已提交
73

R
RubaXa 已提交
74
		_silent = false,
R
RubaXa 已提交
75

R
RubaXa 已提交
76
		abs = Math.abs,
R
RubaXa 已提交
77
		slice = [].slice,
R
RubaXa 已提交
78

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
		touchDragOverListeners = [],

		_autoScroll = _throttle(function (/**Event*/evt, /**Object*/options, /**HTMLElement*/rootEl) {
			// Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
			if (rootEl && options.scroll) {
				var el,
					rect,
					sens = options.scrollSensitivity,
					speed = options.scrollSpeed,

					x = evt.clientX,
					y = evt.clientY,

					winWidth = window.innerWidth,
					winHeight = window.innerHeight,

					vx,
					vy
				;

				// Delect scrollEl
				if (scrollParentEl !== rootEl) {
					scrollEl = options.scroll;
					scrollParentEl = rootEl;

					if (scrollEl === true) {
						scrollEl = rootEl;

						do {
							if ((scrollEl.offsetWidth < scrollEl.scrollWidth) ||
								(scrollEl.offsetHeight < scrollEl.scrollHeight)
							) {
								break;
							}
							/* jshint boss:true */
						} while (scrollEl = scrollEl.parentNode);
					}
				}

				if (scrollEl) {
					el = scrollEl;
					rect = scrollEl.getBoundingClientRect();
					vx = (abs(rect.right - x) <= sens) - (abs(rect.left - x) <= sens);
					vy = (abs(rect.bottom - y) <= sens) - (abs(rect.top - y) <= sens);
				}


				if (!(vx || vy)) {
					vx = (winWidth - x <= sens) - (x <= sens);
					vy = (winHeight - y <= sens) - (y <= sens);

					/* jshint expr:true */
					(vx || vy) && (el = win);
				}


				if (autoScroll.vx !== vx || autoScroll.vy !== vy || autoScroll.el !== el) {
					autoScroll.el = el;
					autoScroll.vx = vx;
					autoScroll.vy = vy;

					clearInterval(autoScroll.pid);

					if (el) {
						autoScroll.pid = setInterval(function () {
							if (el === win) {
145
								win.scrollTo(win.pageXOffset + vx * speed, win.pageYOffset + vy * speed);
146 147 148 149 150 151 152 153
							} else {
								vy && (el.scrollTop += vy * speed);
								vx && (el.scrollLeft += vx * speed);
							}
						}, 24);
					}
				}
			}
R
RubaXa 已提交
154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
		}, 30),

		_prepareGroup = function (options) {
			var group = options.group;

			if (!group || typeof group != 'object') {
				group = options.group = {name: group};
			}

			['pull', 'put'].forEach(function (key) {
				if (!(key in group)) {
					group[key] = true;
				}
			});

			options.groups = ' ' + group.name + (group.put.join ? ' ' + group.put.join(' ') : '') + ' ';
		}
R
RubaXa 已提交
171 172 173
	;


174

R
RubaXa 已提交
175 176 177
	/**
	 * @class  Sortable
	 * @param  {HTMLElement}  el
178
	 * @param  {Object}       [options]
R
RubaXa 已提交
179
	 */
R
RubaXa 已提交
180
	function Sortable(el, options) {
R
RubaXa 已提交
181 182 183 184
		if (!(el && el.nodeType && el.nodeType === 1)) {
			throw 'Sortable: `el` must be HTMLElement, and not ' + {}.toString.call(el);
		}

R
RubaXa 已提交
185
		this.el = el; // root element
186
		this.options = options = _extend({}, options);
R
RubaXa 已提交
187 188


189 190 191 192
		// Export instance
		el[expando] = this;


R
RubaXa 已提交
193
		// Default options
194 195
		var defaults = {
			group: Math.random(),
R
RubaXa 已提交
196
			sort: true,
R
RubaXa 已提交
197
			disabled: false,
198 199
			store: null,
			handle: null,
R
RubaXa 已提交
200 201 202
			scroll: true,
			scrollSensitivity: 30,
			scrollSpeed: 10,
R
RubaXa 已提交
203
			draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*',
204
			ghostClass: 'sortable-ghost',
R
RubaXa 已提交
205
			chosenClass: 'sortable-chosen',
206
			ignore: 'a, img',
207
			filter: null,
R
RubaXa 已提交
208 209 210
			animation: 0,
			setData: function (dataTransfer, dragEl) {
				dataTransfer.setData('Text', dragEl.textContent);
211 212
			},
			dropBubble: false,
R
RubaXa 已提交
213
			dragoverBubble: false,
214
			dataIdAttr: 'data-id',
215
			delay: 0,
C
ChiefORZ 已提交
216 217 218
			forceFallback: false,
			fallbackClass: 'sortable-fallback',
			fallbackOnBody: false
R
RubaXa 已提交
219
		};
220

R
RubaXa 已提交
221

222 223
		// Set default options
		for (var name in defaults) {
R
RubaXa 已提交
224
			!(name in options) && (options[name] = defaults[name]);
225
		}
R
RubaXa 已提交
226

R
RubaXa 已提交
227
		_prepareGroup(options);
R
RubaXa 已提交
228

R
* JSDoc  
RubaXa 已提交
229
		// Bind all private methods
R
RubaXa 已提交
230 231
		for (var fn in this) {
			if (fn.charAt(0) === '_') {
232
				this[fn] = this[fn].bind(this);
R
RubaXa 已提交
233 234 235
			}
		}

R
RubaXa 已提交
236 237
		// Setup drag mode
		this.nativeDraggable = options.forceFallback ? false : supportDraggable;
R
RubaXa 已提交
238 239 240 241 242

		// Bind events
		_on(el, 'mousedown', this._onTapStart);
		_on(el, 'touchstart', this._onTapStart);

R
RubaXa 已提交
243
		if (this.nativeDraggable) {
244 245 246
			_on(el, 'dragover', this);
			_on(el, 'dragenter', this);
		}
R
RubaXa 已提交
247 248

		touchDragOverListeners.push(this._onDragOver);
249 250 251

		// Restore sorting
		options.store && this.sort(options.store.get(this));
R
RubaXa 已提交
252 253 254
	}


255
	Sortable.prototype = /** @lends Sortable.prototype */ {
R
RubaXa 已提交
256 257
		constructor: Sortable,

258
		_onTapStart: function (/** Event|TouchEvent */evt) {
259 260
			var _this = this,
				el = this.el,
261 262 263 264 265 266
				options = this.options,
				type = evt.type,
				touch = evt.touches && evt.touches[0],
				target = (touch || evt).target,
				originalTarget = target,
				filter = options.filter;
R
RubaXa 已提交
267 268


269 270
			if (type === 'mousedown' && evt.button !== 0 || options.disabled) {
				return; // only left button or enabled
R
RubaXa 已提交
271
			}
R
RubaXa 已提交
272

273
			target = _closest(target, options.draggable, el);
274

275 276
			if (!target) {
				return;
277
			}
278 279

			// get the index of the dragged element within its parent
280
			oldIndex = _index(target, options.draggable);
281 282 283 284

			// Check filter
			if (typeof filter === 'function') {
				if (filter.call(this, evt, target, this)) {
285
					_dispatchEvent(_this, originalTarget, 'filter', target, el, oldIndex);
286 287 288
					evt.preventDefault();
					return; // cancel dnd
				}
289
			}
290 291 292
			else if (filter) {
				filter = filter.split(',').some(function (criteria) {
					criteria = _closest(originalTarget, criteria.trim(), el);
293

294
					if (criteria) {
295
						_dispatchEvent(_this, criteria, 'filter', target, el, oldIndex);
296 297 298 299 300 301 302
						return true;
					}
				});

				if (filter) {
					evt.preventDefault();
					return; // cancel dnd
303 304 305 306
				}
			}


307 308 309
			if (options.handle && !_closest(originalTarget, options.handle, el)) {
				return;
			}
310

311 312 313

			// Prepare `dragstart`
			this._prepareDragStart(evt, touch, target);
314 315
		},

316 317 318 319 320 321
		_prepareDragStart: function (/** Event */evt, /** Touch */touch, /** HTMLElement */target) {
			var _this = this,
				el = _this.el,
				options = _this.options,
				ownerDocument = el.ownerDocument,
				dragStartFn;
322 323 324 325

			if (target && !dragEl && (target.parentNode === el)) {
				tapEvt = evt;

326
				rootEl = el;
327
				dragEl = target;
R
RubaXa 已提交
328
				parentEl = dragEl.parentNode;
329
				nextEl = dragEl.nextSibling;
330 331 332 333 334 335
				activeGroup = options.group;

				dragStartFn = function () {
					// Delayed drag has been triggered
					// we can re-enable the events: touchmove/mousemove
					_this._disableDelayedDrag();
336

337 338
					// Make the element draggable
					dragEl.draggable = true;
339

R
RubaXa 已提交
340 341
					// Chosen item
					_toggleClass(dragEl, _this.options.chosenClass, true);
342 343 344 345 346

					// Bind the events: dragstart/dragend
					_this._triggerDragStart(touch);
				};

R
RubaXa 已提交
347 348 349 350 351
				// Disable "draggable"
				options.ignore.split(',').forEach(function (criteria) {
					_find(dragEl, criteria.trim(), _disableDraggable);
				});

352 353 354 355 356
				_on(ownerDocument, 'mouseup', _this._onDrop);
				_on(ownerDocument, 'touchend', _this._onDrop);
				_on(ownerDocument, 'touchcancel', _this._onDrop);

				if (options.delay) {
357 358
					// If the user moves the pointer or let go the click or touch
					// before the delay has been reached:
359
					// disable the delayed drag
360 361 362
					_on(ownerDocument, 'mouseup', _this._disableDelayedDrag);
					_on(ownerDocument, 'touchend', _this._disableDelayedDrag);
					_on(ownerDocument, 'touchcancel', _this._disableDelayedDrag);
363 364 365 366 367 368
					_on(ownerDocument, 'mousemove', _this._disableDelayedDrag);
					_on(ownerDocument, 'touchmove', _this._disableDelayedDrag);

					_this._dragStartTimer = setTimeout(dragStartFn, options.delay);
				} else {
					dragStartFn();
369 370 371
				}
			}
		},
R
RubaXa 已提交
372

373 374
		_disableDelayedDrag: function () {
			var ownerDocument = this.el.ownerDocument;
375

376
			clearTimeout(this._dragStartTimer);
377 378 379
			_off(ownerDocument, 'mouseup', this._disableDelayedDrag);
			_off(ownerDocument, 'touchend', this._disableDelayedDrag);
			_off(ownerDocument, 'touchcancel', this._disableDelayedDrag);
380 381 382
			_off(ownerDocument, 'mousemove', this._disableDelayedDrag);
			_off(ownerDocument, 'touchmove', this._disableDelayedDrag);
		},
R
RubaXa 已提交
383

384 385 386 387 388 389 390 391
		_triggerDragStart: function (/** Touch */touch) {
			if (touch) {
				// Touch device support
				tapEvt = {
					target: dragEl,
					clientX: touch.clientX,
					clientY: touch.clientY
				};
392

393
				this._onDragStart(tapEvt, 'touch');
R
RubaXa 已提交
394
			}
R
RubaXa 已提交
395
			else if (!this.nativeDraggable) {
396 397 398 399 400
				this._onDragStart(tapEvt, true);
			}
			else {
				_on(dragEl, 'dragend', this);
				_on(rootEl, 'dragstart', this._onDragStart);
401 402
			}

403 404 405 406 407
			try {
				if (document.selection) {
					document.selection.empty();
				} else {
					window.getSelection().removeAllRanges();
408
				}
409
			} catch (err) {
410
			}
411
		},
412

413 414 415 416
		_dragStarted: function () {
			if (rootEl && dragEl) {
				// Apply effect
				_toggleClass(dragEl, this.options.ghostClass, true);
R
RubaXa 已提交
417

418
				Sortable.active = this;
419

420
				// Drag start event
421
				_dispatchEvent(this, rootEl, 'start', dragEl, rootEl, oldIndex);
422
			}
R
RubaXa 已提交
423 424
		},

R
RubaXa 已提交
425 426
		_emulateDragOver: function () {
			if (touchEvt) {
R
RubaXa 已提交
427
				if (this._lastX === touchEvt.clientX && this._lastY === touchEvt.clientY) {
428 429
					return;
				}
R
RubaXa 已提交
430 431 432

				this._lastX = touchEvt.clientX;
				this._lastY = touchEvt.clientY;
433

434 435 436
				if (!supportCssPointerEvents) {
					_css(ghostEl, 'display', 'none');
				}
R
RubaXa 已提交
437

R
RubaXa 已提交
438
				var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY),
R
RubaXa 已提交
439
					parent = target,
440
					groupName = ' ' + this.options.group.name + '',
R
RubaXa 已提交
441
					i = touchDragOverListeners.length;
R
RubaXa 已提交
442

R
RubaXa 已提交
443 444
				if (parent) {
					do {
445
						if (parent[expando] && parent[expando].options.groups.indexOf(groupName) > -1) {
R
RubaXa 已提交
446 447 448 449 450 451 452 453 454 455 456 457 458
							while (i--) {
								touchDragOverListeners[i]({
									clientX: touchEvt.clientX,
									clientY: touchEvt.clientY,
									target: target,
									rootEl: parent
								});
							}

							break;
						}

						target = parent; // store last element
L
Larry Davis 已提交
459
					}
R
RubaXa 已提交
460 461
					/* jshint boss:true */
					while (parent = parent.parentNode);
R
RubaXa 已提交
462 463
				}

464 465 466
				if (!supportCssPointerEvents) {
					_css(ghostEl, 'display', '');
				}
R
RubaXa 已提交
467 468 469 470
			}
		},


R
RubaXa 已提交
471 472
		_onTouchMove: function (/**TouchEvent*/evt) {
			if (tapEvt) {
473
				// only set the status to dragging, when we are actually dragging
R
RubaXa 已提交
474
				if (!Sortable.active) {
475 476
					this._dragStarted();
				}
R
RubaXa 已提交
477

478 479
				// as well as creating the ghost element on the document body
				this._appendGhost();
R
RubaXa 已提交
480

R
RubaXa 已提交
481
				var touch = evt.touches ? evt.touches[0] : evt,
R
RubaXa 已提交
482 483
					dx = touch.clientX - tapEvt.clientX,
					dy = touch.clientY - tapEvt.clientY,
R
RubaXa 已提交
484
					translate3d = evt.touches ? 'translate3d(' + dx + 'px,' + dy + 'px,0)' : 'translate(' + dx + 'px,' + dy + 'px)';
R
RubaXa 已提交
485

A
Alex Wild 已提交
486
				moved = true;
R
RubaXa 已提交
487
				touchEvt = touch;
R
RubaXa 已提交
488 489 490 491 492 493

				_css(ghostEl, 'webkitTransform', translate3d);
				_css(ghostEl, 'mozTransform', translate3d);
				_css(ghostEl, 'msTransform', translate3d);
				_css(ghostEl, 'transform', translate3d);

M
Marius Petcu 已提交
494
				evt.preventDefault();
R
RubaXa 已提交
495 496 497
			}
		},

R
RubaXa 已提交
498 499
		_appendGhost: function () {
			if (!ghostEl) {
R
RubaXa 已提交
500 501
				var rect = dragEl.getBoundingClientRect(),
					css = _css(dragEl),
R
RubaXa 已提交
502
					options = this.options,
R
RubaXa 已提交
503
					ghostRect;
R
RubaXa 已提交
504

505
				ghostEl = dragEl.cloneNode(true);
R
RubaXa 已提交
506

R
RubaXa 已提交
507 508
				_toggleClass(ghostEl, options.ghostClass, false);
				_toggleClass(ghostEl, options.fallbackClass, true);
C
ChiefORZ 已提交
509

R
RubaXa 已提交
510 511
				_css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10));
				_css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10));
R
RubaXa 已提交
512 513
				_css(ghostEl, 'width', rect.width);
				_css(ghostEl, 'height', rect.height);
R
RubaXa 已提交
514 515 516
				_css(ghostEl, 'opacity', '0.8');
				_css(ghostEl, 'position', 'fixed');
				_css(ghostEl, 'zIndex', '100000');
517
				_css(ghostEl, 'pointerEvents', 'none');
R
RubaXa 已提交
518

R
RubaXa 已提交
519
				options.fallbackOnBody && document.body.appendChild(ghostEl) || rootEl.appendChild(ghostEl);
R
RubaXa 已提交
520 521 522

				// Fixing dimensions.
				ghostRect = ghostEl.getBoundingClientRect();
R
RubaXa 已提交
523 524
				_css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
				_css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
			}
		},

		_onDragStart: function (/**Event*/evt, /**boolean*/useFallback) {
			var dataTransfer = evt.dataTransfer,
				options = this.options;

			this._offUpEvents();

			if (activeGroup.pull == 'clone') {
				cloneEl = dragEl.cloneNode(true);
				_css(cloneEl, 'display', 'none');
				rootEl.insertBefore(cloneEl, dragEl);
			}

			if (useFallback) {
R
RubaXa 已提交
541

R
RubaXa 已提交
542 543 544 545 546 547 548 549 550 551
				if (useFallback === 'touch') {
					// Bind touch events
					_on(document, 'touchmove', this._onTouchMove);
					_on(document, 'touchend', this._onDrop);
					_on(document, 'touchcancel', this._onDrop);
				} else {
					// Old brwoser
					_on(document, 'mousemove', this._onTouchMove);
					_on(document, 'mouseup', this._onDrop);
				}
R
RubaXa 已提交
552

553
				this._loopId = setInterval(this._emulateDragOver, 50);
R
RubaXa 已提交
554 555
			}
			else {
R
RubaXa 已提交
556 557 558 559
				if (dataTransfer) {
					dataTransfer.effectAllowed = 'move';
					options.setData && options.setData.call(this, dataTransfer, dragEl);
				}
R
RubaXa 已提交
560

R
RubaXa 已提交
561
				_on(document, 'drop', this);
562
				setTimeout(this._dragStarted, 0);
R
RubaXa 已提交
563 564 565
			}
		},

R
RubaXa 已提交
566
		_onDragOver: function (/**Event*/evt) {
R
RubaXa 已提交
567 568 569 570 571 572
			var el = this.el,
				target,
				dragRect,
				revert,
				options = this.options,
				group = options.group,
R
RubaXa 已提交
573
				groupPut = group.put,
574 575
				isOwner = (activeGroup === group),
				canSort = options.sort;
R
RubaXa 已提交
576

R
RubaXa 已提交
577 578
			if (evt.preventDefault !== void 0) {
				evt.preventDefault();
579
				!options.dragoverBubble && evt.stopPropagation();
R
RubaXa 已提交
580
			}
R
RubaXa 已提交
581

A
Alex Wild 已提交
582 583
			moved = true;

R
RubaXa 已提交
584
			if (activeGroup && !options.disabled &&
585
				(isOwner
R
RubaXa 已提交
586
					? canSort || (revert = !rootEl.contains(dragEl)) // Reverting item into the original list
R
RubaXa 已提交
587 588 589 590
					: activeGroup.pull && groupPut && (
						(activeGroup.name === group.name) || // by Name
						(groupPut.indexOf && ~groupPut.indexOf(activeGroup.name)) // by Array
					)
591
				) &&
R
RubaXa 已提交
592
				(evt.rootEl === void 0 || evt.rootEl === this.el) // touch fallback
R
RubaXa 已提交
593
			) {
R
RubaXa 已提交
594 595 596 597 598 599 600
				// Smart auto-scrolling
				_autoScroll(evt, options, this.el);

				if (_silent) {
					return;
				}

R
RubaXa 已提交
601
				target = _closest(evt.target, options.draggable, el);
R
RubaXa 已提交
602 603
				dragRect = dragEl.getBoundingClientRect();

604
				if (revert) {
R
RubaXa 已提交
605 606
					_cloneHide(true);

607 608 609 610 611 612 613
					if (cloneEl || nextEl) {
						rootEl.insertBefore(dragEl, cloneEl || nextEl);
					}
					else if (!canSort) {
						rootEl.appendChild(dragEl);
					}

R
RubaXa 已提交
614 615
					return;
				}
R
RubaXa 已提交
616

R
RubaXa 已提交
617

R
RubaXa 已提交
618
				if ((el.children.length === 0) || (el.children[0] === ghostEl) ||
619
					(el === evt.target) && (target = _ghostIsLast(el, evt))
R
RubaXa 已提交
620
				) {
R
RubaXa 已提交
621

R
RubaXa 已提交
622 623 624 625
					if (target) {
						if (target.animated) {
							return;
						}
R
RubaXa 已提交
626

R
RubaXa 已提交
627 628
						targetRect = target.getBoundingClientRect();
					}
R
RubaXa 已提交
629

R
RubaXa 已提交
630 631
					_cloneHide(isOwner);

R
RubaXa 已提交
632
					if (_onMove(rootEl, el, dragEl, dragRect, target, targetRect) !== false) {
633 634
						if (!dragEl.contains(el)) {
							el.appendChild(dragEl);
R
RubaXa 已提交
635
							parentEl = el; // actualization
636
						}
R
RubaXa 已提交
637

R
RubaXa 已提交
638 639 640
						this._animate(dragRect, dragEl);
						target && this._animate(targetRect, target);
					}
R
RubaXa 已提交
641
				}
R
RubaXa 已提交
642 643
				else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) {
					if (lastEl !== target) {
R
RubaXa 已提交
644
						lastEl = target;
R
RubaXa 已提交
645
						lastCSS = _css(target);
S
sp-kilobug 已提交
646
						lastParentCSS = _css(target.parentNode);
R
RubaXa 已提交
647 648 649
					}


R
RubaXa 已提交
650 651 652
					var targetRect = target.getBoundingClientRect(),
						width = targetRect.right - targetRect.left,
						height = targetRect.bottom - targetRect.top,
S
sp-kilobug 已提交
653 654
						floating = /left|right|inline/.test(lastCSS.cssFloat + lastCSS.display)
							|| (lastParentCSS.display == 'flex' && lastParentCSS['flex-direction'].indexOf('row') === 0),
R
RubaXa 已提交
655 656 657 658
						isWide = (target.offsetWidth > dragEl.offsetWidth),
						isLong = (target.offsetHeight > dragEl.offsetHeight),
						halfway = (floating ? (evt.clientX - targetRect.left) / width : (evt.clientY - targetRect.top) / height) > 0.5,
						nextSibling = target.nextElementSibling,
R
RubaXa 已提交
659
						moveVector = _onMove(rootEl, el, dragEl, dragRect, target, targetRect),
R
RubaXa 已提交
660
						after
R
RubaXa 已提交
661
					;
R
RubaXa 已提交
662

R
RubaXa 已提交
663
					if (moveVector !== false) {
R
RubaXa 已提交
664 665
						_silent = true;
						setTimeout(_unsilent, 30);
R
RubaXa 已提交
666

R
RubaXa 已提交
667
						_cloneHide(isOwner);
R
RubaXa 已提交
668

R
RubaXa 已提交
669 670 671 672
						if (moveVector === 1 || moveVector === -1) {
							after = (moveVector === 1);
						}
						else if (floating) {
S
sp-kilobug 已提交
673 674
							var elTop = dragEl.offsetTop,
								tgTop = target.offsetTop;
R
RubaXa 已提交
675 676

							if (elTop === tgTop) {
S
sp-kilobug 已提交
677 678 679 680
								after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
							} else {
								after = tgTop > elTop;
							}
R
RubaXa 已提交
681 682 683
						} else {
							after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
						}
R
RubaXa 已提交
684

685 686 687 688 689 690
						if (!dragEl.contains(el)) {
							if (after && !nextSibling) {
								el.appendChild(dragEl);
							} else {
								target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
							}
R
RubaXa 已提交
691
						}
R
RubaXa 已提交
692

R
RubaXa 已提交
693 694
						parentEl = dragEl.parentNode; // actualization

R
RubaXa 已提交
695 696 697
						this._animate(dragRect, dragEl);
						this._animate(targetRect, target);
					}
R
RubaXa 已提交
698 699 700 701
				}
			}
		},

702 703 704 705 706 707
		_animate: function (prevRect, target) {
			var ms = this.options.animation;

			if (ms) {
				var currentRect = target.getBoundingClientRect();

R
RubaXa 已提交
708
				_css(target, 'transition', 'none');
709 710 711 712 713 714 715
				_css(target, 'transform', 'translate3d('
					+ (prevRect.left - currentRect.left) + 'px,'
					+ (prevRect.top - currentRect.top) + 'px,0)'
				);

				target.offsetWidth; // repaint

R
RubaXa 已提交
716
				_css(target, 'transition', 'all ' + ms + 'ms');
717 718
				_css(target, 'transform', 'translate3d(0,0,0)');

R
* anim  
RubaXa 已提交
719 720
				clearTimeout(target.animated);
				target.animated = setTimeout(function () {
721
					_css(target, 'transition', '');
722
					_css(target, 'transform', '');
723 724 725 726 727
					target.animated = false;
				}, ms);
			}
		},

728
		_offUpEvents: function () {
729 730
			var ownerDocument = this.el.ownerDocument;

731
			_off(document, 'touchmove', this._onTouchMove);
732 733 734
			_off(ownerDocument, 'mouseup', this._onDrop);
			_off(ownerDocument, 'touchend', this._onDrop);
			_off(ownerDocument, 'touchcancel', this._onDrop);
735
		},
R
RubaXa 已提交
736

R
RubaXa 已提交
737
		_onDrop: function (/**Event*/evt) {
738 739
			var el = this.el,
				options = this.options;
R
RubaXa 已提交
740

R
RubaXa 已提交
741
			clearInterval(this._loopId);
R
RubaXa 已提交
742
			clearInterval(autoScroll.pid);
R
RubaXa 已提交
743
			clearTimeout(this._dragStartTimer);
744

R
RubaXa 已提交
745
			// Unbind events
R
RubaXa 已提交
746
			_off(document, 'mousemove', this._onTouchMove);
747

R
RubaXa 已提交
748
			if (this.nativeDraggable) {
749 750 751
				_off(document, 'drop', this);
				_off(el, 'dragstart', this._onDragStart);
			}
R
RubaXa 已提交
752

753
			this._offUpEvents();
R
RubaXa 已提交
754

R
RubaXa 已提交
755
			if (evt) {
R
RubaXa 已提交
756
				if (moved) {
C
ChiefORZ 已提交
757 758 759
					evt.preventDefault();
					!options.dropBubble && evt.stopPropagation();
				}
R
RubaXa 已提交
760

R
RubaXa 已提交
761
				ghostEl && ghostEl.parentNode.removeChild(ghostEl);
R
RubaXa 已提交
762

R
RubaXa 已提交
763
				if (dragEl) {
R
RubaXa 已提交
764
					if (this.nativeDraggable) {
765 766
						_off(dragEl, 'dragend', this);
					}
R
RubaXa 已提交
767

768
					_disableDraggable(dragEl);
R
RubaXa 已提交
769 770

					// Remove class's
R
RubaXa 已提交
771
					_toggleClass(dragEl, this.options.ghostClass, false);
R
RubaXa 已提交
772
					_toggleClass(dragEl, this.options.chosenClass, false);
R
RubaXa 已提交
773

774
					if (rootEl !== parentEl) {
775
						newIndex = _index(dragEl, options.draggable);
R
RubaXa 已提交
776

777
						if (newIndex >= 0) {
778 779 780
							// drag from one list and drop into another
							_dispatchEvent(null, parentEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
							_dispatchEvent(this, rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
R
RubaXa 已提交
781

782 783
							// Add event
							_dispatchEvent(null, parentEl, 'add', dragEl, rootEl, oldIndex, newIndex);
784

785 786 787
							// Remove event
							_dispatchEvent(this, rootEl, 'remove', dragEl, rootEl, oldIndex, newIndex);
						}
R
RubaXa 已提交
788
					}
R
RubaXa 已提交
789 790
					else {
						// Remove clone
R
RubaXa 已提交
791
						cloneEl && cloneEl.parentNode.removeChild(cloneEl);
R
RubaXa 已提交
792

R
RubaXa 已提交
793 794
						if (dragEl.nextSibling !== nextEl) {
							// Get the index of the dragged element within its parent
795
							newIndex = _index(dragEl, options.draggable);
796 797

							if (newIndex >= 0) {
798 799 800 801
								// drag & drop within the same list
								_dispatchEvent(this, rootEl, 'update', dragEl, rootEl, oldIndex, newIndex);
								_dispatchEvent(this, rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
							}
R
RubaXa 已提交
802
						}
R
RubaXa 已提交
803
					}
804

R
RubaXa 已提交
805
					if (Sortable.active) {
R
RubaXa 已提交
806
						if (newIndex === null || newIndex === -1) {
R
RubaXa 已提交
807 808 809
							newIndex = oldIndex;
						}

R
RubaXa 已提交
810 811 812 813 814
						_dispatchEvent(this, rootEl, 'end', dragEl, rootEl, oldIndex, newIndex);

						// Save sorting
						this.save();
					}
R
RubaXa 已提交
815
				}
R
RubaXa 已提交
816

817 818 819
			}
			this._nulling();
		},
R
RubaXa 已提交
820

821 822 823 824 825 826 827 828
		_nulling: function() {
			// Nulling
			rootEl =
			dragEl =
			parentEl =
			ghostEl =
			nextEl =
			cloneEl =
829

830 831
			scrollEl =
			scrollParentEl =
R
RubaXa 已提交
832

833 834
			tapEvt =
			touchEvt =
C
ChiefORZ 已提交
835

836 837
			moved =
			newIndex =
R
RubaXa 已提交
838

839 840
			lastEl =
			lastCSS =
R
RubaXa 已提交
841

842 843 844
			activeGroup =
			Sortable.active = null;
		},
R
RubaXa 已提交
845

R
RubaXa 已提交
846 847 848
		handleEvent: function (/**Event*/evt) {
			var type = evt.type;

R
RubaXa 已提交
849
			if (type === 'dragover' || type === 'dragenter') {
R
RubaXa 已提交
850 851 852 853
				if (dragEl) {
					this._onDragOver(evt);
					_globalDragOver(evt);
				}
R
RubaXa 已提交
854
			}
R
RubaXa 已提交
855
			else if (type === 'drop' || type === 'dragend') {
R
RubaXa 已提交
856 857
				this._onDrop(evt);
			}
R
RubaXa 已提交
858 859 860
		},


861 862 863 864 865 866 867 868 869
		/**
		 * Serializes the item into an array of string.
		 * @returns {String[]}
		 */
		toArray: function () {
			var order = [],
				el,
				children = this.el.children,
				i = 0,
R
RubaXa 已提交
870 871
				n = children.length,
				options = this.options;
872 873 874

			for (; i < n; i++) {
				el = children[i];
R
RubaXa 已提交
875
				if (_closest(el, options.draggable, this.el)) {
R
RubaXa 已提交
876
					order.push(el.getAttribute(options.dataIdAttr) || _generateId(el));
R
RubaXa 已提交
877
				}
878 879 880 881 882 883 884 885 886 887 888
			}

			return order;
		},


		/**
		 * Sorts the elements according to the array.
		 * @param  {String[]}  order  order of the items
		 */
		sort: function (order) {
R
RubaXa 已提交
889
			var items = {}, rootEl = this.el;
890 891

			this.toArray().forEach(function (id, i) {
R
RubaXa 已提交
892 893
				var el = rootEl.children[i];

R
RubaXa 已提交
894
				if (_closest(el, this.options.draggable, rootEl)) {
R
RubaXa 已提交
895 896 897
					items[id] = el;
				}
			}, this);
898 899 900

			order.forEach(function (id) {
				if (items[id]) {
R
RubaXa 已提交
901 902
					rootEl.removeChild(items[id]);
					rootEl.appendChild(items[id]);
903 904 905 906 907
				}
			});
		},


R
RubaXa 已提交
908 909 910 911 912 913 914 915 916
		/**
		 * Save the current sorting
		 */
		save: function () {
			var store = this.options.store;
			store && store.set(this);
		},


917 918 919 920 921 922 923 924 925 926 927
		/**
		 * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
		 * @param   {HTMLElement}  el
		 * @param   {String}       [selector]  default: `options.draggable`
		 * @returns {HTMLElement|null}
		 */
		closest: function (el, selector) {
			return _closest(el, selector || this.options.draggable, this.el);
		},


928 929 930 931 932 933 934 935 936 937 938 939 940
		/**
		 * Set/get option
		 * @param   {string} name
		 * @param   {*}      [value]
		 * @returns {*}
		 */
		option: function (name, value) {
			var options = this.options;

			if (value === void 0) {
				return options[name];
			} else {
				options[name] = value;
R
RubaXa 已提交
941 942 943 944

				if (name === 'group') {
					_prepareGroup(options);
				}
945 946 947 948
			}
		},


949 950 951 952
		/**
		 * Destroy
		 */
		destroy: function () {
953
			var el = this.el;
R
RubaXa 已提交
954

955
			el[expando] = null;
956

R
RubaXa 已提交
957 958 959
			_off(el, 'mousedown', this._onTapStart);
			_off(el, 'touchstart', this._onTapStart);

R
RubaXa 已提交
960
			if (this.nativeDraggable) {
961 962 963
				_off(el, 'dragover', this);
				_off(el, 'dragenter', this);
			}
R
RubaXa 已提交
964

965
			// Remove draggable attributes
R
RubaXa 已提交
966
			Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
967 968 969
				el.removeAttribute('draggable');
			});

R
RubaXa 已提交
970 971 972 973
			touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);

			this._onDrop();

974
			this.el = el = null;
R
RubaXa 已提交
975 976 977
		}
	};

978

R
RubaXa 已提交
979 980 981 982 983 984 985 986 987
	function _cloneHide(state) {
		if (cloneEl && (cloneEl.state !== state)) {
			_css(cloneEl, 'display', state ? 'none' : '');
			!state && cloneEl.state && rootEl.insertBefore(cloneEl, dragEl);
			cloneEl.state = state;
		}
	}


R
RubaXa 已提交
988
	function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) {
R
RubaXa 已提交
989
		if (el) {
R
RubaXa 已提交
990 991 992
			ctx = ctx || document;

			do {
R
RubaXa 已提交
993
				if (
994 995
					(selector === '>*' && el.parentNode === ctx)
					|| _matches(el, selector)
R
RubaXa 已提交
996 997
				) {
					return el;
R
RubaXa 已提交
998 999
				}
			}
R
RubaXa 已提交
1000
			while (el !== ctx && (el = el.parentNode));
R
RubaXa 已提交
1001 1002
		}

R
RubaXa 已提交
1003
		return null;
R
RubaXa 已提交
1004 1005 1006
	}


1007
	function _globalDragOver(/**Event*/evt) {
1008 1009 1010
		if (evt.dataTransfer) {
			evt.dataTransfer.dropEffect = 'move';
		}
R
RubaXa 已提交
1011 1012 1013 1014
		evt.preventDefault();
	}


R
RubaXa 已提交
1015
	function _on(el, event, fn) {
R
RubaXa 已提交
1016 1017 1018 1019
		el.addEventListener(event, fn, false);
	}


R
RubaXa 已提交
1020
	function _off(el, event, fn) {
R
RubaXa 已提交
1021 1022 1023 1024
		el.removeEventListener(event, fn, false);
	}


R
RubaXa 已提交
1025 1026 1027
	function _toggleClass(el, name, state) {
		if (el) {
			if (el.classList) {
R
RubaXa 已提交
1028 1029 1030
				el.classList[state ? 'add' : 'remove'](name);
			}
			else {
B
Bogdan Mustiata 已提交
1031 1032
				var className = (' ' + el.className + ' ').replace(RSPACE, ' ').replace(' ' + name + ' ', ' ');
				el.className = (className + (state ? ' ' + name : '')).replace(RSPACE, ' ');
R
RubaXa 已提交
1033 1034 1035 1036 1037
			}
		}
	}


R
RubaXa 已提交
1038
	function _css(el, prop, val) {
R
RubaXa 已提交
1039 1040
		var style = el && el.style;

R
RubaXa 已提交
1041 1042 1043
		if (style) {
			if (val === void 0) {
				if (document.defaultView && document.defaultView.getComputedStyle) {
R
RubaXa 已提交
1044 1045
					val = document.defaultView.getComputedStyle(el, '');
				}
R
RubaXa 已提交
1046 1047
				else if (el.currentStyle) {
					val = el.currentStyle;
R
RubaXa 已提交
1048
				}
R
RubaXa 已提交
1049 1050 1051 1052 1053 1054 1055 1056 1057

				return prop === void 0 ? val : val[prop];
			}
			else {
				if (!(prop in style)) {
					prop = '-webkit-' + prop;
				}

				style[prop] = val + (typeof val === 'string' ? '' : 'px');
R
RubaXa 已提交
1058 1059 1060 1061 1062
			}
		}
	}


R
RubaXa 已提交
1063 1064
	function _find(ctx, tagName, iterator) {
		if (ctx) {
R
RubaXa 已提交
1065
			var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
R
RubaXa 已提交
1066

R
RubaXa 已提交
1067 1068
			if (iterator) {
				for (; i < n; i++) {
R
RubaXa 已提交
1069 1070 1071
					iterator(list[i], i);
				}
			}
R
RubaXa 已提交
1072

R
RubaXa 已提交
1073
			return list;
R
RubaXa 已提交
1074
		}
R
RubaXa 已提交
1075 1076

		return [];
R
RubaXa 已提交
1077 1078 1079
	}


R
RubaXa 已提交
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095

	function _dispatchEvent(sortable, rootEl, name, targetEl, fromEl, startIndex, newIndex) {
		var evt = document.createEvent('Event'),
			options = (sortable || rootEl[expando]).options,
			onName = 'on' + name.charAt(0).toUpperCase() + name.substr(1);

		evt.initEvent(name, true, true);

		evt.to = rootEl;
		evt.from = fromEl || rootEl;
		evt.item = targetEl || rootEl;
		evt.clone = cloneEl;

		evt.oldIndex = startIndex;
		evt.newIndex = newIndex;

R
RubaXa 已提交
1096 1097
		rootEl.dispatchEvent(evt);

R
RubaXa 已提交
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
		if (options[onName]) {
			options[onName].call(sortable, evt);
		}
	}


	function _onMove(fromEl, toEl, dragEl, dragRect, targetEl, targetRect) {
		var evt,
			sortable = fromEl[expando],
			onMoveFn = sortable.options.onMove,
			retVal;

C
ChiefORZ 已提交
1110 1111
		evt = document.createEvent('Event');
		evt.initEvent('move', true, true);
R
RubaXa 已提交
1112

C
ChiefORZ 已提交
1113 1114 1115 1116 1117 1118
		evt.to = toEl;
		evt.from = fromEl;
		evt.dragged = dragEl;
		evt.draggedRect = dragRect;
		evt.related = targetEl || toEl;
		evt.relatedRect = targetRect || toEl.getBoundingClientRect();
R
RubaXa 已提交
1119

C
ChiefORZ 已提交
1120
		fromEl.dispatchEvent(evt);
R
RubaXa 已提交
1121

C
ChiefORZ 已提交
1122
		if (onMoveFn) {
R
RubaXa 已提交
1123 1124 1125
			retVal = onMoveFn.call(sortable, evt);
		}

R
RubaXa 已提交
1126
		return retVal;
R
RubaXa 已提交
1127 1128 1129
	}


R
RubaXa 已提交
1130
	function _disableDraggable(el) {
R
RubaXa 已提交
1131
		el.draggable = false;
R
RubaXa 已提交
1132 1133 1134
	}


R
RubaXa 已提交
1135
	function _unsilent() {
R
RubaXa 已提交
1136 1137 1138 1139
		_silent = false;
	}


R
RubaXa 已提交
1140
	/** @returns {HTMLElement|false} */
1141
	function _ghostIsLast(el, evt) {
R
RubaXa 已提交
1142
		var lastEl = el.lastElementChild,
1143
				rect = lastEl.getBoundingClientRect();
R
RubaXa 已提交
1144

1145
		return ((evt.clientY - (rect.top + rect.height) > 5) || (evt.clientX - (rect.right + rect.width) > 5)) && lastEl; // min delta
R
RubaXa 已提交
1146 1147 1148
	}


1149 1150 1151 1152 1153 1154 1155
	/**
	 * Generate id
	 * @param   {HTMLElement} el
	 * @returns {String}
	 * @private
	 */
	function _generateId(el) {
R
RubaXa 已提交
1156
		var str = el.tagName + el.className + el.src + el.href + el.textContent,
1157
			i = str.length,
R
RubaXa 已提交
1158
			sum = 0;
1159

1160 1161 1162
		while (i--) {
			sum += str.charCodeAt(i);
		}
1163

1164 1165 1166
		return sum.toString(36);
	}

1167
	/**
1168 1169
	 * Returns the index of an element within its parent for a selected set of
	 * elements
1170
	 * @param  {HTMLElement} el
1171
	 * @param  {selector} selector
1172
	 * @return {number}
1173
	 */
1174
	function _index(el, selector) {
1175 1176
		var index = 0;

1177 1178 1179
		if (!el || !el.parentNode) {
			return -1;
		}
1180

1181
		while (el && (el = el.previousElementSibling)) {
1182 1183
			if (el.nodeName.toUpperCase() !== 'TEMPLATE'
					&& _matches(el, selector)) {
1184 1185
				index++;
			}
1186
		}
1187

1188 1189
		return index;
	}
R
RubaXa 已提交
1190

1191
	function _matches(/**HTMLElement*/el, /**String*/selector) {
1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
		if (el) {
			selector = selector.split('.');

			var tag = selector.shift().toUpperCase(),
				re = new RegExp('\\s(' + selector.join('|') + ')(?=\\s)', 'g');

			return (
				(tag === '' || el.nodeName.toUpperCase() == tag) &&
				(!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
			);
1202
		}
1203 1204

		return false;
1205 1206
	}

R
RubaXa 已提交
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
	function _throttle(callback, ms) {
		var args, _this;

		return function () {
			if (args === void 0) {
				args = arguments;
				_this = this;

				setTimeout(function () {
					if (args.length === 1) {
						callback.call(_this, args[0]);
					} else {
						callback.apply(_this, args);
					}

					args = void 0;
				}, ms);
			}
		};
	}

1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
	function _extend(dst, src) {
		if (dst && src) {
			for (var key in src) {
				if (src.hasOwnProperty(key)) {
					dst[key] = src[key];
				}
			}
		}

		return dst;
	}

R
RubaXa 已提交
1240

R
RubaXa 已提交
1241 1242 1243 1244 1245 1246
	// Export utils
	Sortable.utils = {
		on: _on,
		off: _off,
		css: _css,
		find: _find,
R
RubaXa 已提交
1247 1248 1249
		is: function (el, selector) {
			return !!_closest(el, selector, el);
		},
1250
		extend: _extend,
R
RubaXa 已提交
1251
		throttle: _throttle,
R
RubaXa 已提交
1252
		closest: _closest,
1253
		toggleClass: _toggleClass,
1254
		index: _index
R
RubaXa 已提交
1255 1256 1257
	};


1258 1259 1260 1261 1262 1263
	/**
	 * Create sortable instance
	 * @param {HTMLElement}  el
	 * @param {Object}      [options]
	 */
	Sortable.create = function (el, options) {
R
RubaXa 已提交
1264
		return new Sortable(el, options);
1265
	};
R
RubaXa 已提交
1266

R
RubaXa 已提交
1267 1268

	// Export
R
RubaXa 已提交
1269
	Sortable.version = '1.4.2';
1270
	return Sortable;
R
RubaXa 已提交
1271
});