Sortable.js 19.2 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 32
		ghostEl,
		cloneEl,
		rootEl,
		nextEl,
R
RubaXa 已提交
33

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

R
RubaXa 已提交
37
		activeGroup,
R
RubaXa 已提交
38

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

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

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

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

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

54 55 56
			evt.initEvent(name, true, true);
			evt.item = targetEl || rootEl;
			evt.from = fromEl || rootEl;
57 58
			if (startIndex !== undefined) evt.oldIndex = startIndex;
			if (newIndex !== undefined) evt.newIndex = newIndex;
59

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

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

R
RubaXa 已提交
65 66
		noop = function () {},
		slice = [].slice,
R
RubaXa 已提交
67

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


72

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


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

R
RubaXa 已提交
100

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

106

R
RubaXa 已提交
107 108 109 110
		if (!options.group.name) {
			options.group = { name: options.group };
		}

R
RubaXa 已提交
111

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


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


R
* JSDoc  
RubaXa 已提交
126
		// Export group name
R
RubaXa 已提交
127
		el[expando] = options.group.name;
R
RubaXa 已提交
128 129


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


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

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

		touchDragOverListeners.push(this._onDragOver);
147 148 149

		// Restore sorting
		options.store && this.sort(options.store.get(this));
R
RubaXa 已提交
150 151 152
	}


153
	Sortable.prototype = /** @lends Sortable.prototype */ {
R
RubaXa 已提交
154 155 156
		constructor: Sortable,


R
RubaXa 已提交
157
		_applyEffects: function () {
R
RubaXa 已提交
158 159 160 161
			_toggleClass(dragEl, this.options.ghostClass, true);
		},


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

R
RubaXa 已提交
170 171
			if (evt.type === 'mousedown' && evt.button !== 0 || options.disabled) {
				return; // only left button or enabled
R
RubaXa 已提交
172 173
			}

174 175 176 177 178 179 180 181 182
			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);

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

				if (filter.length) {
196
					_dispatchEvent(originalTarget, 'filter', target, undefined, startIndex);
197 198 199 200
					return; // cancel dnd
				}
			}

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

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

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

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

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

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

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

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

				_on(this.el, 'dragstart', this._onDragStart);
R
RubaXa 已提交
240
				_on(this.el, 'dragend', this._onDrop);
R
RubaXa 已提交
241 242 243 244
				_on(document, 'dragover', _globalDragOver);


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


254
				_dispatchEvent(dragEl, 'start', undefined, undefined, startIndex);
R
RubaXa 已提交
255 256


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

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

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

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

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

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

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


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

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

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

M
Marius Petcu 已提交
314
				evt.preventDefault();
R
RubaXa 已提交
315 316 317 318
			}
		},


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

323
			this._offUpEvents();
R
RubaXa 已提交
324

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

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

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

R
RubaXa 已提交
340 341 342 343
				rootEl.appendChild(ghostEl);

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

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

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

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

			setTimeout(this._applyEffects);
		},


R
RubaXa 已提交
365
		_onDragOver: function (/**Event*/evt) {
R
RubaXa 已提交
366 367 368 369 370 371
			var el = this.el,
				target,
				dragRect,
				revert,
				options = this.options,
				group = options.group,
R
RubaXa 已提交
372
				groupPut = group.put,
373 374
				isOwner = (activeGroup === group),
				canSort = options.sort;
R
RubaXa 已提交
375

R
RubaXa 已提交
376
			if (!_silent &&
377 378
				(isOwner
					? canSort || (revert = !rootEl.contains(dragEl))
R
RubaXa 已提交
379 380 381 382
					: activeGroup.pull && groupPut && (
						(activeGroup.name === group.name) || // by Name
						(groupPut.indexOf && ~groupPut.indexOf(activeGroup.name)) // by Array
					)
383
				) &&
R
RubaXa 已提交
384
				(evt.rootEl === void 0 || evt.rootEl === this.el)
R
RubaXa 已提交
385
			) {
R
RubaXa 已提交
386
				target = _closest(evt.target, options.draggable, el);
R
RubaXa 已提交
387 388
				dragRect = dragEl.getBoundingClientRect();

R
RubaXa 已提交
389
				if (cloneEl && (cloneEl.state !== isOwner)) {
R
RubaXa 已提交
390 391 392 393 394
					_css(cloneEl, 'display', isOwner ? 'none' : '');
					!isOwner && cloneEl.state && rootEl.insertBefore(cloneEl, dragEl);
					cloneEl.state = isOwner;
				}

395 396 397 398 399 400 401 402
				if (revert) {
					if (cloneEl || nextEl) {
						rootEl.insertBefore(dragEl, cloneEl || nextEl);
					}
					else if (!canSort) {
						rootEl.appendChild(dragEl);
					}

R
RubaXa 已提交
403 404
					return;
				}
R
RubaXa 已提交
405

R
RubaXa 已提交
406
				if ((el.children.length === 0) || (el.children[0] === ghostEl) ||
R
RubaXa 已提交
407
					(el === evt.target) && (target = _ghostInBottom(el, evt))
R
RubaXa 已提交
408
				) {
R
RubaXa 已提交
409 410 411 412 413 414
					if (target) {
						if (target.animated) {
							return;
						}
						targetRect = target.getBoundingClientRect();
					}
R
RubaXa 已提交
415

R
RubaXa 已提交
416
					el.appendChild(dragEl);
R
* anim  
RubaXa 已提交
417
					this._animate(dragRect, dragEl);
R
RubaXa 已提交
418
					target && this._animate(targetRect, target);
R
RubaXa 已提交
419
				}
R
RubaXa 已提交
420 421
				else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) {
					if (lastEl !== target) {
R
RubaXa 已提交
422
						lastEl = target;
R
RubaXa 已提交
423
						lastCSS = _css(target);
R
RubaXa 已提交
424 425 426
					}


R
RubaXa 已提交
427 428 429 430 431 432 433 434 435
					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 已提交
436
					;
R
RubaXa 已提交
437

R
RubaXa 已提交
438 439 440
					_silent = true;
					setTimeout(_unsilent, 30);

R
RubaXa 已提交
441 442
					if (floating) {
						after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
R
RubaXa 已提交
443
					} else {
R
RubaXa 已提交
444
						after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
R
RubaXa 已提交
445 446
					}

R
RubaXa 已提交
447
					if (after && !nextSibling) {
R
RubaXa 已提交
448 449 450
						el.appendChild(dragEl);
					} else {
						target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
R
RubaXa 已提交
451
					}
R
RubaXa 已提交
452

R
RubaXa 已提交
453 454
					this._animate(dragRect, dragEl);
					this._animate(targetRect, target);
R
RubaXa 已提交
455 456 457 458
				}
			}
		},

459 460 461 462 463 464
		_animate: function (prevRect, target) {
			var ms = this.options.animation;

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

R
RubaXa 已提交
465
				_css(target, 'transition', 'none');
466 467 468 469 470 471 472
				_css(target, 'transform', 'translate3d('
					+ (prevRect.left - currentRect.left) + 'px,'
					+ (prevRect.top - currentRect.top) + 'px,0)'
				);

				target.offsetWidth; // repaint

R
RubaXa 已提交
473
				_css(target, 'transition', 'all ' + ms + 'ms');
474 475
				_css(target, 'transform', 'translate3d(0,0,0)');

R
* anim  
RubaXa 已提交
476 477
				clearTimeout(target.animated);
				target.animated = setTimeout(function () {
478 479 480 481 482 483
					_css(target, 'transition', '');
					target.animated = false;
				}, ms);
			}
		},

484 485 486 487 488 489
		_offUpEvents: function () {
			_off(document, 'mouseup', this._onDrop);
			_off(document, 'touchmove', this._onTouchMove);
			_off(document, 'touchend', this._onDrop);
			_off(document, 'touchcancel', this._onDrop);
		},
R
RubaXa 已提交
490

R
RubaXa 已提交
491
		_onDrop: function (/**Event*/evt) {
R
RubaXa 已提交
492 493 494 495 496 497
			clearInterval(this._loopId);

			// Unbind events
			_off(document, 'drop', this._onDrop);
			_off(document, 'dragover', _globalDragOver);

R
RubaXa 已提交
498
			_off(this.el, 'dragend', this._onDrop);
R
RubaXa 已提交
499
			_off(this.el, 'dragstart', this._onDragStart);
N
Nicolas 已提交
500
			_off(this.el, 'selectstart', this._onTapStart);
R
RubaXa 已提交
501

502
			this._offUpEvents();
R
RubaXa 已提交
503

R
RubaXa 已提交
504
			if (evt) {
R
RubaXa 已提交
505
				evt.preventDefault();
R
RubaXa 已提交
506
				evt.stopPropagation();
R
RubaXa 已提交
507

R
RubaXa 已提交
508
				ghostEl && ghostEl.parentNode.removeChild(ghostEl);
R
RubaXa 已提交
509

R
RubaXa 已提交
510
				if (dragEl) {
511 512
					// get the index of the dragged element within its parent
					var newIndex = _index(dragEl);
513
					_disableDraggable(dragEl);
R
RubaXa 已提交
514 515
					_toggleClass(dragEl, this.options.ghostClass, false);

R
RubaXa 已提交
516
					if (!rootEl.contains(dragEl)) {
517 518 519
						// drag from one list and drop into another
						_dispatchEvent(dragEl, 'sort', dragEl, dragEl.parentNode, startIndex, newIndex);
						_dispatchEvent(rootEl, 'sort', dragEl, undefined, startIndex, newIndex);
R
RubaXa 已提交
520 521

						// Add event
522
						_dispatchEvent(dragEl, 'add', dragEl, rootEl, startIndex, newIndex);
523 524

						// Remove event
525
						_dispatchEvent(rootEl, 'remove', dragEl, undefined, startIndex, newIndex);
R
RubaXa 已提交
526
					}
R
RubaXa 已提交
527
					else if (dragEl.nextSibling !== nextEl) {
528 529 530
						// drag & drop within the same list
						_dispatchEvent(dragEl, 'update', undefined, undefined, startIndex, newIndex);
						_dispatchEvent(dragEl, 'sort', undefined, undefined, startIndex, newIndex);
R
RubaXa 已提交
531

R
RubaXa 已提交
532
						cloneEl && cloneEl.parentNode.removeChild(cloneEl);
R
RubaXa 已提交
533
					}
534

535
					_dispatchEvent(rootEl, 'end', undefined, undefined, startIndex, newIndex);
R
RubaXa 已提交
536 537 538 539 540 541 542
				}

				// Set NULL
				rootEl =
				dragEl =
				ghostEl =
				nextEl =
R
RubaXa 已提交
543
				cloneEl =
R
RubaXa 已提交
544 545 546 547 548 549 550 551

				tapEvt =
				touchEvt =

				lastEl =
				lastCSS =

				activeGroup = null;
552 553 554

				// Save sorting
				this.options.store && this.options.store.set(this);
R
RubaXa 已提交
555 556 557 558
			}
		},


559 560 561 562 563 564 565 566 567
		/**
		 * Serializes the item into an array of string.
		 * @returns {String[]}
		 */
		toArray: function () {
			var order = [],
				el,
				children = this.el.children,
				i = 0,
R
RubaXa 已提交
568
				n = children.length;
569 570 571

			for (; i < n; i++) {
				el = children[i];
R
RubaXa 已提交
572 573 574
				if (_closest(el, this.options.draggable, this.el)) {
					order.push(el.getAttribute('data-id') || _generateId(el));
				}
575 576 577 578 579 580 581 582 583 584 585
			}

			return order;
		},


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

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

R
RubaXa 已提交
591
				if (_closest(el, this.options.draggable, rootEl)) {
R
RubaXa 已提交
592 593 594
					items[id] = el;
				}
			}, this);
595 596 597 598


			order.forEach(function (id) {
				if (items[id]) {
R
RubaXa 已提交
599 600
					rootEl.removeChild(items[id]);
					rootEl.appendChild(items[id]);
601 602 603 604 605
				}
			});
		},


606 607 608 609 610 611 612 613 614 615 616
		/**
		 * 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);
		},


617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
		/**
		 * 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;
			}
		},


634 635 636 637
		/**
		 * Destroy
		 */
		destroy: function () {
R
RubaXa 已提交
638 639
			var el = this.el, options = this.options;

640 641 642 643
			_customEvents.forEach(function (name) {
				_off(el, name.substr(2).toLowerCase(), options[name]);
			});

R
RubaXa 已提交
644 645
			_off(el, 'mousedown', this._onTapStart);
			_off(el, 'touchstart', this._onTapStart);
N
Nicolas 已提交
646
			_off(el, 'selectstart', this._onTapStart);
R
RubaXa 已提交
647 648 649 650

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

651
			//remove draggable attributes
R
RubaXa 已提交
652
			Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
653 654 655
				el.removeAttribute('draggable');
			});

R
RubaXa 已提交
656 657 658 659 660 661 662 663
			touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);

			this._onDrop();

			this.el = null;
		}
	};

664

R
RubaXa 已提交
665
	function _bind(ctx, fn) {
R
RubaXa 已提交
666
		var args = slice.call(arguments, 2);
R
RubaXa 已提交
667
		return	fn.bind ? fn.bind.apply(fn, [ctx].concat(args)) : function () {
R
RubaXa 已提交
668 669 670 671 672
			return fn.apply(ctx, args.concat(slice.call(arguments)));
		};
	}


R
RubaXa 已提交
673 674
	function _closest(el, selector, ctx) {
		if (selector === '*') {
R
RubaXa 已提交
675 676
			return el;
		}
R
RubaXa 已提交
677
		else if (el) {
R
RubaXa 已提交
678 679 680
			ctx = ctx || document;
			selector = selector.split('.');

R
RubaXa 已提交
681 682
			var tag = selector.shift().toUpperCase(),
				re = new RegExp('\\s(' + selector.join('|') + ')\\s', 'g');
R
RubaXa 已提交
683 684

			do {
R
RubaXa 已提交
685 686 687 688 689
				if (
					(tag === '' || el.nodeName == tag) &&
					(!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
				) {
					return el;
R
RubaXa 已提交
690 691
				}
			}
R
RubaXa 已提交
692
			while (el !== ctx && (el = el.parentNode));
R
RubaXa 已提交
693 694
		}

R
RubaXa 已提交
695
		return null;
R
RubaXa 已提交
696 697 698
	}


699
	function _globalDragOver(/**Event*/evt) {
R
RubaXa 已提交
700 701 702 703 704
		evt.dataTransfer.dropEffect = 'move';
		evt.preventDefault();
	}


R
RubaXa 已提交
705
	function _on(el, event, fn) {
R
RubaXa 已提交
706 707 708 709
		el.addEventListener(event, fn, false);
	}


R
RubaXa 已提交
710
	function _off(el, event, fn) {
R
RubaXa 已提交
711 712 713 714
		el.removeEventListener(event, fn, false);
	}


R
RubaXa 已提交
715 716 717
	function _toggleClass(el, name, state) {
		if (el) {
			if (el.classList) {
R
RubaXa 已提交
718 719 720
				el.classList[state ? 'add' : 'remove'](name);
			}
			else {
R
RubaXa 已提交
721 722
				var className = (' ' + el.className + ' ').replace(/\s+/g, ' ').replace(' ' + name + ' ', '');
				el.className = className + (state ? ' ' + name : '');
R
RubaXa 已提交
723 724 725 726 727
			}
		}
	}


R
RubaXa 已提交
728
	function _css(el, prop, val) {
R
RubaXa 已提交
729 730
		var style = el && el.style;

R
RubaXa 已提交
731 732 733
		if (style) {
			if (val === void 0) {
				if (document.defaultView && document.defaultView.getComputedStyle) {
R
RubaXa 已提交
734 735
					val = document.defaultView.getComputedStyle(el, '');
				}
R
RubaXa 已提交
736 737
				else if (el.currentStyle) {
					val = el.currentStyle;
R
RubaXa 已提交
738
				}
R
RubaXa 已提交
739 740 741 742 743 744 745 746 747

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

				style[prop] = val + (typeof val === 'string' ? '' : 'px');
R
RubaXa 已提交
748 749 750 751 752
			}
		}
	}


R
RubaXa 已提交
753 754
	function _find(ctx, tagName, iterator) {
		if (ctx) {
R
RubaXa 已提交
755
			var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
R
RubaXa 已提交
756

R
RubaXa 已提交
757 758
			if (iterator) {
				for (; i < n; i++) {
R
RubaXa 已提交
759 760 761
					iterator(list[i], i);
				}
			}
R
RubaXa 已提交
762

R
RubaXa 已提交
763
			return list;
R
RubaXa 已提交
764
		}
R
RubaXa 已提交
765 766

		return [];
R
RubaXa 已提交
767 768 769
	}


R
RubaXa 已提交
770
	function _disableDraggable(el) {
R
RubaXa 已提交
771
		el.draggable = false;
R
RubaXa 已提交
772 773 774
	}


R
RubaXa 已提交
775
	function _unsilent() {
R
RubaXa 已提交
776 777 778 779
		_silent = false;
	}


R
RubaXa 已提交
780
	/** @returns {HTMLElement|false} */
R
RubaXa 已提交
781
	function _ghostInBottom(el, evt) {
R
RubaXa 已提交
782 783
		var lastEl = el.lastElementChild, rect = lastEl.getBoundingClientRect();
		return (evt.clientY - (rect.top + rect.height) > 5) && lastEl; // min delta
R
RubaXa 已提交
784 785 786
	}


787 788 789 790 791 792 793
	/**
	 * Generate id
	 * @param   {HTMLElement} el
	 * @returns {String}
	 * @private
	 */
	function _generateId(el) {
R
RubaXa 已提交
794
		var str = el.tagName + el.className + el.src + el.href + el.textContent,
795
			i = str.length,
R
RubaXa 已提交
796
			sum = 0;
797

798 799 800
		while (i--) {
			sum += str.charCodeAt(i);
		}
801

802 803 804
		return sum.toString(36);
	}

805 806 807
	/**
	 * Returns the index of an element within its parent
	 * @param el
808 809
	 * @returns {number}
	 * @private
810 811 812
	 */
	function _index(/**HTMLElement*/el) {
		var index = 0;
813
		while (el && (el = el.previousElementSibling)) {
814 815 816 817
			index++;
		}
		return index;
	}
R
RubaXa 已提交
818 819 820 821 822 823 824 825 826

	// Export utils
	Sortable.utils = {
		on: _on,
		off: _off,
		css: _css,
		find: _find,
		bind: _bind,
		closest: _closest,
827
		toggleClass: _toggleClass,
828 829
		dispatchEvent: _dispatchEvent,
		index: _index
R
RubaXa 已提交
830 831 832
	};


833
	Sortable.version = '0.7.2';
834

R
RubaXa 已提交
835

836 837 838 839 840 841
	/**
	 * Create sortable instance
	 * @param {HTMLElement}  el
	 * @param {Object}      [options]
	 */
	Sortable.create = function (el, options) {
R
RubaXa 已提交
842
		return new Sortable(el, options);
843
	};
R
RubaXa 已提交
844 845

	// Export
846
	return Sortable;
R
RubaXa 已提交
847
});