Sortable.js 19.9 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 28 29 30
	var dragEl,
		ghostEl,
		cloneEl,
		rootEl,
R
RubaXa 已提交
31
		scrollEl,
R
RubaXa 已提交
32
		nextEl,
R
RubaXa 已提交
33

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

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

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

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

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

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

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

55 56 57 58 59
			evt.initEvent(name, true, true);
			evt.item = targetEl || rootEl;
			evt.from = fromEl || rootEl;

			rootEl.dispatchEvent(evt);
R
RubaXa 已提交
60
		},
61

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

R
RubaXa 已提交
64
		noop = function () {},
R
RubaXa 已提交
65 66

		abs = Math.abs,
R
RubaXa 已提交
67
		slice = [].slice,
R
RubaXa 已提交
68

R
RubaXa 已提交
69
		touchDragOverListeners = []
R
RubaXa 已提交
70 71 72
	;


73

R
RubaXa 已提交
74 75 76
	/**
	 * @class  Sortable
	 * @param  {HTMLElement}  el
77
	 * @param  {Object}       [options]
R
RubaXa 已提交
78
	 */
R
RubaXa 已提交
79
	function Sortable(el, options) {
R
RubaXa 已提交
80 81 82 83
		this.el = el; // root element
		this.options = options = (options || {});


R
RubaXa 已提交
84
		// Default options
85 86
		var defaults = {
			group: Math.random(),
R
RubaXa 已提交
87
			sort: true,
88 89
			store: null,
			handle: null,
R
RubaXa 已提交
90 91 92
			scroll: true,
			scrollSensitivity: 30,
			scrollSpeed: 10,
93 94 95
			draggable: el.children[0] && el.children[0].nodeName || (/[uo]l/i.test(el.nodeName) ? 'li' : '*'),
			ghostClass: 'sortable-ghost',
			ignore: 'a, img',
96
			filter: null,
R
RubaXa 已提交
97 98 99 100
			animation: 0,
			setData: function (dataTransfer, dragEl) {
				dataTransfer.setData('Text', dragEl.textContent);
			}
101 102
		};

R
RubaXa 已提交
103

104 105
		// Set default options
		for (var name in defaults) {
R
RubaXa 已提交
106
			!(name in options) && (options[name] = defaults[name]);
107
		}
R
RubaXa 已提交
108

109

R
RubaXa 已提交
110 111 112 113
		if (!options.group.name) {
			options.group = { name: options.group };
		}

R
RubaXa 已提交
114

R
RubaXa 已提交
115 116 117 118 119 120 121
		['pull', 'put'].forEach(function (key) {
			if (!(key in options.group)) {
				options.group[key] = true;
			}
		});


122
		// Define events
123
		_customEvents.forEach(function (name) {
124
			options[name] = _bind(this, options[name] || noop);
125
			_on(el, name.substr(2).toLowerCase(), options[name]);
R
RubaXa 已提交
126
		}, this);
R
RubaXa 已提交
127 128


R
* JSDoc  
RubaXa 已提交
129
		// Export group name
R
RubaXa 已提交
130
		el[expando] = options.group.name;
R
RubaXa 已提交
131 132


R
* JSDoc  
RubaXa 已提交
133
		// Bind all private methods
R
RubaXa 已提交
134 135
		for (var fn in this) {
			if (fn.charAt(0) === '_') {
R
RubaXa 已提交
136 137 138 139 140 141 142 143
				this[fn] = _bind(this, this[fn]);
			}
		}


		// Bind events
		_on(el, 'mousedown', this._onTapStart);
		_on(el, 'touchstart', this._onTapStart);
R
RubaXa 已提交
144
		supportIEdnd && _on(el, 'selectstart', this._onTapStart);
R
RubaXa 已提交
145 146 147 148 149

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

		touchDragOverListeners.push(this._onDragOver);
150 151 152

		// Restore sorting
		options.store && this.sort(options.store.get(this));
R
RubaXa 已提交
153 154 155
	}


156
	Sortable.prototype = /** @lends Sortable.prototype */ {
R
RubaXa 已提交
157 158 159
		constructor: Sortable,


R
RubaXa 已提交
160
		_applyEffects: function () {
R
RubaXa 已提交
161 162 163 164
			_toggleClass(dragEl, this.options.ghostClass, true);
		},


R
RubaXa 已提交
165 166 167 168 169 170 171
		_onTapStart: function (/**Event|TouchEvent*/evt) {
			var touch = evt.touches && evt.touches[0],
				target = (touch || evt).target,
				options =  this.options,
				el = this.el,
				filter = options.filter;

R
RubaXa 已提交
172

R
RubaXa 已提交
173
			if (evt.type === 'mousedown' && evt.button !== 0) {
R
RubaXa 已提交
174 175 176
				return; // only left button
			}

177
			// Check filter
R
RubaXa 已提交
178 179
			if (typeof filter === 'function') {
				if (filter.call(this, target, this)) {
R
RubaXa 已提交
180 181 182
					_dispatchEvent(el, 'filter', target);
					return; // cancel dnd
				}
183
			}
R
RubaXa 已提交
184
			else if (filter) {
185 186 187 188 189 190 191 192 193 194
				filter = filter.split(',').filter(function (criteria) {
					return _closest(target, criteria.trim(), el);
				});

				if (filter.length) {
					_dispatchEvent(el, 'filter', target);
					return; // cancel dnd
				}
			}

R
RubaXa 已提交
195
			if (options.handle) {
R
RubaXa 已提交
196
				target = _closest(target, options.handle, el);
R
RubaXa 已提交
197 198
			}

R
RubaXa 已提交
199
			target = _closest(target, options.draggable, el);
R
RubaXa 已提交
200

R
RubaXa 已提交
201
			// IE 9 Support
R
RubaXa 已提交
202 203
			if (target && evt.type == 'selectstart') {
				if (target.tagName != 'A' && target.tagName != 'IMG') {
204 205 206
					target.dragDrop();
				}
			}
N
Nicolas 已提交
207

R
RubaXa 已提交
208
			if (target && !dragEl && (target.parentNode === el)) {
R
RubaXa 已提交
209
				tapEvt = evt;
210 211 212 213 214 215 216

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

				dragEl.draggable = true;
R
RubaXa 已提交
217 218

				// Disable "draggable"
219
				options.ignore.split(',').forEach(function (criteria) {
Z
ziflex 已提交
220 221
					_find(target, criteria.trim(), _disableDraggable);
				});
R
RubaXa 已提交
222

R
RubaXa 已提交
223
				if (touch) {
R
RubaXa 已提交
224 225
					// Touch device support
					tapEvt = {
R
RubaXa 已提交
226 227 228
						target: target,
						clientX: touch.clientX,
						clientY: touch.clientY
R
RubaXa 已提交
229
					};
230

R
RubaXa 已提交
231 232 233
					this._onDragStart(tapEvt, true);
					evt.preventDefault();
				}
R
RubaXa 已提交
234

235 236 237
				_on(document, 'mouseup', this._onDrop);
				_on(document, 'touchend', this._onDrop);
				_on(document, 'touchcancel', this._onDrop);
R
RubaXa 已提交
238

R
RubaXa 已提交
239 240 241
				_on(rootEl, 'dragstart', this._onDragStart);
				_on(rootEl, 'dragend', this._onDrop);

R
RubaXa 已提交
242
				_on(document, 'dragover', this);
R
RubaXa 已提交
243 244 245


				try {
R
RubaXa 已提交
246
					if (document.selection) {
R
RubaXa 已提交
247 248
						document.selection.empty();
					} else {
R
RubaXa 已提交
249
						window.getSelection().removeAllRanges();
R
RubaXa 已提交
250
					}
R
RubaXa 已提交
251 252
				} catch (err) {
				}
253 254


255
				_dispatchEvent(dragEl, 'start');
R
RubaXa 已提交
256 257


R
RubaXa 已提交
258 259 260 261 262
				if (activeGroup.pull == 'clone') {
					cloneEl = dragEl.cloneNode(true);
					_css(cloneEl, 'display', 'none');
					rootEl.insertBefore(cloneEl, dragEl);
				}
R
RubaXa 已提交
263 264 265
			}
		},

R
RubaXa 已提交
266 267
		_emulateDragOver: function () {
			if (touchEvt) {
R
RubaXa 已提交
268 269
				_css(ghostEl, 'display', 'none');

R
RubaXa 已提交
270 271 272 273
				var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY),
					parent = target,
					groupName = this.options.group.name,
					i = touchDragOverListeners.length;
R
RubaXa 已提交
274

R
RubaXa 已提交
275
				if (parent) {
L
Larry Davis 已提交
276
					do {
R
RubaXa 已提交
277 278
						if (parent[expando] === groupName) {
							while (i--) {
L
Larry Davis 已提交
279 280 281 282 283 284 285
								touchDragOverListeners[i]({
									clientX: touchEvt.clientX,
									clientY: touchEvt.clientY,
									target: target,
									rootEl: parent
								});
							}
R
RubaXa 已提交
286

L
Larry Davis 已提交
287
							break;
R
RubaXa 已提交
288
						}
R
RubaXa 已提交
289

L
Larry Davis 已提交
290 291
						target = parent; // store last element
					}
R
RubaXa 已提交
292 293
					/* jshint boss:true */
					while (parent = parent.parentNode);
R
RubaXa 已提交
294 295 296 297 298 299 300
				}

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


R
RubaXa 已提交
301 302 303 304 305 306
		_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 已提交
307 308

				touchEvt = touch;
R
RubaXa 已提交
309 310 311 312 313 314

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

R
RubaXa 已提交
315
				this._onDrag(touch);
M
Marius Petcu 已提交
316
				evt.preventDefault();
R
RubaXa 已提交
317 318 319 320
			}
		},


R
RubaXa 已提交
321
		_onDragStart: function (/**Event*/evt, /**boolean*/isTouch) {
R
RubaXa 已提交
322 323
			var dataTransfer = evt.dataTransfer,
				options = this.options;
R
RubaXa 已提交
324

325
			this._offUpEvents();
R
RubaXa 已提交
326

R
RubaXa 已提交
327 328 329 330
			if (isTouch) {
				var rect = dragEl.getBoundingClientRect(),
					css = _css(dragEl),
					ghostRect;
R
RubaXa 已提交
331

332
				ghostEl = dragEl.cloneNode(true);
R
RubaXa 已提交
333 334 335

				_css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10));
				_css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10));
R
RubaXa 已提交
336 337
				_css(ghostEl, 'width', rect.width);
				_css(ghostEl, 'height', rect.height);
R
RubaXa 已提交
338 339 340 341
				_css(ghostEl, 'opacity', '0.8');
				_css(ghostEl, 'position', 'fixed');
				_css(ghostEl, 'zIndex', '100000');

R
RubaXa 已提交
342 343 344 345
				rootEl.appendChild(ghostEl);

				// Fixing dimensions.
				ghostRect = ghostEl.getBoundingClientRect();
R
RubaXa 已提交
346 347
				_css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
				_css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
R
RubaXa 已提交
348 349 350 351

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

R
RubaXa 已提交
354
				this._loopId = setInterval(this._emulateDragOver, 150);
R
RubaXa 已提交
355 356 357
			}
			else {
				dataTransfer.effectAllowed = 'move';
R
RubaXa 已提交
358
				options.setData && options.setData.call(this, dataTransfer, dragEl);
R
RubaXa 已提交
359 360 361 362

				_on(document, 'drop', this._onDrop);
			}

R
RubaXa 已提交
363 364 365 366 367
			setTimeout(this._applyEffects, 0);

			scrollEl = options.scroll;

			if (scrollEl === true) {
R
RubaXa 已提交
368
				scrollEl = rootEl;
R
RubaXa 已提交
369 370 371 372 373 374 375 376 377 378

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

R
RubaXa 已提交
381
		_onDrag: _throttle(function (/**Event*/evt) {
R
RubaXa 已提交
382
			// Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
R
RubaXa 已提交
383
			if (rootEl && this.options.scroll) {
R
RubaXa 已提交
384 385 386
				var el,
					rect,
					options = this.options,
R
RubaXa 已提交
387 388 389 390 391 392 393 394 395
					sens = options.scrollSensitivity,
					speed = options.scrollSpeed,

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

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

R
RubaXa 已提交
396 397
					vx = (winWidth - x <= sens) - (x <= sens),
					vy = (winHeight - y <= sens) - (y <= sens)
R
RubaXa 已提交
398 399 400
				;

				if (vx || vy) {
R
RubaXa 已提交
401
					el = win;
R
RubaXa 已提交
402 403
				}
				else if (scrollEl) {
R
RubaXa 已提交
404
					el = scrollEl;
R
RubaXa 已提交
405 406 407
					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 已提交
408 409 410 411 412 413
				}

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

R
RubaXa 已提交
415 416 417 418 419 420 421 422 423 424 425 426
					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 已提交
427 428 429 430 431
				}
			}
		}, 30),


R
RubaXa 已提交
432
		_onDragOver: function (/**Event*/evt) {
R
RubaXa 已提交
433 434 435 436 437 438
			var el = this.el,
				target,
				dragRect,
				revert,
				options = this.options,
				group = options.group,
R
RubaXa 已提交
439
				groupPut = group.put,
R
RubaXa 已提交
440 441
				isOwner = (activeGroup === group);

R
RubaXa 已提交
442
			if (!_silent &&
R
RubaXa 已提交
443 444
				(activeGroup.name === group.name || groupPut && groupPut.indexOf && groupPut.indexOf(activeGroup.name) > -1) &&
				(isOwner && (options.sort || (revert = !rootEl.contains(dragEl))) || groupPut && activeGroup.pull) &&
R
RubaXa 已提交
445
				(evt.rootEl === void 0 || evt.rootEl === this.el)
R
RubaXa 已提交
446
			) {
R
RubaXa 已提交
447
				target = _closest(evt.target, options.draggable, el);
R
RubaXa 已提交
448 449
				dragRect = dragEl.getBoundingClientRect();

R
RubaXa 已提交
450
				if (cloneEl && (cloneEl.state !== isOwner)) {
R
RubaXa 已提交
451 452 453 454 455
					_css(cloneEl, 'display', isOwner ? 'none' : '');
					!isOwner && cloneEl.state && rootEl.insertBefore(cloneEl, dragEl);
					cloneEl.state = isOwner;
				}

R
RubaXa 已提交
456
				if (revert && cloneEl) {
R
RubaXa 已提交
457 458 459
					rootEl.insertBefore(dragEl, cloneEl);
					return;
				}
R
RubaXa 已提交
460

R
RubaXa 已提交
461
				if ((el.children.length === 0) || (el.children[0] === ghostEl) ||
R
RubaXa 已提交
462
					(el === evt.target) && (target = _ghostInBottom(el, evt))
R
RubaXa 已提交
463
				) {
R
RubaXa 已提交
464 465 466 467 468 469
					if (target) {
						if (target.animated) {
							return;
						}
						targetRect = target.getBoundingClientRect();
					}
R
RubaXa 已提交
470

R
RubaXa 已提交
471
					el.appendChild(dragEl);
R
* anim  
RubaXa 已提交
472
					this._animate(dragRect, dragEl);
R
RubaXa 已提交
473
					target && this._animate(targetRect, target);
R
RubaXa 已提交
474
				}
R
RubaXa 已提交
475 476
				else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) {
					if (lastEl !== target) {
R
RubaXa 已提交
477
						lastEl = target;
R
RubaXa 已提交
478
						lastCSS = _css(target);
R
RubaXa 已提交
479 480 481
					}


R
RubaXa 已提交
482 483 484 485 486 487 488 489 490
					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 已提交
491
					;
R
RubaXa 已提交
492

R
RubaXa 已提交
493 494 495
					_silent = true;
					setTimeout(_unsilent, 30);

R
RubaXa 已提交
496 497
					if (floating) {
						after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
R
RubaXa 已提交
498
					} else {
R
RubaXa 已提交
499
						after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
R
RubaXa 已提交
500 501
					}

R
RubaXa 已提交
502
					if (after && !nextSibling) {
R
RubaXa 已提交
503 504 505
						el.appendChild(dragEl);
					} else {
						target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
R
RubaXa 已提交
506
					}
R
RubaXa 已提交
507 508 509
					
					this._animate(dragRect, dragEl);
					this._animate(targetRect, target);
R
RubaXa 已提交
510 511 512 513
				}
			}
		},

514 515 516 517 518 519
		_animate: function (prevRect, target) {
			var ms = this.options.animation;

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

R
RubaXa 已提交
520
				_css(target, 'transition', 'none');
521 522 523 524 525 526 527
				_css(target, 'transform', 'translate3d('
					+ (prevRect.left - currentRect.left) + 'px,'
					+ (prevRect.top - currentRect.top) + 'px,0)'
				);

				target.offsetWidth; // repaint

R
RubaXa 已提交
528
				_css(target, 'transition', 'all ' + ms + 'ms');
529 530
				_css(target, 'transform', 'translate3d(0,0,0)');

R
* anim  
RubaXa 已提交
531 532
				clearTimeout(target.animated);
				target.animated = setTimeout(function () {
533 534 535 536 537 538
					_css(target, 'transition', '');
					target.animated = false;
				}, ms);
			}
		},

539 540 541 542 543 544
		_offUpEvents: function () {
			_off(document, 'mouseup', this._onDrop);
			_off(document, 'touchmove', this._onTouchMove);
			_off(document, 'touchend', this._onDrop);
			_off(document, 'touchcancel', this._onDrop);
		},
R
RubaXa 已提交
545

R
RubaXa 已提交
546
		_onDrop: function (/**Event*/evt) {
R
RubaXa 已提交
547
			clearInterval(this._loopId);
R
RubaXa 已提交
548
			clearInterval(autoScroll.pid);
R
RubaXa 已提交
549 550 551

			// Unbind events
			_off(document, 'drop', this._onDrop);
R
RubaXa 已提交
552
			_off(document, 'dragover', this);
R
RubaXa 已提交
553

R
RubaXa 已提交
554 555 556
			_off(rootEl, 'dragend', this._onDrop);
			_off(rootEl, 'dragstart', this._onDragStart);
			_off(rootEl, 'selectstart', this._onTapStart);
R
RubaXa 已提交
557

558
			this._offUpEvents();
R
RubaXa 已提交
559

R
RubaXa 已提交
560
			if (evt) {
R
RubaXa 已提交
561
				evt.preventDefault();
R
RubaXa 已提交
562
				evt.stopPropagation();
R
RubaXa 已提交
563

R
RubaXa 已提交
564
				ghostEl && ghostEl.parentNode.removeChild(ghostEl);
R
RubaXa 已提交
565

R
RubaXa 已提交
566
				if (dragEl) {
567
					_disableDraggable(dragEl);
R
RubaXa 已提交
568 569
					_toggleClass(dragEl, this.options.ghostClass, false);

R
RubaXa 已提交
570
					if (!rootEl.contains(dragEl)) {
571 572
						_dispatchEvent(dragEl, 'sort');
						_dispatchEvent(rootEl, 'sort');
R
RubaXa 已提交
573 574

						// Add event
575 576 577 578
						_dispatchEvent(dragEl, 'add', dragEl, rootEl);

						// Remove event
						_dispatchEvent(rootEl, 'remove', dragEl);
R
RubaXa 已提交
579
					}
R
RubaXa 已提交
580
					else if (dragEl.nextSibling !== nextEl) {
R
RubaXa 已提交
581
						// Update event
582
						_dispatchEvent(dragEl, 'update');
583
						_dispatchEvent(dragEl, 'sort');
R
RubaXa 已提交
584

R
RubaXa 已提交
585
						cloneEl && cloneEl.parentNode.removeChild(cloneEl);
R
RubaXa 已提交
586
					}
587

588
					_dispatchEvent(rootEl, 'end');
R
RubaXa 已提交
589 590 591 592 593 594 595
				}

				// Set NULL
				rootEl =
				dragEl =
				ghostEl =
				nextEl =
R
RubaXa 已提交
596
				cloneEl =
R
RubaXa 已提交
597 598 599 600 601 602 603 604

				tapEvt =
				touchEvt =

				lastEl =
				lastCSS =

				activeGroup = null;
605 606 607

				// Save sorting
				this.options.store && this.options.store.set(this);
R
RubaXa 已提交
608 609 610 611
			}
		},


R
RubaXa 已提交
612 613 614 615 616 617 618 619 620 621
		handleEvent: function (/**Event*/evt) {
			var type = evt.type;

			if (type === 'dragover') {
				this._onDrag(evt);
				_globalDragOver(evt);
			}
		},


622 623 624 625 626 627 628 629 630
		/**
		 * Serializes the item into an array of string.
		 * @returns {String[]}
		 */
		toArray: function () {
			var order = [],
				el,
				children = this.el.children,
				i = 0,
R
RubaXa 已提交
631
				n = children.length;
632 633 634

			for (; i < n; i++) {
				el = children[i];
R
RubaXa 已提交
635 636 637
				if (_closest(el, this.options.draggable, this.el)) {
					order.push(el.getAttribute('data-id') || _generateId(el));
				}
638 639 640 641 642 643 644 645 646 647 648
			}

			return order;
		},


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

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

R
RubaXa 已提交
654
				if (_closest(el, this.options.draggable, rootEl)) {
R
RubaXa 已提交
655 656 657
					items[id] = el;
				}
			}, this);
658 659 660 661


			order.forEach(function (id) {
				if (items[id]) {
R
RubaXa 已提交
662 663
					rootEl.removeChild(items[id]);
					rootEl.appendChild(items[id]);
664 665 666 667 668
				}
			});
		},


669 670 671 672 673 674 675 676 677 678 679
		/**
		 * 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);
		},


680 681 682 683
		/**
		 * Destroy
		 */
		destroy: function () {
R
RubaXa 已提交
684 685
			var el = this.el, options = this.options;

686 687 688 689
			_customEvents.forEach(function (name) {
				_off(el, name.substr(2).toLowerCase(), options[name]);
			});

R
RubaXa 已提交
690 691
			_off(el, 'mousedown', this._onTapStart);
			_off(el, 'touchstart', this._onTapStart);
N
Nicolas 已提交
692
			_off(el, 'selectstart', this._onTapStart);
R
RubaXa 已提交
693 694 695 696

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

697
			//remove draggable attributes
R
RubaXa 已提交
698
			Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
699 700 701
				el.removeAttribute('draggable');
			});

R
RubaXa 已提交
702 703 704 705 706 707 708 709
			touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);

			this._onDrop();

			this.el = null;
		}
	};

710

R
RubaXa 已提交
711
	function _bind(ctx, fn) {
R
RubaXa 已提交
712
		var args = slice.call(arguments, 2);
R
RubaXa 已提交
713
		return	fn.bind ? fn.bind.apply(fn, [ctx].concat(args)) : function () {
R
RubaXa 已提交
714 715 716 717 718
			return fn.apply(ctx, args.concat(slice.call(arguments)));
		};
	}


R
RubaXa 已提交
719 720
	function _closest(el, selector, ctx) {
		if (selector === '*') {
R
RubaXa 已提交
721 722
			return el;
		}
R
RubaXa 已提交
723
		else if (el) {
R
RubaXa 已提交
724 725 726
			ctx = ctx || document;
			selector = selector.split('.');

R
RubaXa 已提交
727 728
			var tag = selector.shift().toUpperCase(),
				re = new RegExp('\\s(' + selector.join('|') + ')\\s', 'g');
R
RubaXa 已提交
729 730

			do {
R
RubaXa 已提交
731 732 733 734 735
				if (
					(tag === '' || el.nodeName == tag) &&
					(!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
				) {
					return el;
R
RubaXa 已提交
736 737
				}
			}
R
RubaXa 已提交
738
			while (el !== ctx && (el = el.parentNode));
R
RubaXa 已提交
739 740
		}

R
RubaXa 已提交
741
		return null;
R
RubaXa 已提交
742 743 744
	}


R
RubaXa 已提交
745
	function _globalDragOver(evt) {
R
RubaXa 已提交
746 747 748 749 750
		evt.dataTransfer.dropEffect = 'move';
		evt.preventDefault();
	}


R
RubaXa 已提交
751
	function _on(el, event, fn) {
R
RubaXa 已提交
752 753 754 755
		el.addEventListener(event, fn, false);
	}


R
RubaXa 已提交
756
	function _off(el, event, fn) {
R
RubaXa 已提交
757 758 759 760
		el.removeEventListener(event, fn, false);
	}


R
RubaXa 已提交
761 762 763
	function _toggleClass(el, name, state) {
		if (el) {
			if (el.classList) {
R
RubaXa 已提交
764 765 766
				el.classList[state ? 'add' : 'remove'](name);
			}
			else {
R
RubaXa 已提交
767 768
				var className = (' ' + el.className + ' ').replace(/\s+/g, ' ').replace(' ' + name + ' ', '');
				el.className = className + (state ? ' ' + name : '');
R
RubaXa 已提交
769 770 771 772 773
			}
		}
	}


R
RubaXa 已提交
774
	function _css(el, prop, val) {
R
RubaXa 已提交
775 776
		var style = el && el.style;

R
RubaXa 已提交
777 778 779
		if (style) {
			if (val === void 0) {
				if (document.defaultView && document.defaultView.getComputedStyle) {
R
RubaXa 已提交
780 781
					val = document.defaultView.getComputedStyle(el, '');
				}
R
RubaXa 已提交
782 783
				else if (el.currentStyle) {
					val = el.currentStyle;
R
RubaXa 已提交
784
				}
R
RubaXa 已提交
785 786 787 788 789 790 791 792 793

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

				style[prop] = val + (typeof val === 'string' ? '' : 'px');
R
RubaXa 已提交
794 795 796 797 798
			}
		}
	}


R
RubaXa 已提交
799 800
	function _find(ctx, tagName, iterator) {
		if (ctx) {
R
RubaXa 已提交
801
			var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
R
RubaXa 已提交
802

R
RubaXa 已提交
803 804
			if (iterator) {
				for (; i < n; i++) {
R
RubaXa 已提交
805 806 807
					iterator(list[i], i);
				}
			}
R
RubaXa 已提交
808

R
RubaXa 已提交
809
			return list;
R
RubaXa 已提交
810
		}
R
RubaXa 已提交
811 812

		return [];
R
RubaXa 已提交
813 814 815
	}


R
RubaXa 已提交
816
	function _disableDraggable(el) {
R
RubaXa 已提交
817
		el.draggable = false;
R
RubaXa 已提交
818 819 820
	}


R
RubaXa 已提交
821
	function _unsilent() {
R
RubaXa 已提交
822 823 824 825
		_silent = false;
	}


R
RubaXa 已提交
826
	/** @returns {HTMLElement|false} */
R
RubaXa 已提交
827
	function _ghostInBottom(el, evt) {
R
RubaXa 已提交
828 829
		var lastEl = el.lastElementChild, rect = lastEl.getBoundingClientRect();
		return (evt.clientY - (rect.top + rect.height) > 5) && lastEl; // min delta
R
RubaXa 已提交
830 831 832
	}


833 834 835 836 837 838 839
	/**
	 * Generate id
	 * @param   {HTMLElement} el
	 * @returns {String}
	 * @private
	 */
	function _generateId(el) {
R
RubaXa 已提交
840
		var str = el.tagName + el.className + el.src + el.href + el.textContent,
841
			i = str.length,
R
RubaXa 已提交
842
			sum = 0;
843

844 845 846
		while (i--) {
			sum += str.charCodeAt(i);
		}
847

848 849 850
		return sum.toString(36);
	}

R
RubaXa 已提交
851

R
RubaXa 已提交
852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
	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 已提交
874 875 876 877 878 879 880
	// Export utils
	Sortable.utils = {
		on: _on,
		off: _off,
		css: _css,
		find: _find,
		bind: _bind,
R
RubaXa 已提交
881
		throttle: _throttle,
R
RubaXa 已提交
882
		closest: _closest,
883 884
		toggleClass: _toggleClass,
		dispatchEvent: _dispatchEvent
R
RubaXa 已提交
885 886 887
	};


888
	Sortable.version = '0.6.0';
R
RubaXa 已提交
889

890

891 892 893 894 895 896
	/**
	 * Create sortable instance
	 * @param {HTMLElement}  el
	 * @param {Object}      [options]
	 */
	Sortable.create = function (el, options) {
R
RubaXa 已提交
897
		return new Sortable(el, options);
898
	};
R
RubaXa 已提交
899 900

	// Export
901
	return Sortable;
R
RubaXa 已提交
902
});