Sortable.js 21.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
	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
		},
R
RubaXa 已提交
108 109

		group = options.group;
110

R
RubaXa 已提交
111

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

117

R
RubaXa 已提交
118 119
		if (!group || typeof group != 'object') {
			group = options.group = { name: group };
R
RubaXa 已提交
120 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
					evt.preventDefault();
R
RubaXa 已提交
199 200
					return; // cancel dnd
				}
201
			}
R
RubaXa 已提交
202
			else if (filter) {
R
RubaXa 已提交
203 204 205 206 207 208 209
				filter = filter.split(',').some(function (criteria) {
					criteria = _closest(originalTarget, criteria.trim(), el);

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

R
RubaXa 已提交
212 213
				if (filter) {
					evt.preventDefault();
214 215 216 217
					return; // cancel dnd
				}
			}

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

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

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

				dragEl.draggable = true;
R
RubaXa 已提交
234 235

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

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

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

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

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

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


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


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


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

				Sortable.active = this;
R
RubaXa 已提交
283 284 285
			}
		},

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

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

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

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


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

				touchEvt = touch;
R
RubaXa 已提交
319 320 321 322 323 324

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

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


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

335
			this._offUpEvents();
R
RubaXa 已提交
336

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

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

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

R
RubaXa 已提交
352 353 354 355
				rootEl.appendChild(ghostEl);

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

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

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

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

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

			scrollEl = options.scroll;

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

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

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

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

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

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

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

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

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

R
RubaXa 已提交
441

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

R
RubaXa 已提交
453 454 455 456
			if (evt.preventDefault !== void 0) {
				evt.preventDefault();
				evt.stopPropagation();
			}
R
RubaXa 已提交
457

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


472
				if (revert) {
R
RubaXa 已提交
473 474
					_cloneHide(true);

475 476 477 478 479 480 481
					if (cloneEl || nextEl) {
						rootEl.insertBefore(dragEl, cloneEl || nextEl);
					}
					else if (!canSort) {
						rootEl.appendChild(dragEl);
					}

R
RubaXa 已提交
482 483
					return;
				}
R
RubaXa 已提交
484

R
RubaXa 已提交
485

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

R
RubaXa 已提交
496 497
					_cloneHide(isOwner);

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


R
RubaXa 已提交
509 510 511 512 513 514 515 516 517
					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 已提交
518
					;
R
RubaXa 已提交
519

R
RubaXa 已提交
520 521 522
					_silent = true;
					setTimeout(_unsilent, 30);

R
RubaXa 已提交
523 524
					_cloneHide(isOwner);

R
RubaXa 已提交
525 526
					if (floating) {
						after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
R
RubaXa 已提交
527
					} else {
R
RubaXa 已提交
528
						after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
R
RubaXa 已提交
529 530
					}

R
RubaXa 已提交
531
					if (after && !nextSibling) {
R
RubaXa 已提交
532 533 534
						el.appendChild(dragEl);
					} else {
						target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
R
RubaXa 已提交
535
					}
R
RubaXa 已提交
536

R
RubaXa 已提交
537 538
					this._animate(dragRect, dragEl);
					this._animate(targetRect, target);
R
RubaXa 已提交
539 540 541 542
				}
			}
		},

543 544 545 546 547 548
		_animate: function (prevRect, target) {
			var ms = this.options.animation;

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

R
RubaXa 已提交
549
				_css(target, 'transition', 'none');
550 551 552 553 554 555 556
				_css(target, 'transform', 'translate3d('
					+ (prevRect.left - currentRect.left) + 'px,'
					+ (prevRect.top - currentRect.top) + 'px,0)'
				);

				target.offsetWidth; // repaint

R
RubaXa 已提交
557
				_css(target, 'transition', 'all ' + ms + 'ms');
558 559
				_css(target, 'transform', 'translate3d(0,0,0)');

R
* anim  
RubaXa 已提交
560 561
				clearTimeout(target.animated);
				target.animated = setTimeout(function () {
562 563 564 565 566 567
					_css(target, 'transition', '');
					target.animated = false;
				}, ms);
			}
		},

568 569 570 571 572 573
		_offUpEvents: function () {
			_off(document, 'mouseup', this._onDrop);
			_off(document, 'touchmove', this._onTouchMove);
			_off(document, 'touchend', this._onDrop);
			_off(document, 'touchcancel', this._onDrop);
		},
R
RubaXa 已提交
574

R
RubaXa 已提交
575
		_onDrop: function (/**Event*/evt) {
R
RubaXa 已提交
576 577
			var el = this.el;

R
RubaXa 已提交
578
			clearInterval(this._loopId);
R
RubaXa 已提交
579
			clearInterval(autoScroll.pid);
R
RubaXa 已提交
580 581

			// Unbind events
R
RubaXa 已提交
582
			_off(document, 'drop', this);
R
RubaXa 已提交
583
			_off(document, 'dragover', this);
R
RubaXa 已提交
584

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

587
			this._offUpEvents();
R
RubaXa 已提交
588

R
RubaXa 已提交
589
			if (evt) {
R
RubaXa 已提交
590
				evt.preventDefault();
R
RubaXa 已提交
591
				evt.stopPropagation();
R
RubaXa 已提交
592

R
RubaXa 已提交
593
				ghostEl && ghostEl.parentNode.removeChild(ghostEl);
R
RubaXa 已提交
594

R
RubaXa 已提交
595
				if (dragEl) {
R
RubaXa 已提交
596 597
					_off(dragEl, 'dragend', this);

598 599
					// get the index of the dragged element within its parent
					var newIndex = _index(dragEl);
R
RubaXa 已提交
600

601
					_disableDraggable(dragEl);
R
RubaXa 已提交
602 603
					_toggleClass(dragEl, this.options.ghostClass, false);

R
RubaXa 已提交
604
					if (!rootEl.contains(dragEl)) {
605
						// drag from one list and drop into another
R
RubaXa 已提交
606 607
						_dispatchEvent(dragEl.parentNode, 'sort', dragEl, rootEl, startIndex, newIndex);
						_dispatchEvent(rootEl, 'sort', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
608 609

						// Add event
610
						_dispatchEvent(dragEl, 'add', dragEl, rootEl, startIndex, newIndex);
611 612

						// Remove event
R
RubaXa 已提交
613
						_dispatchEvent(rootEl, 'remove', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
614
					}
R
RubaXa 已提交
615
					else if (dragEl.nextSibling !== nextEl) {
616
						// drag & drop within the same list
R
RubaXa 已提交
617 618
						_dispatchEvent(rootEl, 'update', dragEl, rootEl, startIndex, newIndex);
						_dispatchEvent(rootEl, 'sort', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
619

R
RubaXa 已提交
620
						cloneEl && cloneEl.parentNode.removeChild(cloneEl);
R
RubaXa 已提交
621
					}
622

R
RubaXa 已提交
623 624
					// Drag end event
					_dispatchEvent(rootEl, 'end', dragEl, rootEl, startIndex, newIndex);
R
RubaXa 已提交
625 626 627 628 629 630 631
				}

				// Set NULL
				rootEl =
				dragEl =
				ghostEl =
				nextEl =
R
RubaXa 已提交
632
				cloneEl =
R
RubaXa 已提交
633 634 635 636 637 638 639

				tapEvt =
				touchEvt =

				lastEl =
				lastCSS =

R
RubaXa 已提交
640 641
				activeGroup =
				Sortable.active = null;
642 643

				// Save sorting
R
RubaXa 已提交
644
				this.save();
R
RubaXa 已提交
645 646 647 648
			}
		},


R
RubaXa 已提交
649 650 651 652 653 654 655
		handleEvent: function (/**Event*/evt) {
			var type = evt.type;

			if (type === 'dragover') {
				this._onDrag(evt);
				_globalDragOver(evt);
			}
R
RubaXa 已提交
656
			else if (type === 'drop' || type === 'dragend') {
R
RubaXa 已提交
657 658
				this._onDrop(evt);
			}
R
RubaXa 已提交
659 660 661
		},


662 663 664 665 666 667 668 669 670
		/**
		 * Serializes the item into an array of string.
		 * @returns {String[]}
		 */
		toArray: function () {
			var order = [],
				el,
				children = this.el.children,
				i = 0,
R
RubaXa 已提交
671
				n = children.length;
672 673 674

			for (; i < n; i++) {
				el = children[i];
R
RubaXa 已提交
675 676 677
				if (_closest(el, this.options.draggable, this.el)) {
					order.push(el.getAttribute('data-id') || _generateId(el));
				}
678 679 680 681 682 683 684 685 686 687 688
			}

			return order;
		},


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

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

R
RubaXa 已提交
694
				if (_closest(el, this.options.draggable, rootEl)) {
R
RubaXa 已提交
695 696 697
					items[id] = el;
				}
			}, this);
698 699 700

			order.forEach(function (id) {
				if (items[id]) {
R
RubaXa 已提交
701 702
					rootEl.removeChild(items[id]);
					rootEl.appendChild(items[id]);
703 704 705 706 707
				}
			});
		},


R
RubaXa 已提交
708 709 710 711 712 713 714 715 716
		/**
		 * Save the current sorting
		 */
		save: function () {
			var store = this.options.store;
			store && store.set(this);
		},


717 718 719 720 721 722 723 724 725 726 727
		/**
		 * 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);
		},


728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
		/**
		 * 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;
			}
		},


745 746 747 748
		/**
		 * Destroy
		 */
		destroy: function () {
R
RubaXa 已提交
749 750
			var el = this.el, options = this.options;

751 752 753 754
			_customEvents.forEach(function (name) {
				_off(el, name.substr(2).toLowerCase(), options[name]);
			});

R
RubaXa 已提交
755 756
			_off(el, 'mousedown', this._onTapStart);
			_off(el, 'touchstart', this._onTapStart);
N
Nicolas 已提交
757
			_off(el, 'selectstart', this._onTapStart);
R
RubaXa 已提交
758 759 760 761

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

762
			//remove draggable attributes
R
RubaXa 已提交
763
			Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
764 765 766
				el.removeAttribute('draggable');
			});

R
RubaXa 已提交
767 768 769 770 771 772 773 774
			touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);

			this._onDrop();

			this.el = null;
		}
	};

775

R
RubaXa 已提交
776 777 778 779 780 781 782 783 784
	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 已提交
785
	function _bind(ctx, fn) {
R
RubaXa 已提交
786
		var args = slice.call(arguments, 2);
R
RubaXa 已提交
787
		return	fn.bind ? fn.bind.apply(fn, [ctx].concat(args)) : function () {
R
RubaXa 已提交
788 789 790 791 792
			return fn.apply(ctx, args.concat(slice.call(arguments)));
		};
	}


R
RubaXa 已提交
793
	function _closest(/**HTMLElement*/el, /**String*/selector, /**HTMLElement*/ctx) {
R
RubaXa 已提交
794
		if (el) {
R
RubaXa 已提交
795 796 797
			ctx = ctx || document;
			selector = selector.split('.');

R
RubaXa 已提交
798 799
			var tag = selector.shift().toUpperCase(),
				re = new RegExp('\\s(' + selector.join('|') + ')\\s', 'g');
R
RubaXa 已提交
800 801

			do {
R
RubaXa 已提交
802
				if (
R
RubaXa 已提交
803 804 805 806
					(tag === '>*' && el.parentNode === ctx) || (
						(tag === '' || el.nodeName == tag) &&
						(!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
					)
R
RubaXa 已提交
807 808
				) {
					return el;
R
RubaXa 已提交
809 810
				}
			}
R
RubaXa 已提交
811
			while (el !== ctx && (el = el.parentNode));
R
RubaXa 已提交
812 813
		}

R
RubaXa 已提交
814
		return null;
R
RubaXa 已提交
815 816 817
	}


818
	function _globalDragOver(/**Event*/evt) {
R
RubaXa 已提交
819 820 821 822 823
		evt.dataTransfer.dropEffect = 'move';
		evt.preventDefault();
	}


R
RubaXa 已提交
824
	function _on(el, event, fn) {
R
RubaXa 已提交
825 826 827 828
		el.addEventListener(event, fn, false);
	}


R
RubaXa 已提交
829
	function _off(el, event, fn) {
R
RubaXa 已提交
830 831 832 833
		el.removeEventListener(event, fn, false);
	}


R
RubaXa 已提交
834 835 836
	function _toggleClass(el, name, state) {
		if (el) {
			if (el.classList) {
R
RubaXa 已提交
837 838 839
				el.classList[state ? 'add' : 'remove'](name);
			}
			else {
R
RubaXa 已提交
840 841
				var className = (' ' + el.className + ' ').replace(/\s+/g, ' ').replace(' ' + name + ' ', '');
				el.className = className + (state ? ' ' + name : '');
R
RubaXa 已提交
842 843 844 845 846
			}
		}
	}


R
RubaXa 已提交
847
	function _css(el, prop, val) {
R
RubaXa 已提交
848 849
		var style = el && el.style;

R
RubaXa 已提交
850 851 852
		if (style) {
			if (val === void 0) {
				if (document.defaultView && document.defaultView.getComputedStyle) {
R
RubaXa 已提交
853 854
					val = document.defaultView.getComputedStyle(el, '');
				}
R
RubaXa 已提交
855 856
				else if (el.currentStyle) {
					val = el.currentStyle;
R
RubaXa 已提交
857
				}
R
RubaXa 已提交
858 859 860 861 862 863 864 865 866

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

				style[prop] = val + (typeof val === 'string' ? '' : 'px');
R
RubaXa 已提交
867 868 869 870 871
			}
		}
	}


R
RubaXa 已提交
872 873
	function _find(ctx, tagName, iterator) {
		if (ctx) {
R
RubaXa 已提交
874
			var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
R
RubaXa 已提交
875

R
RubaXa 已提交
876 877
			if (iterator) {
				for (; i < n; i++) {
R
RubaXa 已提交
878 879 880
					iterator(list[i], i);
				}
			}
R
RubaXa 已提交
881

R
RubaXa 已提交
882
			return list;
R
RubaXa 已提交
883
		}
R
RubaXa 已提交
884 885

		return [];
R
RubaXa 已提交
886 887 888
	}


R
RubaXa 已提交
889
	function _disableDraggable(el) {
R
RubaXa 已提交
890
		el.draggable = false;
R
RubaXa 已提交
891 892 893
	}


R
RubaXa 已提交
894
	function _unsilent() {
R
RubaXa 已提交
895 896 897 898
		_silent = false;
	}


R
RubaXa 已提交
899
	/** @returns {HTMLElement|false} */
R
RubaXa 已提交
900
	function _ghostInBottom(el, evt) {
R
RubaXa 已提交
901 902
		var lastEl = el.lastElementChild, rect = lastEl.getBoundingClientRect();
		return (evt.clientY - (rect.top + rect.height) > 5) && lastEl; // min delta
R
RubaXa 已提交
903 904 905
	}


906 907 908 909 910 911 912
	/**
	 * Generate id
	 * @param   {HTMLElement} el
	 * @returns {String}
	 * @private
	 */
	function _generateId(el) {
R
RubaXa 已提交
913
		var str = el.tagName + el.className + el.src + el.href + el.textContent,
914
			i = str.length,
R
RubaXa 已提交
915
			sum = 0;
916

917 918 919
		while (i--) {
			sum += str.charCodeAt(i);
		}
920

921 922 923
		return sum.toString(36);
	}

924 925 926
	/**
	 * Returns the index of an element within its parent
	 * @param el
927 928
	 * @returns {number}
	 * @private
929 930 931
	 */
	function _index(/**HTMLElement*/el) {
		var index = 0;
G
Greg Hoyl 已提交
932
		while (el && (el = el.previousElementSibling) && (el.nodeName !== 'TEMPLATE')) {
933 934 935 936
			index++;
		}
		return index;
	}
R
RubaXa 已提交
937

R
RubaXa 已提交
938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959
	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 已提交
960 961 962 963 964 965 966
	// Export utils
	Sortable.utils = {
		on: _on,
		off: _off,
		css: _css,
		find: _find,
		bind: _bind,
R
RubaXa 已提交
967 968 969
		is: function (el, selector) {
			return !!_closest(el, selector, el);
		},
R
RubaXa 已提交
970
		throttle: _throttle,
R
RubaXa 已提交
971
		closest: _closest,
972
		toggleClass: _toggleClass,
973 974
		dispatchEvent: _dispatchEvent,
		index: _index
R
RubaXa 已提交
975 976 977
	};


R
RubaXa 已提交
978
	Sortable.version = '1.0.0';
979

R
RubaXa 已提交
980

981 982 983 984 985 986
	/**
	 * Create sortable instance
	 * @param {HTMLElement}  el
	 * @param {Object}      [options]
	 */
	Sortable.create = function (el, options) {
R
RubaXa 已提交
987
		return new Sortable(el, options);
988
	};
R
RubaXa 已提交
989 990

	// Export
991
	return Sortable;
R
RubaXa 已提交
992
});