Sortable.js 22.3 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 38 39
		oldIndex,
		newIndex,

R
RubaXa 已提交
40
		activeGroup,
R
RubaXa 已提交
41
		autoScroll = {},
R
RubaXa 已提交
42

R
RubaXa 已提交
43 44
		tapEvt,
		touchEvt,
R
RubaXa 已提交
45

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

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

R
RubaXa 已提交
53
		_silent = false,
R
RubaXa 已提交
54

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

58
			evt.initEvent(name, true, true);
R
RubaXa 已提交
59

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

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

67
			rootEl.dispatchEvent(evt);
R
RubaXa 已提交
68
		},
69

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

R
RubaXa 已提交
72
		noop = function () {},
R
RubaXa 已提交
73 74

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

R
RubaXa 已提交
77
		touchDragOverListeners = []
R
RubaXa 已提交
78 79 80
	;


81

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


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

R
RubaXa 已提交
114

115 116
		// Set default options
		for (var name in defaults) {
R
RubaXa 已提交
117
			!(name in options) && (options[name] = defaults[name]);
118
		}
R
RubaXa 已提交
119

120

R
RubaXa 已提交
121 122
		var group = options.group;

R
RubaXa 已提交
123 124
		if (!group || typeof group != 'object') {
			group = options.group = { name: group };
R
RubaXa 已提交
125 126
		}

R
RubaXa 已提交
127

R
RubaXa 已提交
128
		['pull', 'put'].forEach(function (key) {
R
RubaXa 已提交
129 130
			if (!(key in group)) {
				group[key] = true;
R
RubaXa 已提交
131 132 133 134
			}
		});


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


R
* JSDoc  
RubaXa 已提交
142
		// Export group name
R
RubaXa 已提交
143
		el[expando] = group.name + ' ' + (group.put.join ? group.put.join(' ') : '');
R
RubaXa 已提交
144 145


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


		// Bind events
		_on(el, 'mousedown', this._onTapStart);
		_on(el, 'touchstart', this._onTapStart);
R
RubaXa 已提交
157
		supportIEdnd && _on(el, 'selectstart', this._onTapStart);
R
RubaXa 已提交
158 159 160 161 162

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

		touchDragOverListeners.push(this._onDragOver);
163 164 165

		// Restore sorting
		options.store && this.sort(options.store.get(this));
R
RubaXa 已提交
166 167 168
	}


169
	Sortable.prototype = /** @lends Sortable.prototype */ {
R
RubaXa 已提交
170 171 172
		constructor: Sortable,


R
RubaXa 已提交
173 174
		_dragStarted: function () {
			// Apply effect
R
RubaXa 已提交
175
			_toggleClass(dragEl, this.options.ghostClass, true);
R
RubaXa 已提交
176 177 178 179

			Sortable.active = this;

			// Drag start event
R
RubaXa 已提交
180
			_dispatchEvent(rootEl, 'start', dragEl, rootEl, oldIndex);
R
RubaXa 已提交
181 182 183
		},


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

R
RubaXa 已提交
193
			if (type === 'mousedown' && evt.button !== 0 || options.disabled) {
R
RubaXa 已提交
194
				return; // only left button or enabled
R
RubaXa 已提交
195 196
			}

197 198 199 200 201 202 203
			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
R
RubaXa 已提交
204
			oldIndex = _index(target);
205

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

					if (criteria) {
R
RubaXa 已提交
219
						_dispatchEvent(criteria, 'filter', target, el, oldIndex);
R
RubaXa 已提交
220 221
						return true;
					}
222 223
				});

R
RubaXa 已提交
224 225
				if (filter) {
					evt.preventDefault();
226 227 228 229
					return; // cancel dnd
				}
			}

R
RubaXa 已提交
230
			// Prepare `dragstart`
R
RubaXa 已提交
231
			if (target && !dragEl && (target.parentNode === el)) {
R
RubaXa 已提交
232 233 234
				// IE 9 Support
				(type === 'selectstart') && target.dragDrop();

R
RubaXa 已提交
235
				tapEvt = evt;
236 237 238 239 240 241 242

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

				dragEl.draggable = true;
R
RubaXa 已提交
243 244

				// Disable "draggable"
245
				options.ignore.split(',').forEach(function (criteria) {
Z
ziflex 已提交
246 247
					_find(target, criteria.trim(), _disableDraggable);
				});
R
RubaXa 已提交
248

R
RubaXa 已提交
249
				if (touch) {
R
RubaXa 已提交
250 251
					// Touch device support
					tapEvt = {
R
RubaXa 已提交
252 253 254
						target: target,
						clientX: touch.clientX,
						clientY: touch.clientY
R
RubaXa 已提交
255
					};
256

R
RubaXa 已提交
257 258 259
					this._onDragStart(tapEvt, true);
					evt.preventDefault();
				}
R
RubaXa 已提交
260

261 262 263
				_on(document, 'mouseup', this._onDrop);
				_on(document, 'touchend', this._onDrop);
				_on(document, 'touchcancel', this._onDrop);
R
RubaXa 已提交
264

R
RubaXa 已提交
265
				_on(dragEl, 'dragend', this);
R
RubaXa 已提交
266 267
				_on(rootEl, 'dragstart', this._onDragStart);

R
RubaXa 已提交
268
				_on(document, 'dragover', this);
R
RubaXa 已提交
269 270 271


				try {
R
RubaXa 已提交
272
					if (document.selection) {
R
RubaXa 已提交
273 274
						document.selection.empty();
					} else {
R
RubaXa 已提交
275
						window.getSelection().removeAllRanges();
R
RubaXa 已提交
276
					}
R
RubaXa 已提交
277 278
				} catch (err) {
				}
279 280


R
RubaXa 已提交
281 282 283 284 285
				if (activeGroup.pull == 'clone') {
					cloneEl = dragEl.cloneNode(true);
					_css(cloneEl, 'display', 'none');
					rootEl.insertBefore(cloneEl, dragEl);
				}
R
RubaXa 已提交
286 287 288
			}
		},

R
RubaXa 已提交
289 290
		_emulateDragOver: function () {
			if (touchEvt) {
R
RubaXa 已提交
291 292
				_css(ghostEl, 'display', 'none');

R
RubaXa 已提交
293
				var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY),
R
RubaXa 已提交
294
					parent = target,
R
RubaXa 已提交
295 296
					groupName = this.options.group.name,
					i = touchDragOverListeners.length;
R
RubaXa 已提交
297

R
RubaXa 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
				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 已提交
314
					}
R
RubaXa 已提交
315 316
					/* jshint boss:true */
					while (parent = parent.parentNode);
R
RubaXa 已提交
317 318 319 320 321 322 323
				}

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


R
RubaXa 已提交
324 325 326 327 328 329
		_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 已提交
330 331

				touchEvt = touch;
R
RubaXa 已提交
332 333 334 335 336 337

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

R
RubaXa 已提交
338
				this._onDrag(touch);
M
Marius Petcu 已提交
339
				evt.preventDefault();
R
RubaXa 已提交
340 341 342 343
			}
		},


R
RubaXa 已提交
344
		_onDragStart: function (/**Event*/evt, /**boolean*/isTouch) {
R
RubaXa 已提交
345 346
			var dataTransfer = evt.dataTransfer,
				options = this.options;
R
RubaXa 已提交
347

348
			this._offUpEvents();
R
RubaXa 已提交
349

R
RubaXa 已提交
350 351 352 353
			if (isTouch) {
				var rect = dragEl.getBoundingClientRect(),
					css = _css(dragEl),
					ghostRect;
R
RubaXa 已提交
354

355
				ghostEl = dragEl.cloneNode(true);
R
RubaXa 已提交
356 357 358

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

R
RubaXa 已提交
365 366 367 368
				rootEl.appendChild(ghostEl);

				// Fixing dimensions.
				ghostRect = ghostEl.getBoundingClientRect();
R
RubaXa 已提交
369 370
				_css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
				_css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
R
RubaXa 已提交
371 372 373 374

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

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

R
RubaXa 已提交
385
				_on(document, 'drop', this);
R
RubaXa 已提交
386 387
			}

R
RubaXa 已提交
388 389 390
			scrollEl = options.scroll;

			if (scrollEl === true) {
R
RubaXa 已提交
391
				scrollEl = rootEl;
R
RubaXa 已提交
392 393 394 395 396 397 398 399 400 401

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

			setTimeout(this._dragStarted, 0);
R
RubaXa 已提交
404 405
		},

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

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

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

R
RubaXa 已提交
421 422
					vx = (winWidth - x <= sens) - (x <= sens),
					vy = (winHeight - y <= sens) - (y <= sens)
R
RubaXa 已提交
423 424 425
				;

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

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

R
RubaXa 已提交
440 441 442 443 444 445 446 447 448 449 450 451
					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 已提交
452 453 454 455
				}
			}
		}, 30),

R
RubaXa 已提交
456

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

R
RubaXa 已提交
468 469
			if (evt.preventDefault !== void 0) {
				evt.preventDefault();
470
				!options.dragoverBubble && evt.stopPropagation();
R
RubaXa 已提交
471
			}
R
RubaXa 已提交
472

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


487
				if (revert) {
R
RubaXa 已提交
488 489
					_cloneHide(true);

490 491 492 493 494 495 496
					if (cloneEl || nextEl) {
						rootEl.insertBefore(dragEl, cloneEl || nextEl);
					}
					else if (!canSort) {
						rootEl.appendChild(dragEl);
					}

R
RubaXa 已提交
497 498
					return;
				}
R
RubaXa 已提交
499

R
RubaXa 已提交
500

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

R
RubaXa 已提交
511 512
					_cloneHide(isOwner);

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


R
RubaXa 已提交
524 525 526 527 528 529 530 531 532
					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 已提交
533
					;
R
RubaXa 已提交
534

R
RubaXa 已提交
535 536 537
					_silent = true;
					setTimeout(_unsilent, 30);

R
RubaXa 已提交
538 539
					_cloneHide(isOwner);

R
RubaXa 已提交
540 541
					if (floating) {
						after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
R
RubaXa 已提交
542
					} else {
R
RubaXa 已提交
543
						after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
R
RubaXa 已提交
544 545
					}

R
RubaXa 已提交
546
					if (after && !nextSibling) {
R
RubaXa 已提交
547 548 549
						el.appendChild(dragEl);
					} else {
						target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
R
RubaXa 已提交
550
					}
R
RubaXa 已提交
551

R
RubaXa 已提交
552 553
					this._animate(dragRect, dragEl);
					this._animate(targetRect, target);
R
RubaXa 已提交
554 555 556 557
				}
			}
		},

558 559 560 561 562 563
		_animate: function (prevRect, target) {
			var ms = this.options.animation;

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

R
RubaXa 已提交
564
				_css(target, 'transition', 'none');
565 566 567 568 569 570 571
				_css(target, 'transform', 'translate3d('
					+ (prevRect.left - currentRect.left) + 'px,'
					+ (prevRect.top - currentRect.top) + 'px,0)'
				);

				target.offsetWidth; // repaint

R
RubaXa 已提交
572
				_css(target, 'transition', 'all ' + ms + 'ms');
573 574
				_css(target, 'transform', 'translate3d(0,0,0)');

R
* anim  
RubaXa 已提交
575 576
				clearTimeout(target.animated);
				target.animated = setTimeout(function () {
577 578 579 580 581 582
					_css(target, 'transition', '');
					target.animated = false;
				}, ms);
			}
		},

583 584 585 586 587 588
		_offUpEvents: function () {
			_off(document, 'mouseup', this._onDrop);
			_off(document, 'touchmove', this._onTouchMove);
			_off(document, 'touchend', this._onDrop);
			_off(document, 'touchcancel', this._onDrop);
		},
R
RubaXa 已提交
589

R
RubaXa 已提交
590
		_onDrop: function (/**Event*/evt) {
591 592
			var el = this.el,
				options = this.options;
R
RubaXa 已提交
593

R
RubaXa 已提交
594
			clearInterval(this._loopId);
R
RubaXa 已提交
595
			clearInterval(autoScroll.pid);
R
RubaXa 已提交
596 597

			// Unbind events
R
RubaXa 已提交
598
			_off(document, 'drop', this);
R
RubaXa 已提交
599
			_off(document, 'dragover', this);
R
RubaXa 已提交
600

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

603
			this._offUpEvents();
R
RubaXa 已提交
604

R
RubaXa 已提交
605
			if (evt) {
R
RubaXa 已提交
606
				evt.preventDefault();
607
				!options.dropBubble && evt.stopPropagation();
R
RubaXa 已提交
608

R
RubaXa 已提交
609
				ghostEl && ghostEl.parentNode.removeChild(ghostEl);
R
RubaXa 已提交
610

R
RubaXa 已提交
611
				if (dragEl) {
R
RubaXa 已提交
612 613
					_off(dragEl, 'dragend', this);

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

617
					if (rootEl !== dragEl.parentNode) {
R
RubaXa 已提交
618 619
						newIndex = _index(dragEl);

620
						// drag from one list and drop into another
R
RubaXa 已提交
621 622
						_dispatchEvent(dragEl.parentNode, 'sort', dragEl, rootEl, oldIndex, newIndex);
						_dispatchEvent(rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
R
RubaXa 已提交
623 624

						// Add event
R
RubaXa 已提交
625
						_dispatchEvent(dragEl, 'add', dragEl, rootEl, oldIndex, newIndex);
626 627

						// Remove event
R
RubaXa 已提交
628
						_dispatchEvent(rootEl, 'remove', dragEl, rootEl, oldIndex, newIndex);
R
RubaXa 已提交
629
					}
R
RubaXa 已提交
630
					else if (dragEl.nextSibling !== nextEl) {
R
RubaXa 已提交
631
						// (1) Remove clone
R
RubaXa 已提交
632
						cloneEl && cloneEl.parentNode.removeChild(cloneEl);
R
RubaXa 已提交
633 634 635 636 637 638 639

 						// (2) Get the index of the dragged element within its parent
						newIndex = _index(dragEl);

						// drag & drop within the same list
						_dispatchEvent(rootEl, 'update', dragEl, rootEl, oldIndex, newIndex);
						_dispatchEvent(rootEl, 'sort', dragEl, rootEl, oldIndex, newIndex);
R
RubaXa 已提交
640
					}
641

R
RubaXa 已提交
642
					// Drag end event
R
RubaXa 已提交
643
					Sortable.active && _dispatchEvent(rootEl, 'end', dragEl, rootEl, oldIndex, newIndex);
R
RubaXa 已提交
644 645 646 647 648 649 650
				}

				// Set NULL
				rootEl =
				dragEl =
				ghostEl =
				nextEl =
R
RubaXa 已提交
651
				cloneEl =
R
RubaXa 已提交
652 653 654 655 656 657 658

				tapEvt =
				touchEvt =

				lastEl =
				lastCSS =

R
RubaXa 已提交
659 660
				activeGroup =
				Sortable.active = null;
661 662

				// Save sorting
R
RubaXa 已提交
663
				this.save();
R
RubaXa 已提交
664 665 666 667
			}
		},


R
RubaXa 已提交
668 669 670 671 672 673 674
		handleEvent: function (/**Event*/evt) {
			var type = evt.type;

			if (type === 'dragover') {
				this._onDrag(evt);
				_globalDragOver(evt);
			}
R
RubaXa 已提交
675
			else if (type === 'drop' || type === 'dragend') {
R
RubaXa 已提交
676 677
				this._onDrop(evt);
			}
R
RubaXa 已提交
678 679 680
		},


681 682 683 684 685 686 687 688 689
		/**
		 * Serializes the item into an array of string.
		 * @returns {String[]}
		 */
		toArray: function () {
			var order = [],
				el,
				children = this.el.children,
				i = 0,
R
RubaXa 已提交
690
				n = children.length;
691 692 693

			for (; i < n; i++) {
				el = children[i];
R
RubaXa 已提交
694 695 696
				if (_closest(el, this.options.draggable, this.el)) {
					order.push(el.getAttribute('data-id') || _generateId(el));
				}
697 698 699 700 701 702 703 704 705 706 707
			}

			return order;
		},


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

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

R
RubaXa 已提交
713
				if (_closest(el, this.options.draggable, rootEl)) {
R
RubaXa 已提交
714 715 716
					items[id] = el;
				}
			}, this);
717 718 719

			order.forEach(function (id) {
				if (items[id]) {
R
RubaXa 已提交
720 721
					rootEl.removeChild(items[id]);
					rootEl.appendChild(items[id]);
722 723 724 725 726
				}
			});
		},


R
RubaXa 已提交
727 728 729 730 731 732 733 734 735
		/**
		 * Save the current sorting
		 */
		save: function () {
			var store = this.options.store;
			store && store.set(this);
		},


736 737 738 739 740 741 742 743 744 745 746
		/**
		 * 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);
		},


747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
		/**
		 * 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;
			}
		},


764 765 766 767
		/**
		 * Destroy
		 */
		destroy: function () {
R
RubaXa 已提交
768 769
			var el = this.el, options = this.options;

770 771 772 773
			_customEvents.forEach(function (name) {
				_off(el, name.substr(2).toLowerCase(), options[name]);
			});

R
RubaXa 已提交
774 775
			_off(el, 'mousedown', this._onTapStart);
			_off(el, 'touchstart', this._onTapStart);
N
Nicolas 已提交
776
			_off(el, 'selectstart', this._onTapStart);
R
RubaXa 已提交
777 778 779 780

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

781
			//remove draggable attributes
R
RubaXa 已提交
782
			Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
783 784 785
				el.removeAttribute('draggable');
			});

R
RubaXa 已提交
786 787 788 789 790 791 792 793
			touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);

			this._onDrop();

			this.el = null;
		}
	};

794

R
RubaXa 已提交
795 796 797 798 799 800 801 802 803
	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 已提交
804
	function _bind(ctx, fn) {
R
RubaXa 已提交
805
		var args = slice.call(arguments, 2);
R
RubaXa 已提交
806
		return	fn.bind ? fn.bind.apply(fn, [ctx].concat(args)) : function () {
R
RubaXa 已提交
807 808 809 810 811
			return fn.apply(ctx, args.concat(slice.call(arguments)));
		};
	}


R
RubaXa 已提交
812
	function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) {
R
RubaXa 已提交
813
		if (el) {
R
RubaXa 已提交
814 815 816
			ctx = ctx || document;
			selector = selector.split('.');

R
RubaXa 已提交
817 818
			var tag = selector.shift().toUpperCase(),
				re = new RegExp('\\s(' + selector.join('|') + ')\\s', 'g');
R
RubaXa 已提交
819 820

			do {
R
RubaXa 已提交
821
				if (
R
RubaXa 已提交
822 823 824 825
					(tag === '>*' && el.parentNode === ctx) || (
						(tag === '' || el.nodeName == tag) &&
						(!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
					)
R
RubaXa 已提交
826 827
				) {
					return el;
R
RubaXa 已提交
828 829
				}
			}
R
RubaXa 已提交
830
			while (el !== ctx && (el = el.parentNode));
R
RubaXa 已提交
831 832
		}

R
RubaXa 已提交
833
		return null;
R
RubaXa 已提交
834 835 836
	}


837
	function _globalDragOver(/**Event*/evt) {
R
RubaXa 已提交
838 839 840 841 842
		evt.dataTransfer.dropEffect = 'move';
		evt.preventDefault();
	}


R
RubaXa 已提交
843
	function _on(el, event, fn) {
R
RubaXa 已提交
844 845 846 847
		el.addEventListener(event, fn, false);
	}


R
RubaXa 已提交
848
	function _off(el, event, fn) {
R
RubaXa 已提交
849 850 851 852
		el.removeEventListener(event, fn, false);
	}


R
RubaXa 已提交
853 854 855
	function _toggleClass(el, name, state) {
		if (el) {
			if (el.classList) {
R
RubaXa 已提交
856 857 858
				el.classList[state ? 'add' : 'remove'](name);
			}
			else {
R
RubaXa 已提交
859 860
				var className = (' ' + el.className + ' ').replace(/\s+/g, ' ').replace(' ' + name + ' ', '');
				el.className = className + (state ? ' ' + name : '');
R
RubaXa 已提交
861 862 863 864 865
			}
		}
	}


R
RubaXa 已提交
866
	function _css(el, prop, val) {
R
RubaXa 已提交
867 868
		var style = el && el.style;

R
RubaXa 已提交
869 870 871
		if (style) {
			if (val === void 0) {
				if (document.defaultView && document.defaultView.getComputedStyle) {
R
RubaXa 已提交
872 873
					val = document.defaultView.getComputedStyle(el, '');
				}
R
RubaXa 已提交
874 875
				else if (el.currentStyle) {
					val = el.currentStyle;
R
RubaXa 已提交
876
				}
R
RubaXa 已提交
877 878 879 880 881 882 883 884 885

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

				style[prop] = val + (typeof val === 'string' ? '' : 'px');
R
RubaXa 已提交
886 887 888 889 890
			}
		}
	}


R
RubaXa 已提交
891 892
	function _find(ctx, tagName, iterator) {
		if (ctx) {
R
RubaXa 已提交
893
			var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
R
RubaXa 已提交
894

R
RubaXa 已提交
895 896
			if (iterator) {
				for (; i < n; i++) {
R
RubaXa 已提交
897 898 899
					iterator(list[i], i);
				}
			}
R
RubaXa 已提交
900

R
RubaXa 已提交
901
			return list;
R
RubaXa 已提交
902
		}
R
RubaXa 已提交
903 904

		return [];
R
RubaXa 已提交
905 906 907
	}


R
RubaXa 已提交
908
	function _disableDraggable(el) {
R
RubaXa 已提交
909
		el.draggable = false;
R
RubaXa 已提交
910 911 912
	}


R
RubaXa 已提交
913
	function _unsilent() {
R
RubaXa 已提交
914 915 916 917
		_silent = false;
	}


R
RubaXa 已提交
918
	/** @returns {HTMLElement|false} */
R
RubaXa 已提交
919
	function _ghostInBottom(el, evt) {
R
RubaXa 已提交
920 921
		var lastEl = el.lastElementChild, rect = lastEl.getBoundingClientRect();
		return (evt.clientY - (rect.top + rect.height) > 5) && lastEl; // min delta
R
RubaXa 已提交
922 923 924
	}


925 926 927 928 929 930 931
	/**
	 * Generate id
	 * @param   {HTMLElement} el
	 * @returns {String}
	 * @private
	 */
	function _generateId(el) {
R
RubaXa 已提交
932
		var str = el.tagName + el.className + el.src + el.href + el.textContent,
933
			i = str.length,
R
RubaXa 已提交
934
			sum = 0;
935

936 937 938
		while (i--) {
			sum += str.charCodeAt(i);
		}
939

940 941 942
		return sum.toString(36);
	}

943 944 945
	/**
	 * Returns the index of an element within its parent
	 * @param el
946 947
	 * @returns {number}
	 * @private
948 949 950
	 */
	function _index(/**HTMLElement*/el) {
		var index = 0;
G
Greg Hoyl 已提交
951
		while (el && (el = el.previousElementSibling) && (el.nodeName !== 'TEMPLATE')) {
952 953 954 955
			index++;
		}
		return index;
	}
R
RubaXa 已提交
956

R
RubaXa 已提交
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
	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 已提交
979 980 981 982 983 984 985
	// Export utils
	Sortable.utils = {
		on: _on,
		off: _off,
		css: _css,
		find: _find,
		bind: _bind,
R
RubaXa 已提交
986 987 988
		is: function (el, selector) {
			return !!_closest(el, selector, el);
		},
R
RubaXa 已提交
989
		throttle: _throttle,
R
RubaXa 已提交
990
		closest: _closest,
991
		toggleClass: _toggleClass,
992 993
		dispatchEvent: _dispatchEvent,
		index: _index
R
RubaXa 已提交
994 995 996
	};


R
RubaXa 已提交
997
	Sortable.version = '1.0.0';
998

R
RubaXa 已提交
999

1000 1001 1002 1003 1004 1005
	/**
	 * Create sortable instance
	 * @param {HTMLElement}  el
	 * @param {Object}      [options]
	 */
	Sortable.create = function (el, options) {
R
RubaXa 已提交
1006
		return new Sortable(el, options);
1007
	};
R
RubaXa 已提交
1008 1009

	// Export
1010
	return Sortable;
R
RubaXa 已提交
1011
});