You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

659 lines
15 KiB

11 years ago
/**!
* Sortable
* @author RubaXa <trash@rubaxa.org>
* @license MIT
*/
(function (factory){
"use strict";
if( typeof define === "function" && define.amd ){
11 years ago
define(factory);
11 years ago
}
else if( typeof module != "undefined" && typeof module.exports != "undefined" ){
module.exports = factory();
}
11 years ago
else {
window["Sortable"] = factory();
}
})(function (){
"use strict";
var
dragEl
11 years ago
, ghostEl
, rootEl
, nextEl
, lastEl
, lastCSS
, lastRect
11 years ago
, activeGroup
, tapEvt
, touchEvt
, expando = 'Sortable' + (new Date).getTime()
, win = window
, document = win.document
, parseInt = win.parseInt
, supportIEdnd = !!document.createElement('div').dragDrop
, _silent = false
, _createEvent = function (event/**String*/, item/**HTMLElement*/){
var evt = document.createEvent('Event');
evt.initEvent(event, true, true);
evt.item = item;
return evt;
}
11 years ago
, noop = function (){}
, slice = [].slice
, touchDragOverListeners = []
, pointerdown
, pointerup
, pointermove
, pointercancel
11 years ago
;
11 years ago
/**
* @class Sortable
* @param {HTMLElement} el
* @param {Object} [options]
11 years ago
*/
function Sortable(el, options){
this.el = el; // root element
this.options = options = (options || {});
// Defaults
options.group = options.group || Math.random();
options.store = options.store || null;
11 years ago
options.handle = options.handle || null;
options.draggable = options.draggable || el.children[0] && el.children[0].nodeName || (/[uo]l/i.test(el.nodeName) ? 'li' : '*');
11 years ago
options.ghostClass = options.ghostClass || 'sortable-ghost';
options.ignore = options.ignore || 'a, img';
11 years ago
options.onAdd = _bind(this, options.onAdd || noop);
options.onUpdate = _bind(this, options.onUpdate || noop);
options.onRemove = _bind(this, options.onRemove || noop);
options.onStart = _bind(this, options.onStart || noop);
options.onEnd = _bind(this, options.onEnd || noop);
11 years ago
11 years ago
// Export group name
11 years ago
el[expando] = options.group;
11 years ago
// Bind all private methods
11 years ago
for( var fn in this ){
if( fn.charAt(0) === '_' ){
this[fn] = _bind(this, this[fn]);
}
}
11 years ago
// Detect IE10/IE11+
if (window.onpointerdown !== undefined) {
pointerdown = 'pointerdown';
pointerup = 'pointerup';
pointermove = 'pointermove';
pointercancel = 'pointercancel';
} else {
pointerdown = 'MSPointerDown';
pointerup = 'MSPointerUp';
pointermove = 'MSPointerMove';
pointercancel = 'MSPointerCancel';
}
11 years ago
// Bind events
_on(el, 'add', options.onAdd);
_on(el, 'update', options.onUpdate);
_on(el, 'remove', options.onRemove);
_on(el, 'start', options.onStart);
_on(el, 'stop', options.onEnd);
11 years ago
_on(el, 'mousedown', this._onTapStart);
_on(el, 'touchstart', this._onTapStart);
supportIEdnd && _on(el, 'selectstart', this._onTapStart);
11 years ago
_on(el, 'dragover', this._onDragOver);
_on(el, 'dragenter', this._onDragOver);
11 years ago
_on(el, pointerdown, this._onTapStart);
11 years ago
11 years ago
_css(el, 'touch-action', 'none');
_css(el, '-ms-touch-action', 'none');
11 years ago
touchDragOverListeners.push(this._onDragOver);
// Restore sorting
options.store && this.sort(options.store.get(this));
11 years ago
}
Sortable.prototype = /** @lends Sortable.prototype */ {
11 years ago
constructor: Sortable,
_applyEffects: function (){
_toggleClass(dragEl, this.options.ghostClass, true);
},
_onTapStart: function (evt/**Event|TouchEvent|PointerEvent*/){
11 years ago
var
touch = evt.touches && evt.touches[0]
11 years ago
, target = (touch || evt).target
, options = this.options
11 years ago
, el = this.el
11 years ago
;
if( options.handle ){
11 years ago
target = _closest(target, options.handle, el);
11 years ago
}
11 years ago
target = _closest(target, options.draggable, el);
11 years ago
// IE 9 Support
if( target && evt.type == 'selectstart' ){
if( target.tagName != 'A' && target.tagName != 'IMG'){
target.dragDrop();
}
}
if( target && !dragEl && (target.parentNode === el) ){
11 years ago
tapEvt = evt;
target.draggable = true;
// Disable "draggable"
Array.prototype.forEach.call(options.ignore.split(','), function (criteria) {
_find(target, criteria.trim(), _disableDraggable);
});
11 years ago
if( touch ){
// Touch device support
tapEvt = {
target: target
11 years ago
, clientX: touch.clientX
, clientY: touch.clientY
};
this._onDragStart(tapEvt, true);
evt.preventDefault();
}
11 years ago
if (evt.type == 'pointerdown' || evt.type == 'MSPointerDown') {
this._onDragStart(tapEvt, true);
evt.preventDefault();
}
11 years ago
_on(this.el, 'dragstart', this._onDragStart);
11 years ago
_on(this.el, 'dragend', this._onDrop);
11 years ago
_on(document, 'dragover', _globalDragOver);
try {
if( document.selection ){
document.selection.empty();
} else {
window.getSelection().removeAllRanges()
}
} catch (err){ }
}
},
_emulateDragOver: function (){
if( touchEvt ){
_css(ghostEl, 'display', 'none');
var
target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY)
11 years ago
, parent = target
, group = this.options.group
, i = touchDragOverListeners.length
;
11 years ago
if( parent ){
do {
if( parent[expando] === group ){
while( i-- ){
touchDragOverListeners[i]({
clientX: touchEvt.clientX,
clientY: touchEvt.clientY,
target: target,
rootEl: parent
});
}
break;
11 years ago
}
11 years ago
target = parent; // store last element
}
while( parent = parent.parentNode );
11 years ago
}
_css(ghostEl, 'display', '');
}
},
11 years ago
_onTouchMove: function (evt/**TouchEvent|PointerEvent*/){
11 years ago
if( tapEvt ){
var
touch = evt.touches[0]
11 years ago
, dx = touch.clientX - tapEvt.clientX
, dy = touch.clientY - tapEvt.clientY
;
touchEvt = touch;
_css(ghostEl, 'webkitTransform', 'translate3d('+dx+'px,'+dy+'px,0)');
11 years ago
_css(ghostEl, 'mozTransform', 'translate3d('+dx+'px,'+dy+'px,0)');
_css(ghostEl, 'msTransform', 'translate3d('+dx+'px,'+dy+'px,0)');
_css(ghostEl, 'transform', 'translate3d('+dx+'px,'+dy+'px,0)');
11 years ago
evt.preventDefault();
11 years ago
}
},
11 years ago
_onDragStart: function (evt/**Event*/, isTouch/**Boolean*/){
11 years ago
var
target = evt.target
11 years ago
, dataTransfer = evt.dataTransfer
;
rootEl = this.el;
dragEl = target;
nextEl = target.nextSibling;
activeGroup = this.options.group;
if( isTouch ){
11 years ago
var
rect = target.getBoundingClientRect()
11 years ago
, css = _css(target)
, ghostRect
;
11 years ago
ghostEl = target.cloneNode(true);
_css(ghostEl, 'top', rect.top - parseInt(css.marginTop, 10));
_css(ghostEl, 'left', rect.left - parseInt(css.marginLeft, 10));
11 years ago
_css(ghostEl, 'width', rect.width);
_css(ghostEl, 'height', rect.height);
11 years ago
_css(ghostEl, 'opacity', '0.8');
_css(ghostEl, 'position', 'fixed');
_css(ghostEl, 'zIndex', '100000');
11 years ago
rootEl.appendChild(ghostEl);
// Fixing dimensions.
ghostRect = ghostEl.getBoundingClientRect();
_css(ghostEl, 'width', rect.width*2 - ghostRect.width);
_css(ghostEl, 'height', rect.height*2 - ghostRect.height);
11 years ago
// Bind touch events
_on(document, 'touchmove', this._onTouchMove);
_on(document, 'touchend', this._onDrop);
_on(document, 'touchcancel', this._onDrop);
11 years ago
_on(document, pointermove, this._onTouchMove);
_on(document, pointerup, this._onDrop);
_on(document, pointercancel, this._onDrop);
11 years ago
this._loopId = setInterval(this._emulateDragOver, 150);
11 years ago
}
else {
dataTransfer.effectAllowed = 'move';
dataTransfer.setData('Text', target.textContent);
_on(document, 'drop', this._onDrop);
}
dragEl.dispatchEvent(_createEvent('start', dragEl));
11 years ago
setTimeout(this._applyEffects);
},
11 years ago
_onDragOver: function (evt/**Event*/){
if( !_silent && (activeGroup === this.options.group) && (evt.rootEl === void 0 || evt.rootEl === this.el) ){
11 years ago
var
el = this.el
11 years ago
, target = _closest(evt.target, this.options.draggable, el)
;
if( el.children.length === 0 || el.children[0] === ghostEl || (el === evt.target) && _ghostInBottom(el, evt) ){
el.appendChild(dragEl);
}
else if( target && target !== dragEl && (target.parentNode[expando] !== void 0) ){
if( lastEl !== target ){
lastEl = target;
lastCSS = _css(target);
lastRect = target.getBoundingClientRect();
11 years ago
}
var
rect = lastRect
, width = rect.right - rect.left
, height = rect.bottom - rect.top
, floating = /left|right|inline/.test(lastCSS.cssFloat + lastCSS.display)
, skew = (floating ? (evt.clientX - rect.left)/width : (evt.clientY - rect.top)/height) > .5
, isWide = (target.offsetWidth > dragEl.offsetWidth)
, isLong = (target.offsetHeight > dragEl.offsetHeight)
, nextSibling = target.nextSibling
, after
;
_silent = true;
setTimeout(_unsilent, 30);
if( floating ){
after = (target.previousElementSibling === dragEl) && !isWide || (skew > .5) && isWide
} else {
after = (target.nextElementSibling !== dragEl) && !isLong || (skew > .5) && isLong;
}
if( after && !nextSibling ){
el.appendChild(dragEl);
} else {
target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
11 years ago
}
}
}
},
_onDrop: function (evt/**Event*/){
clearInterval(this._loopId);
// Unbind events
_off(document, 'drop', this._onDrop);
_off(document, 'dragover', _globalDragOver);
11 years ago
_off(this.el, 'dragend', this._onDrop);
11 years ago
_off(this.el, 'dragstart', this._onDragStart);
_off(this.el, 'selectstart', this._onTapStart);
11 years ago
_off(document, 'touchmove', this._onTouchMove);
_off(document, 'touchend', this._onDrop);
_off(document, 'touchcancel', this._onDrop);
11 years ago
_off(document, pointermove, this._onTouchMove);
_off(document, pointerup, this._onDrop);
_off(document, pointercancel, this._onDrop);
11 years ago
if( evt ){
evt.preventDefault();
evt.stopPropagation();
11 years ago
11 years ago
if( ghostEl ){
ghostEl.parentNode.removeChild(ghostEl);
}
11 years ago
if( dragEl ){
_disableDraggable(dragEl);
11 years ago
_toggleClass(dragEl, this.options.ghostClass, false);
if( !rootEl.contains(dragEl) ){
// Remove event
rootEl.dispatchEvent(_createEvent('remove', dragEl));
11 years ago
// Add event
dragEl.dispatchEvent(_createEvent('add', dragEl));
11 years ago
}
else if( dragEl.nextSibling !== nextEl ){
// Update event
dragEl.dispatchEvent(_createEvent('update', dragEl));
11 years ago
}
dragEl.dispatchEvent(_createEvent('stop', dragEl));
11 years ago
}
// Set NULL
rootEl =
dragEl =
ghostEl =
nextEl =
tapEvt =
touchEvt =
lastEl =
lastCSS =
activeGroup = null;
// Save sorting
this.options.store && this.options.store.set(this);
11 years ago
}
},
/**
* Serializes the item into an array of string.
* @returns {String[]}
*/
toArray: function () {
var order = [],
el,
children = this.el.children,
i = 0,
n = children.length
;
for (; i < n; i++) {
el = children[i];
order.push(el.getAttribute('data-id') || _generateId(el));
}
return order;
},
/**
* Sorts the elements according to the array.
* @param {String[]} order order of the items
*/
sort: function (order) {
var items = {}, el = this.el;
this.toArray().forEach(function (id, i) {
items[id] = el.children[i];
});
order.forEach(function (id) {
if (items[id]) {
el.removeChild(items[id]);
el.appendChild(items[id]);
}
});
},
/**
* Destroy
*/
destroy: function () {
11 years ago
var el = this.el, options = this.options;
_off(el, 'add', options.onAdd);
_off(el, 'update', options.onUpdate);
_off(el, 'remove', options.onRemove);
_off(el, 'start', options.onStart);
_off(el, 'stop', options.onEnd);
11 years ago
_off(el, 'mousedown', this._onTapStart);
_off(el, 'touchstart', this._onTapStart);
_off(el, 'selectstart', this._onTapStart);
11 years ago
_off(el, pointerdown, this._onTapStart);
11 years ago
_off(el, 'dragover', this._onDragOver);
_off(el, 'dragenter', this._onDragOver);
//remove draggable attributes
Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function(el) {
el.removeAttribute('draggable');
});
11 years ago
touchDragOverListeners.splice(touchDragOverListeners.indexOf(this._onDragOver), 1);
this._onDrop();
this.el = null;
}
};
11 years ago
function _bind(ctx, fn){
var args = slice.call(arguments, 2);
return fn.bind ? fn.bind.apply(fn, [ctx].concat(args)) : function (){
return fn.apply(ctx, args.concat(slice.call(arguments)));
};
}
function _closest(el, selector, ctx){
if( selector === '*' ){
return el;
}
else if( el ){
11 years ago
ctx = ctx || document;
selector = selector.split('.');
var
tag = selector.shift().toUpperCase()
11 years ago
, re = new RegExp('\\s('+selector.join('|')+')\\s', 'g')
11 years ago
;
do {
if(
(tag === '' || el.nodeName == tag)
11 years ago
&& (!selector.length || ((' '+el.className+' ').match(re) || []).length == selector.length)
11 years ago
){
return el;
}
}
while( el !== ctx && (el = el.parentNode) );
}
return null;
}
function _globalDragOver(evt){
evt.dataTransfer.dropEffect = 'move';
evt.preventDefault();
}
function _on(el, event, fn){
el.addEventListener(event, fn, false);
}
function _off(el, event, fn){
el.removeEventListener(event, fn, false);
}
function _toggleClass(el, name, state){
if( el ){
if( el.classList ){
el.classList[state ? 'add' : 'remove'](name);
}
else {
11 years ago
var className = (' '+el.className+' ').replace(/\s+/g, ' ').replace(' '+name+' ', '');
11 years ago
el.className = className + (state ? ' '+name : '')
}
}
}
function _css(el, prop, val){
if( el && el.style ){
if( val === void 0 ){
if( document.defaultView && document.defaultView.getComputedStyle ){
val = document.defaultView.getComputedStyle(el, '');
}
else if( el.currentStyle ){
val = el.currentStyle;
}
return prop === void 0 ? val : val[prop];
} else {
el.style[prop] = val + (typeof val === 'string' ? '' : 'px');
}
}
}
function _find(ctx, tagName, iterator){
if( ctx ){
var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
if( iterator ){
for( ; i < n; i++ ){
iterator(list[i], i);
}
}
return list;
}
return [];
}
function _disableDraggable(el){
return el.draggable = false;
}
function _unsilent(){
_silent = false;
}
function _ghostInBottom(el, evt){
var last = el.lastElementChild.getBoundingClientRect();
return evt.clientY - (last.top + last.height) > 5; // min delta
}
/**
* Generate id
* @param {HTMLElement} el
* @returns {String}
* @private
*/
function _generateId(el) {
var str = el.innerHTML + el.className + el.src,
i = str.length,
sum = 0
;
while (i--) {
sum += str.charCodeAt(i);
}
return sum.toString(36);
}
11 years ago
// Export utils
Sortable.utils = {
on: _on,
off: _off,
css: _css,
find: _find,
bind: _bind,
closest: _closest,
toggleClass: _toggleClass
};
Sortable.version = '0.4.0';
11 years ago
// Export
return Sortable;
});