Sortable.js 21.6 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 61 62

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

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

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

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

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

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


78

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


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

R
RubaXa 已提交
122

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


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


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


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


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

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

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

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


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


R
RubaXa 已提交
168
		_applyEffects: function () {
R
RubaXa 已提交
169 170 171 172
			_toggleClass(dragEl, this.options.ghostClass, true);
		},


R
RubaXa 已提交
173 174 175
		_onTapStart: function (/**Event|TouchEvent*/evt) {
			var touch = evt.touches && evt.touches[0],
				target = (touch || evt).target,
176
				originalTarget = target,
R
RubaXa 已提交
177 178 179
				options =  this.options,
				el = this.el,
				filter = options.filter;
R
RubaXa 已提交
180

R
RubaXa 已提交
181 182
			if (evt.type === 'mousedown' && evt.button !== 0 || options.disabled) {
				return; // only left button or enabled
R
RubaXa 已提交
183 184
			}

185 186 187 188 189 190 191 192 193
			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);

194
			// Check filter
R
RubaXa 已提交
195
			if (typeof filter === 'function') {
R
RubaXa 已提交
196 197
				if (filter.call(this, evt, target, this)) {
					_dispatchEvent(originalTarget, 'filter', target, el, startIndex);
R
RubaXa 已提交
198 199
					return; // cancel dnd
				}
200
			}
R
RubaXa 已提交
201
			else if (filter) {
R
RubaXa 已提交
202 203 204 205 206 207 208
				filter = filter.split(',').some(function (criteria) {
					criteria = _closest(originalTarget, criteria.trim(), el);

					if (criteria) {
						_dispatchEvent(criteria, 'filter', target, el, startIndex);
						return true;
					}
209 210 211 212 213 214 215
				});

				if (filter.length) {
					return; // cancel dnd
				}
			}

R
RubaXa 已提交
216
			// IE 9 Support
R
RubaXa 已提交
217 218
			if (target && evt.type == 'selectstart') {
				if (target.tagName != 'A' && target.tagName != 'IMG') {
219 220 221
					target.dragDrop();
				}
			}
N
Nicolas 已提交
222

R
RubaXa 已提交
223
			if (target && !dragEl && (target.parentNode === el)) {
R
RubaXa 已提交
224
				tapEvt = evt;
225 226 227 228 229 230 231

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

				dragEl.draggable = true;
R
RubaXa 已提交
232 233

				// Disable "draggable"
234
				options.ignore.split(',').forEach(function (criteria) {
Z
ziflex 已提交
235 236
					_find(target, criteria.trim(), _disableDraggable);
				});
R
RubaXa 已提交
237

R
RubaXa 已提交
238
				if (touch) {
R
RubaXa 已提交
239 240
					// Touch device support
					tapEvt = {
R
RubaXa 已提交
241 242 243
						target: target,
						clientX: touch.clientX,
						clientY: touch.clientY
R
RubaXa 已提交
244
					};
245

R
RubaXa 已提交
246 247 248
					this._onDragStart(tapEvt, true);
					evt.preventDefault();
				}
R
RubaXa 已提交
249

250 251 252
				_on(document, 'mouseup', this._onDrop);
				_on(document, 'touchend', this._onDrop);
				_on(document, 'touchcancel', this._onDrop);
R
RubaXa 已提交
253

R
RubaXa 已提交
254
				_on(dragEl, 'dragend', this);
R
RubaXa 已提交
255 256
				_on(rootEl, 'dragstart', this._onDragStart);

R
RubaXa 已提交
257
				_on(document, 'dragover', this);
R
RubaXa 已提交
258 259 260


				try {
R
RubaXa 已提交
261
					if (document.selection) {
R
RubaXa 已提交
262 263
						document.selection.empty();
					} else {
R
RubaXa 已提交
264
						window.getSelection().removeAllRanges();
R
RubaXa 已提交
265
					}
R
RubaXa 已提交
266 267
				} catch (err) {
				}
268 269


R
RubaXa 已提交
270 271
				// Drag start event
				_dispatchEvent(rootEl, 'start', dragEl, rootEl, startIndex);
R
RubaXa 已提交
272 273


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

				Sortable.active = this;
R
RubaXa 已提交
281 282 283
			}
		},

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

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

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

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


R
RubaXa 已提交
309 310 311 312 313 314
		_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 已提交
315 316

				touchEvt = touch;
R
RubaXa 已提交
317 318 319 320 321 322

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

R
RubaXa 已提交
323
				this._onDrag(touch);
M
Marius Petcu 已提交
324
				evt.preventDefault();
R
RubaXa 已提交
325 326 327 328
			}
		},


R
RubaXa 已提交
329
		_onDragStart: function (/**Event*/evt, /**boolean*/isTouch) {
R
RubaXa 已提交
330 331
			var dataTransfer = evt.dataTransfer,
				options = this.options;
R
RubaXa 已提交
332

333
			this._offUpEvents();
R
RubaXa 已提交
334

R
RubaXa 已提交
335 336 337 338
			if (isTouch) {
				var rect = dragEl.getBoundingClientRect(),
					css = _css(dragEl),
					ghostRect;
R
RubaXa 已提交
339

340
				ghostEl = dragEl.cloneNode(true);
R
RubaXa 已提交
341 342 343

				_css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10));
				_css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10));
R
RubaXa 已提交
344 345
				_css(ghostEl, 'width', rect.width);
				_css(ghostEl, 'height', rect.height);
R
RubaXa 已提交
346 347 348 349
				_css(ghostEl, 'opacity', '0.8');
				_css(ghostEl, 'position', 'fixed');
				_css(ghostEl, 'zIndex', '100000');

R
RubaXa 已提交
350 351 352 353
				rootEl.appendChild(ghostEl);

				// Fixing dimensions.
				ghostRect = ghostEl.getBoundingClientRect();
R
RubaXa 已提交
354 355
				_css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
				_css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
R
RubaXa 已提交
356 357 358 359

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

R
RubaXa 已提交
362
				this._loopId = setInterval(this._emulateDragOver, 150);
R
RubaXa 已提交
363 364 365
			}
			else {
				dataTransfer.effectAllowed = 'move';
R
RubaXa 已提交
366
				options.setData && options.setData.call(this, dataTransfer, dragEl);
R
RubaXa 已提交
367

R
RubaXa 已提交
368
				_on(document, 'drop', this);
R
RubaXa 已提交
369 370
			}

R
RubaXa 已提交
371 372 373 374 375
			setTimeout(this._applyEffects, 0);

			scrollEl = options.scroll;

			if (scrollEl === true) {
R
RubaXa 已提交
376
				scrollEl = rootEl;
R
RubaXa 已提交
377 378 379 380 381 382 383 384 385 386

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

R
RubaXa 已提交
389
		_onDrag: _throttle(function (/**Event*/evt) {
R
RubaXa 已提交
390
			// Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=505521
R
RubaXa 已提交
391
			if (rootEl && this.options.scroll) {
R
RubaXa 已提交
392 393 394
				var el,
					rect,
					options = this.options,
R
RubaXa 已提交
395 396 397 398 399 400 401 402 403
					sens = options.scrollSensitivity,
					speed = options.scrollSpeed,

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

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

R
RubaXa 已提交
404 405
					vx = (winWidth - x <= sens) - (x <= sens),
					vy = (winHeight - y <= sens) - (y <= sens)
R
RubaXa 已提交
406 407 408
				;

				if (vx || vy) {
R
RubaXa 已提交
409
					el = win;
R
RubaXa 已提交
410 411
				}
				else if (scrollEl) {
R
RubaXa 已提交
412
					el = scrollEl;
R
RubaXa 已提交
413 414 415
					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 已提交
416 417 418 419 420 421
				}

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

R
RubaXa 已提交
423 424 425 426 427 428 429 430 431 432 433 434
					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 已提交
435 436 437 438
				}
			}
		}, 30),

R
RubaXa 已提交
439

R
RubaXa 已提交
440
		_onDragOver: function (/**Event*/evt) {
R
RubaXa 已提交
441 442 443 444 445 446
			var el = this.el,
				target,
				dragRect,
				revert,
				options = this.options,
				group = options.group,
R
RubaXa 已提交
447
				groupPut = group.put,
448 449
				isOwner = (activeGroup === group),
				canSort = options.sort;
R
RubaXa 已提交
450

R
RubaXa 已提交
451 452
			(evt.stopPropagation !== void 0) && evt.stopPropagation();

R
RubaXa 已提交
453
			if (!_silent && activeGroup &&
454 455
				(isOwner
					? canSort || (revert = !rootEl.contains(dragEl))
R
RubaXa 已提交
456 457 458 459
					: activeGroup.pull && groupPut && (
						(activeGroup.name === group.name) || // by Name
						(groupPut.indexOf && ~groupPut.indexOf(activeGroup.name)) // by Array
					)
460
				) &&
R
RubaXa 已提交
461
				(evt.rootEl === void 0 || evt.rootEl === this.el)
R
RubaXa 已提交
462
			) {
R
RubaXa 已提交
463
				target = _closest(evt.target, options.draggable, el);
R
RubaXa 已提交
464 465
				dragRect = dragEl.getBoundingClientRect();

R
RubaXa 已提交
466
				if (cloneEl && (cloneEl.state !== isOwner)) {
R
RubaXa 已提交
467 468 469 470 471
					_css(cloneEl, 'display', isOwner ? 'none' : '');
					!isOwner && cloneEl.state && rootEl.insertBefore(cloneEl, dragEl);
					cloneEl.state = isOwner;
				}

472 473 474 475 476 477 478 479
				if (revert) {
					if (cloneEl || nextEl) {
						rootEl.insertBefore(dragEl, cloneEl || nextEl);
					}
					else if (!canSort) {
						rootEl.appendChild(dragEl);
					}

R
RubaXa 已提交
480 481
					return;
				}
R
RubaXa 已提交
482

R
RubaXa 已提交
483
				if ((el.children.length === 0) || (el.children[0] === ghostEl) ||
R
RubaXa 已提交
484
					(el === evt.target) && (target = _ghostInBottom(el, evt))
R
RubaXa 已提交
485
				) {
R
RubaXa 已提交
486 487 488 489 490 491
					if (target) {
						if (target.animated) {
							return;
						}
						targetRect = target.getBoundingClientRect();
					}
R
RubaXa 已提交
492

R
RubaXa 已提交
493
					el.appendChild(dragEl);
R
* anim  
RubaXa 已提交
494
					this._animate(dragRect, dragEl);
R
RubaXa 已提交
495
					target && this._animate(targetRect, target);
R
RubaXa 已提交
496
				}
R
RubaXa 已提交
497 498
				else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) {
					if (lastEl !== target) {
R
RubaXa 已提交
499
						lastEl = target;
R
RubaXa 已提交
500
						lastCSS = _css(target);
R
RubaXa 已提交
501 502 503
					}


R
RubaXa 已提交
504 505 506 507 508 509 510 511 512
					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 已提交
513
					;
R
RubaXa 已提交
514

R
RubaXa 已提交
515 516 517
					_silent = true;
					setTimeout(_unsilent, 30);

R
RubaXa 已提交
518 519
					if (floating) {
						after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
R
RubaXa 已提交
520
					} else {
R
RubaXa 已提交
521
						after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
R
RubaXa 已提交
522 523
					}

R
RubaXa 已提交
524
					if (after && !nextSibling) {
R
RubaXa 已提交
525 526 527
						el.appendChild(dragEl);
					} else {
						target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
R
RubaXa 已提交
528
					}
R
RubaXa 已提交
529

R
RubaXa 已提交
530 531
					this._animate(dragRect, dragEl);
					this._animate(targetRect, target);
R
RubaXa 已提交
532 533 534 535
				}
			}
		},

536 537 538 539 540 541
		_animate: function (prevRect, target) {
			var ms = this.options.animation;

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

R
RubaXa 已提交
542
				_css(target, 'transition', 'none');
543 544 545 546 547 548 549
				_css(target, 'transform', 'translate3d('
					+ (prevRect.left - currentRect.left) + 'px,'
					+ (prevRect.top - currentRect.top) + 'px,0)'
				);

				target.offsetWidth; // repaint

R
RubaXa 已提交
550
				_css(target, 'transition', 'all ' + ms + 'ms');
551 552
				_css(target, 'transform', 'translate3d(0,0,0)');

R
* anim  
RubaXa 已提交
553 554
				clearTimeout(target.animated);
				target.animated = setTimeout(function () {
555 556 557 558 559 560
					_css(target, 'transition', '');
					target.animated = false;
				}, ms);
			}
		},

561 562 563 564 565 566
		_offUpEvents: function () {
			_off(document, 'mouseup', this._onDrop);
			_off(document, 'touchmove', this._onTouchMove);
			_off(document, 'touchend', this._onDrop);
			_off(document, 'touchcancel', this._onDrop);
		},
R
RubaXa 已提交
567

R
RubaXa 已提交
568
		_onDrop: function (/**Event*/evt) {
R
RubaXa 已提交
569 570
			var el = this.el;

R
RubaXa 已提交
571
			clearInterval(this._loopId);
R
RubaXa 已提交
572
			clearInterval(autoScroll.pid);
R
RubaXa 已提交
573 574

			// Unbind events
R
RubaXa 已提交
575
			_off(document, 'drop', this);
R
RubaXa 已提交
576
			_off(document, 'dragover', this);
R
RubaXa 已提交
577

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

580
			this._offUpEvents();
R
RubaXa 已提交
581

R
RubaXa 已提交
582
			if (evt) {
R
RubaXa 已提交
583
				evt.preventDefault();
R
RubaXa 已提交
584
				evt.stopPropagation();
R
RubaXa 已提交
585

R
RubaXa 已提交
586
				ghostEl && ghostEl.parentNode.removeChild(ghostEl);
R
RubaXa 已提交
587

R
RubaXa 已提交
588
				if (dragEl) {
R
RubaXa 已提交
589 590
					_off(dragEl, 'dragend', this);

591 592
					// get the index of the dragged element within its parent
					var newIndex = _index(dragEl);
R
RubaXa 已提交
593

594
					_disableDraggable(dragEl);
R
RubaXa 已提交
595 596
					_toggleClass(dragEl, this.options.ghostClass, false);

R
RubaXa 已提交
597
					if (!rootEl.contains(dragEl)) {
598
						// drag from one list and drop into another
R
RubaXa 已提交
599 600
						_dispatchEvent(dragEl.parentNode, 'sort', dragEl, rootEl, startIndex, newIndex);
						_dispatchEvent(rootEl, 'sort', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
601 602

						// Add event
603
						_dispatchEvent(dragEl, 'add', dragEl, rootEl, startIndex, newIndex);
604 605

						// Remove event
R
RubaXa 已提交
606
						_dispatchEvent(rootEl, 'remove', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
607
					}
R
RubaXa 已提交
608
					else if (dragEl.nextSibling !== nextEl) {
609
						// drag & drop within the same list
R
RubaXa 已提交
610 611
						_dispatchEvent(rootEl, 'update', dragEl, rootEl, startIndex, newIndex);
						_dispatchEvent(rootEl, 'sort', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
612

R
RubaXa 已提交
613
						cloneEl && cloneEl.parentNode.removeChild(cloneEl);
R
RubaXa 已提交
614
					}
615

R
RubaXa 已提交
616 617
					// Drag end event
					_dispatchEvent(rootEl, 'end', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
618 619 620 621 622 623 624
				}

				// Set NULL
				rootEl =
				dragEl =
				ghostEl =
				nextEl =
R
RubaXa 已提交
625
				cloneEl =
R
RubaXa 已提交
626 627 628 629 630 631 632

				tapEvt =
				touchEvt =

				lastEl =
				lastCSS =

R
RubaXa 已提交
633 634
				activeGroup =
				Sortable.active = null;
635 636 637

				// Save sorting
				this.options.store && this.options.store.set(this);
R
RubaXa 已提交
638 639 640 641
			}
		},


R
RubaXa 已提交
642 643 644 645 646 647 648
		handleEvent: function (/**Event*/evt) {
			var type = evt.type;

			if (type === 'dragover') {
				this._onDrag(evt);
				_globalDragOver(evt);
			}
R
RubaXa 已提交
649
			else if (type === 'drop' || type === 'dragend') {
R
RubaXa 已提交
650 651
				this._onDrop(evt);
			}
R
RubaXa 已提交
652 653 654
		},


655 656 657 658 659 660 661 662 663
		/**
		 * Serializes the item into an array of string.
		 * @returns {String[]}
		 */
		toArray: function () {
			var order = [],
				el,
				children = this.el.children,
				i = 0,
R
RubaXa 已提交
664
				n = children.length;
665 666 667

			for (; i < n; i++) {
				el = children[i];
R
RubaXa 已提交
668 669 670
				if (_closest(el, this.options.draggable, this.el)) {
					order.push(el.getAttribute('data-id') || _generateId(el));
				}
671 672 673 674 675 676 677 678 679 680 681
			}

			return order;
		},


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

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

R
RubaXa 已提交
687
				if (_closest(el, this.options.draggable, rootEl)) {
R
RubaXa 已提交
688 689 690
					items[id] = el;
				}
			}, this);
691 692 693 694


			order.forEach(function (id) {
				if (items[id]) {
R
RubaXa 已提交
695 696
					rootEl.removeChild(items[id]);
					rootEl.appendChild(items[id]);
697 698 699 700 701
				}
			});
		},


702 703 704 705 706 707 708 709 710 711 712
		/**
		 * 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);
		},


713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
		/**
		 * 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;
			}
		},


730 731 732 733
		/**
		 * Destroy
		 */
		destroy: function () {
R
RubaXa 已提交
734 735
			var el = this.el, options = this.options;

736 737 738 739
			_customEvents.forEach(function (name) {
				_off(el, name.substr(2).toLowerCase(), options[name]);
			});

R
RubaXa 已提交
740 741
			_off(el, 'mousedown', this._onTapStart);
			_off(el, 'touchstart', this._onTapStart);
N
Nicolas 已提交
742
			_off(el, 'selectstart', this._onTapStart);
R
RubaXa 已提交
743 744 745 746

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

747
			//remove draggable attributes
R
RubaXa 已提交
748
			Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
749 750 751
				el.removeAttribute('draggable');
			});

R
RubaXa 已提交
752 753 754 755 756 757 758 759
			touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);

			this._onDrop();

			this.el = null;
		}
	};

760

R
RubaXa 已提交
761
	function _bind(ctx, fn) {
R
RubaXa 已提交
762
		var args = slice.call(arguments, 2);
R
RubaXa 已提交
763
		return	fn.bind ? fn.bind.apply(fn, [ctx].concat(args)) : function () {
R
RubaXa 已提交
764 765 766 767 768
			return fn.apply(ctx, args.concat(slice.call(arguments)));
		};
	}


R
RubaXa 已提交
769
	function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) {
R
RubaXa 已提交
770
		if (el) {
R
RubaXa 已提交
771 772 773
			ctx = ctx || document;
			selector = selector.split('.');

R
RubaXa 已提交
774 775
			var tag = selector.shift().toUpperCase(),
				re = new RegExp('\\s(' + selector.join('|') + ')\\s', 'g');
R
RubaXa 已提交
776 777

			do {
R
RubaXa 已提交
778
				if (
R
RubaXa 已提交
779 780 781 782
					(tag === '>*' && el.parentNode === ctx) || (
						(tag === '' || el.nodeName == tag) &&
						(!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
					)
R
RubaXa 已提交
783 784
				) {
					return el;
R
RubaXa 已提交
785 786
				}
			}
R
RubaXa 已提交
787
			while (el !== ctx && (el = el.parentNode));
R
RubaXa 已提交
788 789
		}

R
RubaXa 已提交
790
		return null;
R
RubaXa 已提交
791 792 793
	}


794
	function _globalDragOver(/**Event*/evt) {
R
RubaXa 已提交
795 796 797 798 799
		evt.dataTransfer.dropEffect = 'move';
		evt.preventDefault();
	}


R
RubaXa 已提交
800
	function _on(el, event, fn) {
R
RubaXa 已提交
801 802 803 804
		el.addEventListener(event, fn, false);
	}


R
RubaXa 已提交
805
	function _off(el, event, fn) {
R
RubaXa 已提交
806 807 808 809
		el.removeEventListener(event, fn, false);
	}


R
RubaXa 已提交
810 811 812
	function _toggleClass(el, name, state) {
		if (el) {
			if (el.classList) {
R
RubaXa 已提交
813 814 815
				el.classList[state ? 'add' : 'remove'](name);
			}
			else {
R
RubaXa 已提交
816 817
				var className = (' ' + el.className + ' ').replace(/\s+/g, ' ').replace(' ' + name + ' ', '');
				el.className = className + (state ? ' ' + name : '');
R
RubaXa 已提交
818 819 820 821 822
			}
		}
	}


R
RubaXa 已提交
823
	function _css(el, prop, val) {
R
RubaXa 已提交
824 825
		var style = el && el.style;

R
RubaXa 已提交
826 827 828
		if (style) {
			if (val === void 0) {
				if (document.defaultView && document.defaultView.getComputedStyle) {
R
RubaXa 已提交
829 830
					val = document.defaultView.getComputedStyle(el, '');
				}
R
RubaXa 已提交
831 832
				else if (el.currentStyle) {
					val = el.currentStyle;
R
RubaXa 已提交
833
				}
R
RubaXa 已提交
834 835 836 837 838 839 840 841 842

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

				style[prop] = val + (typeof val === 'string' ? '' : 'px');
R
RubaXa 已提交
843 844 845 846 847
			}
		}
	}


R
RubaXa 已提交
848 849
	function _find(ctx, tagName, iterator) {
		if (ctx) {
R
RubaXa 已提交
850
			var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
R
RubaXa 已提交
851

R
RubaXa 已提交
852 853
			if (iterator) {
				for (; i < n; i++) {
R
RubaXa 已提交
854 855 856
					iterator(list[i], i);
				}
			}
R
RubaXa 已提交
857

R
RubaXa 已提交
858
			return list;
R
RubaXa 已提交
859
		}
R
RubaXa 已提交
860 861

		return [];
R
RubaXa 已提交
862 863 864
	}


R
RubaXa 已提交
865
	function _disableDraggable(el) {
R
RubaXa 已提交
866
		el.draggable = false;
R
RubaXa 已提交
867 868 869
	}


R
RubaXa 已提交
870
	function _unsilent() {
R
RubaXa 已提交
871 872 873 874
		_silent = false;
	}


R
RubaXa 已提交
875
	/** @returns {HTMLElement|false} */
R
RubaXa 已提交
876
	function _ghostInBottom(el, evt) {
R
RubaXa 已提交
877 878
		var lastEl = el.lastElementChild, rect = lastEl.getBoundingClientRect();
		return (evt.clientY - (rect.top + rect.height) > 5) && lastEl; // min delta
R
RubaXa 已提交
879 880 881
	}


882 883 884 885 886 887 888
	/**
	 * Generate id
	 * @param   {HTMLElement} el
	 * @returns {String}
	 * @private
	 */
	function _generateId(el) {
R
RubaXa 已提交
889
		var str = el.tagName + el.className + el.src + el.href + el.textContent,
890
			i = str.length,
R
RubaXa 已提交
891
			sum = 0;
892

893 894 895
		while (i--) {
			sum += str.charCodeAt(i);
		}
896

897 898 899
		return sum.toString(36);
	}

900 901 902
	/**
	 * Returns the index of an element within its parent
	 * @param el
903 904
	 * @returns {number}
	 * @private
905 906 907
	 */
	function _index(/**HTMLElement*/el) {
		var index = 0;
908
		while (el && (el = el.previousElementSibling)) {
909 910 911 912
			index++;
		}
		return index;
	}
R
RubaXa 已提交
913

R
RubaXa 已提交
914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
	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 已提交
936 937 938 939 940 941 942
	// Export utils
	Sortable.utils = {
		on: _on,
		off: _off,
		css: _css,
		find: _find,
		bind: _bind,
R
RubaXa 已提交
943 944 945
		is: function (el, selector) {
			return !!_closest(el, selector, el);
		},
R
RubaXa 已提交
946
		throttle: _throttle,
R
RubaXa 已提交
947
		closest: _closest,
948
		toggleClass: _toggleClass,
949 950
		dispatchEvent: _dispatchEvent,
		index: _index
R
RubaXa 已提交
951 952 953
	};


954
	Sortable.version = '0.7.2';
955

R
RubaXa 已提交
956

957 958 959 960 961 962
	/**
	 * Create sortable instance
	 * @param {HTMLElement}  el
	 * @param {Object}      [options]
	 */
	Sortable.create = function (el, options) {
R
RubaXa 已提交
963
		return new Sortable(el, options);
964
	};
R
RubaXa 已提交
965 966

	// Export
967
	return Sortable;
R
RubaXa 已提交
968
});