Sortable.js 22.1 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 26
	"use strict";

R
RubaXa 已提交
27
	var dragEl,
28
		startIndex,
R
RubaXa 已提交
29 30 31
		ghostEl,
		cloneEl,
		rootEl,
R
RubaXa 已提交
32
		scrollEl,
R
RubaXa 已提交
33
		nextEl,
R
RubaXa 已提交
34

R
RubaXa 已提交
35 36
		lastEl,
		lastCSS,
R
RubaXa 已提交
37

R
RubaXa 已提交
38
		activeGroup,
R
RubaXa 已提交
39
		autoScroll = {},
R
RubaXa 已提交
40

R
RubaXa 已提交
41 42
		tapEvt,
		touchEvt,
R
RubaXa 已提交
43

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

R
RubaXa 已提交
46 47 48 49
		win = window,
		document = win.document,
		parseInt = win.parseInt,
		supportIEdnd = !!document.createElement('div').dragDrop,
R
RubaXa 已提交
50

R
RubaXa 已提交
51
		_silent = false,
R
RubaXa 已提交
52

53
		_dispatchEvent = function (rootEl, name, targetEl, fromEl, startIndex, newIndex) {
R
RubaXa 已提交
54
			var evt = document.createEvent('Event');
R
RubaXa 已提交
55

56
			evt.initEvent(name, true, true);
R
RubaXa 已提交
57

58 59
			evt.item = targetEl || rootEl;
			evt.from = fromEl || rootEl;
R
RubaXa 已提交
60
			evt.clone = cloneEl;
R
RubaXa 已提交
61 62 63

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

65
			rootEl.dispatchEvent(evt);
R
RubaXa 已提交
66
		},
67

R
RubaXa 已提交
68
		_customEvents = 'onAdd onUpdate onRemove onStart onEnd onFilter onSort'.split(' '),
R
RubaXa 已提交
69

R
RubaXa 已提交
70
		noop = function () {},
R
RubaXa 已提交
71 72

		abs = Math.abs,
R
RubaXa 已提交
73
		slice = [].slice,
R
RubaXa 已提交
74

R
RubaXa 已提交
75
		touchDragOverListeners = []
R
RubaXa 已提交
76 77 78
	;


79

R
RubaXa 已提交
80 81 82
	/**
	 * @class  Sortable
	 * @param  {HTMLElement}  el
83
	 * @param  {Object}       [options]
R
RubaXa 已提交
84
	 */
R
RubaXa 已提交
85
	function Sortable(el, options) {
R
RubaXa 已提交
86 87 88 89
		this.el = el; // root element
		this.options = options = (options || {});


R
RubaXa 已提交
90
		// Default options
91 92
		var defaults = {
			group: Math.random(),
R
RubaXa 已提交
93
			sort: true,
R
RubaXa 已提交
94
			disabled: false,
95 96
			store: null,
			handle: null,
R
RubaXa 已提交
97 98 99
			scroll: true,
			scrollSensitivity: 30,
			scrollSpeed: 10,
R
RubaXa 已提交
100
			draggable: /[uo]l/i.test(el.nodeName) ? 'li' : '>*',
101 102
			ghostClass: 'sortable-ghost',
			ignore: 'a, img',
103
			filter: null,
R
RubaXa 已提交
104 105 106 107
			animation: 0,
			setData: function (dataTransfer, dragEl) {
				dataTransfer.setData('Text', dragEl.textContent);
			}
R
RubaXa 已提交
108
		};
109

R
RubaXa 已提交
110

111 112
		// Set default options
		for (var name in defaults) {
R
RubaXa 已提交
113
			!(name in options) && (options[name] = defaults[name]);
114
		}
R
RubaXa 已提交
115

116

R
RubaXa 已提交
117 118
		var group = options.group;

R
RubaXa 已提交
119 120
		if (!group || typeof group != 'object') {
			group = options.group = { name: group };
R
RubaXa 已提交
121 122
		}

R
RubaXa 已提交
123

R
RubaXa 已提交
124
		['pull', 'put'].forEach(function (key) {
R
RubaXa 已提交
125 126
			if (!(key in group)) {
				group[key] = true;
R
RubaXa 已提交
127 128 129 130
			}
		});


131
		// Define events
132
		_customEvents.forEach(function (name) {
133
			options[name] = _bind(this, options[name] || noop);
134
			_on(el, name.substr(2).toLowerCase(), options[name]);
R
RubaXa 已提交
135
		}, this);
R
RubaXa 已提交
136 137


R
* JSDoc  
RubaXa 已提交
138
		// Export group name
R
RubaXa 已提交
139
		el[expando] = group.name + ' ' + (group.put.join ? group.put.join(' ') : '');
R
RubaXa 已提交
140 141


R
* JSDoc  
RubaXa 已提交
142
		// Bind all private methods
R
RubaXa 已提交
143 144
		for (var fn in this) {
			if (fn.charAt(0) === '_') {
R
RubaXa 已提交
145 146 147 148 149 150 151 152
				this[fn] = _bind(this, this[fn]);
			}
		}


		// Bind events
		_on(el, 'mousedown', this._onTapStart);
		_on(el, 'touchstart', this._onTapStart);
R
RubaXa 已提交
153
		supportIEdnd && _on(el, 'selectstart', this._onTapStart);
R
RubaXa 已提交
154 155 156 157 158

		_on(el, 'dragover', this._onDragOver);
		_on(el, 'dragenter', this._onDragOver);

		touchDragOverListeners.push(this._onDragOver);
159 160 161

		// Restore sorting
		options.store && this.sort(options.store.get(this));
R
RubaXa 已提交
162 163 164
	}


165
	Sortable.prototype = /** @lends Sortable.prototype */ {
R
RubaXa 已提交
166 167 168
		constructor: Sortable,


R
RubaXa 已提交
169 170
		_dragStarted: function () {
			// Apply effect
R
RubaXa 已提交
171
			_toggleClass(dragEl, this.options.ghostClass, true);
R
RubaXa 已提交
172 173 174 175 176

			Sortable.active = this;

			// Drag start event
			_dispatchEvent(rootEl, 'start', dragEl, rootEl, startIndex);
R
RubaXa 已提交
177 178 179
		},


R
RubaXa 已提交
180
		_onTapStart: function (/**Event|TouchEvent*/evt) {
R
RubaXa 已提交
181 182
			var type = evt.type,
				touch = evt.touches && evt.touches[0],
R
RubaXa 已提交
183
				target = (touch || evt).target,
184
				originalTarget = target,
R
RubaXa 已提交
185 186 187
				options =  this.options,
				el = this.el,
				filter = options.filter;
R
RubaXa 已提交
188

R
RubaXa 已提交
189
			if (type === 'mousedown' && evt.button !== 0 || options.disabled) {
R
RubaXa 已提交
190
				return; // only left button or enabled
R
RubaXa 已提交
191 192
			}

193 194 195 196 197 198 199 200 201
			if (options.handle) {
				target = _closest(target, options.handle, el);
			}

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

			// get the index of the dragged element within its parent
			startIndex = _index(target);

202
			// Check filter
R
RubaXa 已提交
203
			if (typeof filter === 'function') {
R
RubaXa 已提交
204 205
				if (filter.call(this, evt, target, this)) {
					_dispatchEvent(originalTarget, 'filter', target, el, startIndex);
R
RubaXa 已提交
206
					evt.preventDefault();
R
RubaXa 已提交
207 208
					return; // cancel dnd
				}
209
			}
R
RubaXa 已提交
210
			else if (filter) {
R
RubaXa 已提交
211 212 213 214 215 216 217
				filter = filter.split(',').some(function (criteria) {
					criteria = _closest(originalTarget, criteria.trim(), el);

					if (criteria) {
						_dispatchEvent(criteria, 'filter', target, el, startIndex);
						return true;
					}
218 219
				});

R
RubaXa 已提交
220 221
				if (filter) {
					evt.preventDefault();
222 223 224 225
					return; // cancel dnd
				}
			}

R
RubaXa 已提交
226
			// Prepare `dragstart`
R
RubaXa 已提交
227
			if (target && !dragEl && (target.parentNode === el)) {
R
RubaXa 已提交
228 229 230
				// IE 9 Support
				(type === 'selectstart') && target.dragDrop();

R
RubaXa 已提交
231
				tapEvt = evt;
232 233 234 235 236 237 238

				rootEl = this.el;
				dragEl = target;
				nextEl = dragEl.nextSibling;
				activeGroup = this.options.group;

				dragEl.draggable = true;
R
RubaXa 已提交
239 240

				// Disable "draggable"
241
				options.ignore.split(',').forEach(function (criteria) {
Z
ziflex 已提交
242 243
					_find(target, criteria.trim(), _disableDraggable);
				});
R
RubaXa 已提交
244

R
RubaXa 已提交
245
				if (touch) {
R
RubaXa 已提交
246 247
					// Touch device support
					tapEvt = {
R
RubaXa 已提交
248 249 250
						target: target,
						clientX: touch.clientX,
						clientY: touch.clientY
R
RubaXa 已提交
251
					};
252

R
RubaXa 已提交
253 254 255
					this._onDragStart(tapEvt, true);
					evt.preventDefault();
				}
R
RubaXa 已提交
256

257 258 259
				_on(document, 'mouseup', this._onDrop);
				_on(document, 'touchend', this._onDrop);
				_on(document, 'touchcancel', this._onDrop);
R
RubaXa 已提交
260

R
RubaXa 已提交
261
				_on(dragEl, 'dragend', this);
R
RubaXa 已提交
262 263
				_on(rootEl, 'dragstart', this._onDragStart);

R
RubaXa 已提交
264
				_on(document, 'dragover', this);
R
RubaXa 已提交
265 266 267


				try {
R
RubaXa 已提交
268
					if (document.selection) {
R
RubaXa 已提交
269 270
						document.selection.empty();
					} else {
R
RubaXa 已提交
271
						window.getSelection().removeAllRanges();
R
RubaXa 已提交
272
					}
R
RubaXa 已提交
273 274
				} catch (err) {
				}
275 276


R
RubaXa 已提交
277 278 279 280 281
				if (activeGroup.pull == 'clone') {
					cloneEl = dragEl.cloneNode(true);
					_css(cloneEl, 'display', 'none');
					rootEl.insertBefore(cloneEl, dragEl);
				}
R
RubaXa 已提交
282 283 284
			}
		},

R
RubaXa 已提交
285 286
		_emulateDragOver: function () {
			if (touchEvt) {
R
RubaXa 已提交
287 288
				_css(ghostEl, 'display', 'none');

R
RubaXa 已提交
289
				var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY),
R
RubaXa 已提交
290
					parent = target,
R
RubaXa 已提交
291 292
					groupName = this.options.group.name,
					i = touchDragOverListeners.length;
R
RubaXa 已提交
293

R
RubaXa 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
				if (parent) {
					do {
						if ((' ' + parent[expando] + ' ').indexOf(groupName) > -1) {
							while (i--) {
								touchDragOverListeners[i]({
									clientX: touchEvt.clientX,
									clientY: touchEvt.clientY,
									target: target,
									rootEl: parent
								});
							}

							break;
						}

						target = parent; // store last element
L
Larry Davis 已提交
310
					}
R
RubaXa 已提交
311 312
					/* jshint boss:true */
					while (parent = parent.parentNode);
R
RubaXa 已提交
313 314 315 316 317 318 319
				}

				_css(ghostEl, 'display', '');
			}
		},


R
RubaXa 已提交
320 321 322 323 324 325
		_onTouchMove: function (/**TouchEvent*/evt) {
			if (tapEvt) {
				var touch = evt.touches[0],
					dx = touch.clientX - tapEvt.clientX,
					dy = touch.clientY - tapEvt.clientY,
					translate3d = 'translate3d(' + dx + 'px,' + dy + 'px,0)';
R
RubaXa 已提交
326 327

				touchEvt = touch;
R
RubaXa 已提交
328 329 330 331 332 333

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

R
RubaXa 已提交
334
				this._onDrag(touch);
M
Marius Petcu 已提交
335
				evt.preventDefault();
R
RubaXa 已提交
336 337 338 339
			}
		},


R
RubaXa 已提交
340
		_onDragStart: function (/**Event*/evt, /**boolean*/isTouch) {
R
RubaXa 已提交
341 342
			var dataTransfer = evt.dataTransfer,
				options = this.options;
R
RubaXa 已提交
343

344
			this._offUpEvents();
R
RubaXa 已提交
345

R
RubaXa 已提交
346 347 348 349
			if (isTouch) {
				var rect = dragEl.getBoundingClientRect(),
					css = _css(dragEl),
					ghostRect;
R
RubaXa 已提交
350

351
				ghostEl = dragEl.cloneNode(true);
R
RubaXa 已提交
352 353 354

				_css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10));
				_css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10));
R
RubaXa 已提交
355 356
				_css(ghostEl, 'width', rect.width);
				_css(ghostEl, 'height', rect.height);
R
RubaXa 已提交
357 358 359 360
				_css(ghostEl, 'opacity', '0.8');
				_css(ghostEl, 'position', 'fixed');
				_css(ghostEl, 'zIndex', '100000');

R
RubaXa 已提交
361 362 363 364
				rootEl.appendChild(ghostEl);

				// Fixing dimensions.
				ghostRect = ghostEl.getBoundingClientRect();
R
RubaXa 已提交
365 366
				_css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
				_css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
R
RubaXa 已提交
367 368 369 370

				// Bind touch events
				_on(document, 'touchmove', this._onTouchMove);
				_on(document, 'touchend', this._onDrop);
M
Marius Petcu 已提交
371
				_on(document, 'touchcancel', this._onDrop);
R
RubaXa 已提交
372

R
RubaXa 已提交
373
				this._loopId = setInterval(this._emulateDragOver, 150);
R
RubaXa 已提交
374 375
			}
			else {
R
RubaXa 已提交
376 377 378 379
				if (dataTransfer) {
					dataTransfer.effectAllowed = 'move';
					options.setData && options.setData.call(this, dataTransfer, dragEl);
				}
R
RubaXa 已提交
380

R
RubaXa 已提交
381
				_on(document, 'drop', this);
R
RubaXa 已提交
382 383
			}

R
RubaXa 已提交
384 385 386
			scrollEl = options.scroll;

			if (scrollEl === true) {
R
RubaXa 已提交
387
				scrollEl = rootEl;
R
RubaXa 已提交
388 389 390 391 392 393 394 395 396 397

				do {
					if ((scrollEl.offsetWidth < scrollEl.scrollWidth) ||
						(scrollEl.offsetHeight < scrollEl.scrollHeight)
					) {
						break;
					}
				/* jshint boss:true */
				} while (scrollEl = scrollEl.parentNode);
			}
R
RubaXa 已提交
398 399

			setTimeout(this._dragStarted, 0);
R
RubaXa 已提交
400 401
		},

R
RubaXa 已提交
402
		_onDrag: _throttle(function (/**Event*/evt) {
R
RubaXa 已提交
403
			// Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
R
RubaXa 已提交
404
			if (rootEl && this.options.scroll) {
R
RubaXa 已提交
405 406 407
				var el,
					rect,
					options = this.options,
R
RubaXa 已提交
408 409 410 411 412 413 414 415 416
					sens = options.scrollSensitivity,
					speed = options.scrollSpeed,

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

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

R
RubaXa 已提交
417 418
					vx = (winWidth - x <= sens) - (x <= sens),
					vy = (winHeight - y <= sens) - (y <= sens)
R
RubaXa 已提交
419 420 421
				;

				if (vx || vy) {
R
RubaXa 已提交
422
					el = win;
R
RubaXa 已提交
423 424
				}
				else if (scrollEl) {
R
RubaXa 已提交
425
					el = scrollEl;
R
RubaXa 已提交
426 427 428
					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);
R
RubaXa 已提交
429 430 431 432 433 434
				}

				if (autoScroll.vx !== vx || autoScroll.vy !== vy || autoScroll.el !== el) {
					autoScroll.el = el;
					autoScroll.vx = vx;
					autoScroll.vy = vy;
R
RubaXa 已提交
435

R
RubaXa 已提交
436 437 438 439 440 441 442 443 444 445 446 447
					clearInterval(autoScroll.pid);

					if (el) {
						autoScroll.pid = setInterval(function () {
							if (el === win) {
								win.scrollTo(win.scrollX + vx * speed, win.scrollY + vy * speed);
							} else {
								vy && (el.scrollTop += vy * speed);
								vx && (el.scrollLeft += vx * speed);
							}
						}, 24);
					}
R
RubaXa 已提交
448 449 450 451
				}
			}
		}, 30),

R
RubaXa 已提交
452

R
RubaXa 已提交
453
		_onDragOver: function (/**Event*/evt) {
R
RubaXa 已提交
454 455 456 457 458 459
			var el = this.el,
				target,
				dragRect,
				revert,
				options = this.options,
				group = options.group,
R
RubaXa 已提交
460
				groupPut = group.put,
461 462
				isOwner = (activeGroup === group),
				canSort = options.sort;
R
RubaXa 已提交
463

R
RubaXa 已提交
464 465 466 467
			if (evt.preventDefault !== void 0) {
				evt.preventDefault();
				evt.stopPropagation();
			}
R
RubaXa 已提交
468

R
RubaXa 已提交
469
			if (!_silent && activeGroup &&
470 471
				(isOwner
					? canSort || (revert = !rootEl.contains(dragEl))
R
RubaXa 已提交
472 473 474 475
					: activeGroup.pull && groupPut && (
						(activeGroup.name === group.name) || // by Name
						(groupPut.indexOf && ~groupPut.indexOf(activeGroup.name)) // by Array
					)
476
				) &&
R
RubaXa 已提交
477
				(evt.rootEl === void 0 || evt.rootEl === this.el)
R
RubaXa 已提交
478
			) {
R
RubaXa 已提交
479
				target = _closest(evt.target, options.draggable, el);
R
RubaXa 已提交
480 481 482
				dragRect = dragEl.getBoundingClientRect();


483
				if (revert) {
R
RubaXa 已提交
484 485
					_cloneHide(true);

486 487 488 489 490 491 492
					if (cloneEl || nextEl) {
						rootEl.insertBefore(dragEl, cloneEl || nextEl);
					}
					else if (!canSort) {
						rootEl.appendChild(dragEl);
					}

R
RubaXa 已提交
493 494
					return;
				}
R
RubaXa 已提交
495

R
RubaXa 已提交
496

R
RubaXa 已提交
497
				if ((el.children.length === 0) || (el.children[0] === ghostEl) ||
R
RubaXa 已提交
498
					(el === evt.target) && (target = _ghostInBottom(el, evt))
R
RubaXa 已提交
499
				) {
R
RubaXa 已提交
500 501 502 503 504 505
					if (target) {
						if (target.animated) {
							return;
						}
						targetRect = target.getBoundingClientRect();
					}
R
RubaXa 已提交
506

R
RubaXa 已提交
507 508
					_cloneHide(isOwner);

R
RubaXa 已提交
509
					el.appendChild(dragEl);
R
* anim  
RubaXa 已提交
510
					this._animate(dragRect, dragEl);
R
RubaXa 已提交
511
					target && this._animate(targetRect, target);
R
RubaXa 已提交
512
				}
R
RubaXa 已提交
513 514
				else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) {
					if (lastEl !== target) {
R
RubaXa 已提交
515
						lastEl = target;
R
RubaXa 已提交
516
						lastCSS = _css(target);
R
RubaXa 已提交
517 518 519
					}


R
RubaXa 已提交
520 521 522 523 524 525 526 527 528
					var targetRect = target.getBoundingClientRect(),
						width = targetRect.right - targetRect.left,
						height = targetRect.bottom - targetRect.top,
						floating = /left|right|inline/.test(lastCSS.cssFloat + lastCSS.display),
						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,
						after
R
RubaXa 已提交
529
					;
R
RubaXa 已提交
530

R
RubaXa 已提交
531 532 533
					_silent = true;
					setTimeout(_unsilent, 30);

R
RubaXa 已提交
534 535
					_cloneHide(isOwner);

R
RubaXa 已提交
536 537
					if (floating) {
						after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
R
RubaXa 已提交
538
					} else {
R
RubaXa 已提交
539
						after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
R
RubaXa 已提交
540 541
					}

R
RubaXa 已提交
542
					if (after && !nextSibling) {
R
RubaXa 已提交
543 544 545
						el.appendChild(dragEl);
					} else {
						target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
R
RubaXa 已提交
546
					}
R
RubaXa 已提交
547

R
RubaXa 已提交
548 549
					this._animate(dragRect, dragEl);
					this._animate(targetRect, target);
R
RubaXa 已提交
550 551 552 553
				}
			}
		},

554 555 556 557 558 559
		_animate: function (prevRect, target) {
			var ms = this.options.animation;

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

R
RubaXa 已提交
560
				_css(target, 'transition', 'none');
561 562 563 564 565 566 567
				_css(target, 'transform', 'translate3d('
					+ (prevRect.left - currentRect.left) + 'px,'
					+ (prevRect.top - currentRect.top) + 'px,0)'
				);

				target.offsetWidth; // repaint

R
RubaXa 已提交
568
				_css(target, 'transition', 'all ' + ms + 'ms');
569 570
				_css(target, 'transform', 'translate3d(0,0,0)');

R
* anim  
RubaXa 已提交
571 572
				clearTimeout(target.animated);
				target.animated = setTimeout(function () {
573 574 575 576 577 578
					_css(target, 'transition', '');
					target.animated = false;
				}, ms);
			}
		},

579 580 581 582 583 584
		_offUpEvents: function () {
			_off(document, 'mouseup', this._onDrop);
			_off(document, 'touchmove', this._onTouchMove);
			_off(document, 'touchend', this._onDrop);
			_off(document, 'touchcancel', this._onDrop);
		},
R
RubaXa 已提交
585

R
RubaXa 已提交
586
		_onDrop: function (/**Event*/evt) {
R
RubaXa 已提交
587 588
			var el = this.el;

R
RubaXa 已提交
589
			clearInterval(this._loopId);
R
RubaXa 已提交
590
			clearInterval(autoScroll.pid);
R
RubaXa 已提交
591 592

			// Unbind events
R
RubaXa 已提交
593
			_off(document, 'drop', this);
R
RubaXa 已提交
594
			_off(document, 'dragover', this);
R
RubaXa 已提交
595

R
RubaXa 已提交
596
			_off(el, 'dragstart', this._onDragStart);
R
RubaXa 已提交
597

598
			this._offUpEvents();
R
RubaXa 已提交
599

R
RubaXa 已提交
600
			if (evt) {
R
RubaXa 已提交
601
				evt.preventDefault();
R
RubaXa 已提交
602
				evt.stopPropagation();
R
RubaXa 已提交
603

R
RubaXa 已提交
604
				ghostEl && ghostEl.parentNode.removeChild(ghostEl);
R
RubaXa 已提交
605

R
RubaXa 已提交
606
				if (dragEl) {
R
RubaXa 已提交
607 608
					_off(dragEl, 'dragend', this);

609 610
					// get the index of the dragged element within its parent
					var newIndex = _index(dragEl);
R
RubaXa 已提交
611

612
					_disableDraggable(dragEl);
R
RubaXa 已提交
613 614
					_toggleClass(dragEl, this.options.ghostClass, false);

615
					if (rootEl !== dragEl.parentNode) {
616
						// drag from one list and drop into another
R
RubaXa 已提交
617 618
						_dispatchEvent(dragEl.parentNode, 'sort', dragEl, rootEl, startIndex, newIndex);
						_dispatchEvent(rootEl, 'sort', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
619 620

						// Add event
621
						_dispatchEvent(dragEl, 'add', dragEl, rootEl, startIndex, newIndex);
622 623

						// Remove event
R
RubaXa 已提交
624
						_dispatchEvent(rootEl, 'remove', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
625
					}
R
RubaXa 已提交
626
					else if (dragEl.nextSibling !== nextEl) {
627
						// drag & drop within the same list
R
RubaXa 已提交
628 629
						_dispatchEvent(rootEl, 'update', dragEl, rootEl, startIndex, newIndex);
						_dispatchEvent(rootEl, 'sort', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
630

R
RubaXa 已提交
631
						cloneEl && cloneEl.parentNode.removeChild(cloneEl);
R
RubaXa 已提交
632
					}
633

R
RubaXa 已提交
634
					// Drag end event
R
RubaXa 已提交
635
					Sortable.active && _dispatchEvent(rootEl, 'end', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
636 637 638 639 640 641 642
				}

				// Set NULL
				rootEl =
				dragEl =
				ghostEl =
				nextEl =
R
RubaXa 已提交
643
				cloneEl =
R
RubaXa 已提交
644 645 646 647 648 649 650

				tapEvt =
				touchEvt =

				lastEl =
				lastCSS =

R
RubaXa 已提交
651 652
				activeGroup =
				Sortable.active = null;
653 654

				// Save sorting
R
RubaXa 已提交
655
				this.save();
R
RubaXa 已提交
656 657 658 659
			}
		},


R
RubaXa 已提交
660 661 662 663 664 665 666
		handleEvent: function (/**Event*/evt) {
			var type = evt.type;

			if (type === 'dragover') {
				this._onDrag(evt);
				_globalDragOver(evt);
			}
R
RubaXa 已提交
667
			else if (type === 'drop' || type === 'dragend') {
R
RubaXa 已提交
668 669
				this._onDrop(evt);
			}
R
RubaXa 已提交
670 671 672
		},


673 674 675 676 677 678 679 680 681
		/**
		 * Serializes the item into an array of string.
		 * @returns {String[]}
		 */
		toArray: function () {
			var order = [],
				el,
				children = this.el.children,
				i = 0,
R
RubaXa 已提交
682
				n = children.length;
683 684 685

			for (; i < n; i++) {
				el = children[i];
R
RubaXa 已提交
686 687 688
				if (_closest(el, this.options.draggable, this.el)) {
					order.push(el.getAttribute('data-id') || _generateId(el));
				}
689 690 691 692 693 694 695 696 697 698 699
			}

			return order;
		},


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

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

R
RubaXa 已提交
705
				if (_closest(el, this.options.draggable, rootEl)) {
R
RubaXa 已提交
706 707 708
					items[id] = el;
				}
			}, this);
709 710 711

			order.forEach(function (id) {
				if (items[id]) {
R
RubaXa 已提交
712 713
					rootEl.removeChild(items[id]);
					rootEl.appendChild(items[id]);
714 715 716 717 718
				}
			});
		},


R
RubaXa 已提交
719 720 721 722 723 724 725 726 727
		/**
		 * Save the current sorting
		 */
		save: function () {
			var store = this.options.store;
			store && store.set(this);
		},


728 729 730 731 732 733 734 735 736 737 738
		/**
		 * 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);
		},


739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
		/**
		 * 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;
			}
		},


756 757 758 759
		/**
		 * Destroy
		 */
		destroy: function () {
R
RubaXa 已提交
760 761
			var el = this.el, options = this.options;

762 763 764 765
			_customEvents.forEach(function (name) {
				_off(el, name.substr(2).toLowerCase(), options[name]);
			});

R
RubaXa 已提交
766 767
			_off(el, 'mousedown', this._onTapStart);
			_off(el, 'touchstart', this._onTapStart);
N
Nicolas 已提交
768
			_off(el, 'selectstart', this._onTapStart);
R
RubaXa 已提交
769 770 771 772

			_off(el, 'dragover', this._onDragOver);
			_off(el, 'dragenter', this._onDragOver);

773
			//remove draggable attributes
R
RubaXa 已提交
774
			Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
775 776 777
				el.removeAttribute('draggable');
			});

R
RubaXa 已提交
778 779 780 781 782 783 784 785
			touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);

			this._onDrop();

			this.el = null;
		}
	};

786

R
RubaXa 已提交
787 788 789 790 791 792 793 794 795
	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 已提交
796
	function _bind(ctx, fn) {
R
RubaXa 已提交
797
		var args = slice.call(arguments, 2);
R
RubaXa 已提交
798
		return	fn.bind ? fn.bind.apply(fn, [ctx].concat(args)) : function () {
R
RubaXa 已提交
799 800 801 802 803
			return fn.apply(ctx, args.concat(slice.call(arguments)));
		};
	}


R
RubaXa 已提交
804
	function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) {
R
RubaXa 已提交
805
		if (el) {
R
RubaXa 已提交
806 807 808
			ctx = ctx || document;
			selector = selector.split('.');

R
RubaXa 已提交
809 810
			var tag = selector.shift().toUpperCase(),
				re = new RegExp('\\s(' + selector.join('|') + ')\\s', 'g');
R
RubaXa 已提交
811 812

			do {
R
RubaXa 已提交
813
				if (
R
RubaXa 已提交
814 815 816 817
					(tag === '>*' && el.parentNode === ctx) || (
						(tag === '' || el.nodeName == tag) &&
						(!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
					)
R
RubaXa 已提交
818 819
				) {
					return el;
R
RubaXa 已提交
820 821
				}
			}
R
RubaXa 已提交
822
			while (el !== ctx && (el = el.parentNode));
R
RubaXa 已提交
823 824
		}

R
RubaXa 已提交
825
		return null;
R
RubaXa 已提交
826 827 828
	}


829
	function _globalDragOver(/**Event*/evt) {
R
RubaXa 已提交
830 831 832 833 834
		evt.dataTransfer.dropEffect = 'move';
		evt.preventDefault();
	}


R
RubaXa 已提交
835
	function _on(el, event, fn) {
R
RubaXa 已提交
836 837 838 839
		el.addEventListener(event, fn, false);
	}


R
RubaXa 已提交
840
	function _off(el, event, fn) {
R
RubaXa 已提交
841 842 843 844
		el.removeEventListener(event, fn, false);
	}


R
RubaXa 已提交
845 846 847
	function _toggleClass(el, name, state) {
		if (el) {
			if (el.classList) {
R
RubaXa 已提交
848 849 850
				el.classList[state ? 'add' : 'remove'](name);
			}
			else {
R
RubaXa 已提交
851 852
				var className = (' ' + el.className + ' ').replace(/\s+/g, ' ').replace(' ' + name + ' ', '');
				el.className = className + (state ? ' ' + name : '');
R
RubaXa 已提交
853 854 855 856 857
			}
		}
	}


R
RubaXa 已提交
858
	function _css(el, prop, val) {
R
RubaXa 已提交
859 860
		var style = el && el.style;

R
RubaXa 已提交
861 862 863
		if (style) {
			if (val === void 0) {
				if (document.defaultView && document.defaultView.getComputedStyle) {
R
RubaXa 已提交
864 865
					val = document.defaultView.getComputedStyle(el, '');
				}
R
RubaXa 已提交
866 867
				else if (el.currentStyle) {
					val = el.currentStyle;
R
RubaXa 已提交
868
				}
R
RubaXa 已提交
869 870 871 872 873 874 875 876 877

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

				style[prop] = val + (typeof val === 'string' ? '' : 'px');
R
RubaXa 已提交
878 879 880 881 882
			}
		}
	}


R
RubaXa 已提交
883 884
	function _find(ctx, tagName, iterator) {
		if (ctx) {
R
RubaXa 已提交
885
			var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
R
RubaXa 已提交
886

R
RubaXa 已提交
887 888
			if (iterator) {
				for (; i < n; i++) {
R
RubaXa 已提交
889 890 891
					iterator(list[i], i);
				}
			}
R
RubaXa 已提交
892

R
RubaXa 已提交
893
			return list;
R
RubaXa 已提交
894
		}
R
RubaXa 已提交
895 896

		return [];
R
RubaXa 已提交
897 898 899
	}


R
RubaXa 已提交
900
	function _disableDraggable(el) {
R
RubaXa 已提交
901
		el.draggable = false;
R
RubaXa 已提交
902 903 904
	}


R
RubaXa 已提交
905
	function _unsilent() {
R
RubaXa 已提交
906 907 908 909
		_silent = false;
	}


R
RubaXa 已提交
910
	/** @returns {HTMLElement|false} */
R
RubaXa 已提交
911
	function _ghostInBottom(el, evt) {
R
RubaXa 已提交
912 913
		var lastEl = el.lastElementChild, rect = lastEl.getBoundingClientRect();
		return (evt.clientY - (rect.top + rect.height) > 5) && lastEl; // min delta
R
RubaXa 已提交
914 915 916
	}


917 918 919 920 921 922 923
	/**
	 * Generate id
	 * @param   {HTMLElement} el
	 * @returns {String}
	 * @private
	 */
	function _generateId(el) {
R
RubaXa 已提交
924
		var str = el.tagName + el.className + el.src + el.href + el.textContent,
925
			i = str.length,
R
RubaXa 已提交
926
			sum = 0;
927

928 929 930
		while (i--) {
			sum += str.charCodeAt(i);
		}
931

932 933 934
		return sum.toString(36);
	}

935 936 937
	/**
	 * Returns the index of an element within its parent
	 * @param el
938 939
	 * @returns {number}
	 * @private
940 941 942
	 */
	function _index(/**HTMLElement*/el) {
		var index = 0;
G
Greg Hoyl 已提交
943
		while (el && (el = el.previousElementSibling) && (el.nodeName !== 'TEMPLATE')) {
944 945 946 947
			index++;
		}
		return index;
	}
R
RubaXa 已提交
948

R
RubaXa 已提交
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
	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);
			}
		};
	}


R
RubaXa 已提交
971 972 973 974 975 976 977
	// Export utils
	Sortable.utils = {
		on: _on,
		off: _off,
		css: _css,
		find: _find,
		bind: _bind,
R
RubaXa 已提交
978 979 980
		is: function (el, selector) {
			return !!_closest(el, selector, el);
		},
R
RubaXa 已提交
981
		throttle: _throttle,
R
RubaXa 已提交
982
		closest: _closest,
983
		toggleClass: _toggleClass,
984 985
		dispatchEvent: _dispatchEvent,
		index: _index
R
RubaXa 已提交
986 987 988
	};


R
RubaXa 已提交
989
	Sortable.version = '1.0.0';
990

R
RubaXa 已提交
991

992 993 994 995 996 997
	/**
	 * Create sortable instance
	 * @param {HTMLElement}  el
	 * @param {Object}      [options]
	 */
	Sortable.create = function (el, options) {
R
RubaXa 已提交
998
		return new Sortable(el, options);
999
	};
R
RubaXa 已提交
1000 1001

	// Export
1002
	return Sortable;
R
RubaXa 已提交
1003
});