Browse Source

+ code style

pull/126/merge
RubaXa 10 years ago
parent
commit
386c659903
  1. 301
      Sortable.js

301
Sortable.js

@ -5,49 +5,49 @@
*/ */
(function (factory){ (function (factory) {
"use strict"; "use strict";
if( typeof define === "function" && define.amd ){ if (typeof define === "function" && define.amd) {
define(factory); define(factory);
} }
else if( typeof module != "undefined" && typeof module.exports != "undefined" ){ else if (typeof module != "undefined" && typeof module.exports != "undefined") {
module.exports = factory(); module.exports = factory();
} }
else if( typeof Package !== "undefined" ){ else if (typeof Package !== "undefined") {
Sortable = factory(); // export for Meteor.js Sortable = factory(); // export for Meteor.js
} }
else { else {
/* jshint sub:true */
window["Sortable"] = factory(); window["Sortable"] = factory();
} }
})(function (){ })(function () {
"use strict"; "use strict";
var var dragEl,
dragEl ghostEl,
, ghostEl cloneEl,
, cloneEl rootEl,
, rootEl nextEl,
, nextEl
, lastEl lastEl,
, lastCSS lastCSS,
, activeGroup activeGroup,
, tapEvt tapEvt,
, touchEvt touchEvt,
, expando = 'Sortable' + (new Date).getTime() expando = 'Sortable' + (new Date).getTime(),
, win = window win = window,
, document = win.document document = win.document,
, parseInt = win.parseInt parseInt = win.parseInt,
, supportIEdnd = !!document.createElement('div').dragDrop supportIEdnd = !!document.createElement('div').dragDrop,
, _silent = false _silent = false,
, _dispatchEvent = function (rootEl, name, targetEl, fromEl) { _dispatchEvent = function (rootEl, name, targetEl, fromEl) {
var evt = document.createEvent('Event'); var evt = document.createEvent('Event');
evt.initEvent(name, true, true); evt.initEvent(name, true, true);
@ -55,14 +55,14 @@
evt.from = fromEl || rootEl; evt.from = fromEl || rootEl;
rootEl.dispatchEvent(evt); rootEl.dispatchEvent(evt);
} },
, _customEvents = 'onAdd onUpdate onRemove onStart onEnd onFilter onSort'.split(' ') _customEvents = 'onAdd onUpdate onRemove onStart onEnd onFilter onSort'.split(' '),
, noop = function (){} noop = function () {},
, slice = [].slice slice = [].slice,
, touchDragOverListeners = [] touchDragOverListeners = []
; ;
@ -72,7 +72,7 @@
* @param {HTMLElement} el * @param {HTMLElement} el
* @param {Object} [options] * @param {Object} [options]
*/ */
function Sortable(el, options){ function Sortable(el, options) {
this.el = el; // root element this.el = el; // root element
this.options = options = (options || {}); this.options = options = (options || {});
@ -124,8 +124,8 @@
// Bind all private methods // Bind all private methods
for( var fn in this ){ for (var fn in this) {
if( fn.charAt(0) === '_' ){ if (fn.charAt(0) === '_') {
this[fn] = _bind(this, this[fn]); this[fn] = _bind(this, this[fn]);
} }
} }
@ -150,32 +150,31 @@
constructor: Sortable, constructor: Sortable,
_applyEffects: function (){ _applyEffects: function () {
_toggleClass(dragEl, this.options.ghostClass, true); _toggleClass(dragEl, this.options.ghostClass, true);
}, },
_onTapStart: function (evt/**Event|TouchEvent*/){ _onTapStart: function (/**Event|TouchEvent*/evt) {
var var touch = evt.touches && evt.touches[0],
touch = evt.touches && evt.touches[0] target = (touch || evt).target,
, target = (touch || evt).target options = this.options,
, options = this.options el = this.el,
, el = this.el filter = options.filter;
, filter = options.filter
;
if( evt.type === 'mousedown' && evt.button !== 0 ) { if (evt.type === 'mousedown' && evt.button !== 0) {
return; // only left button return; // only left button
} }
// Check filter // Check filter
if( typeof filter === 'function' ){ if (typeof filter === 'function') {
if( filter.call(this, target, this) ){ if (filter.call(this, target, this)) {
_dispatchEvent(el, 'filter', target); _dispatchEvent(el, 'filter', target);
return; // cancel dnd return; // cancel dnd
} }
} }
else if( filter ){ else if (filter) {
filter = filter.split(',').filter(function (criteria) { filter = filter.split(',').filter(function (criteria) {
return _closest(target, criteria.trim(), el); return _closest(target, criteria.trim(), el);
}); });
@ -186,20 +185,20 @@
} }
} }
if( options.handle ){ if (options.handle) {
target = _closest(target, options.handle, el); target = _closest(target, options.handle, el);
} }
target = _closest(target, options.draggable, el); target = _closest(target, options.draggable, el);
// IE 9 Support // IE 9 Support
if( target && evt.type == 'selectstart' ){ if (target && evt.type == 'selectstart') {
if( target.tagName != 'A' && target.tagName != 'IMG'){ if (target.tagName != 'A' && target.tagName != 'IMG') {
target.dragDrop(); target.dragDrop();
} }
} }
if( target && !dragEl && (target.parentNode === el) ){ if (target && !dragEl && (target.parentNode === el)) {
tapEvt = evt; tapEvt = evt;
rootEl = this.el; rootEl = this.el;
@ -214,12 +213,12 @@
_find(target, criteria.trim(), _disableDraggable); _find(target, criteria.trim(), _disableDraggable);
}); });
if( touch ){ if (touch) {
// Touch device support // Touch device support
tapEvt = { tapEvt = {
target: target target: target,
, clientX: touch.clientX clientX: touch.clientX,
, clientY: touch.clientY clientY: touch.clientY
}; };
this._onDragStart(tapEvt, true); this._onDragStart(tapEvt, true);
@ -236,12 +235,13 @@
try { try {
if( document.selection ){ if (document.selection) {
document.selection.empty(); document.selection.empty();
} else { } else {
window.getSelection().removeAllRanges() window.getSelection().removeAllRanges();
} }
} catch (err){ } } catch (err) {
}
_dispatchEvent(dragEl, 'start'); _dispatchEvent(dragEl, 'start');
@ -255,21 +255,19 @@
} }
}, },
_emulateDragOver: function (){ _emulateDragOver: function () {
if( touchEvt ){ if (touchEvt) {
_css(ghostEl, 'display', 'none'); _css(ghostEl, 'display', 'none');
var var target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY),
target = document.elementFromPoint(touchEvt.clientX, touchEvt.clientY) parent = target,
, parent = target groupName = this.options.group.name,
, groupName = this.options.group.name i = touchDragOverListeners.length;
, i = touchDragOverListeners.length
;
if( parent ){ if (parent) {
do { do {
if( parent[expando] === groupName ){ if (parent[expando] === groupName) {
while( i-- ){ while (i--) {
touchDragOverListeners[i]({ touchDragOverListeners[i]({
clientX: touchEvt.clientX, clientX: touchEvt.clientX,
clientY: touchEvt.clientY, clientY: touchEvt.clientY,
@ -277,12 +275,14 @@
rootEl: parent rootEl: parent
}); });
} }
break; break;
} }
target = parent; // store last element target = parent; // store last element
} }
while( parent = parent.parentNode ); /* jshint boss:true */
while (parent = parent.parentNode);
} }
_css(ghostEl, 'display', ''); _css(ghostEl, 'display', '');
@ -290,14 +290,12 @@
}, },
_onTouchMove: function (evt/**TouchEvent*/){ _onTouchMove: function (/**TouchEvent*/evt) {
if( tapEvt ){ if (tapEvt) {
var var touch = evt.touches[0],
touch = evt.touches[0] dx = touch.clientX - tapEvt.clientX,
, dx = touch.clientX - tapEvt.clientX dy = touch.clientY - tapEvt.clientY,
, dy = touch.clientY - tapEvt.clientY translate3d = 'translate3d(' + dx + 'px,' + dy + 'px,0)';
, translate3d = 'translate3d(' + dx + 'px,' + dy + 'px,0)'
;
touchEvt = touch; touchEvt = touch;
@ -311,18 +309,16 @@
}, },
_onDragStart: function (evt/**Event*/, isTouch/**Boolean*/){ _onDragStart: function (/**Event*/evt, /**boolean*/isTouch) {
var dataTransfer = evt.dataTransfer, var dataTransfer = evt.dataTransfer,
options = this.options; options = this.options;
this._offUpEvents(); this._offUpEvents();
if( isTouch ){ if (isTouch) {
var var rect = dragEl.getBoundingClientRect(),
rect = dragEl.getBoundingClientRect() css = _css(dragEl),
, css = _css(dragEl) ghostRect;
, ghostRect
;
ghostEl = dragEl.cloneNode(true); ghostEl = dragEl.cloneNode(true);
@ -338,8 +334,8 @@
// Fixing dimensions. // Fixing dimensions.
ghostRect = ghostEl.getBoundingClientRect(); ghostRect = ghostEl.getBoundingClientRect();
_css(ghostEl, 'width', rect.width*2 - ghostRect.width); _css(ghostEl, 'width', rect.width * 2 - ghostRect.width);
_css(ghostEl, 'height', rect.height*2 - ghostRect.height); _css(ghostEl, 'height', rect.height * 2 - ghostRect.height);
// Bind touch events // Bind touch events
_on(document, 'touchmove', this._onTouchMove); _on(document, 'touchmove', this._onTouchMove);
@ -359,7 +355,7 @@
}, },
_onDragOver: function (evt/**Event*/){ _onDragOver: function (/**Event*/evt) {
var el = this.el, var el = this.el,
target, target,
dragRect, dragRect,
@ -369,11 +365,11 @@
groupPut = group.put, groupPut = group.put,
isOwner = (activeGroup === group); isOwner = (activeGroup === group);
if( !_silent && if (!_silent &&
(activeGroup.name === group.name || groupPut && groupPut.indexOf && groupPut.indexOf(activeGroup.name) > -1) && (activeGroup.name === group.name || groupPut && groupPut.indexOf && groupPut.indexOf(activeGroup.name) > -1) &&
(isOwner && (options.sort || (revert = !rootEl.contains(dragEl))) || groupPut && activeGroup.pull) && (isOwner && (options.sort || (revert = !rootEl.contains(dragEl))) || groupPut && activeGroup.pull) &&
(evt.rootEl === void 0 || evt.rootEl === this.el) (evt.rootEl === void 0 || evt.rootEl === this.el)
){ ) {
target = _closest(evt.target, this.options.draggable, el); target = _closest(evt.target, this.options.draggable, el);
dragRect = dragEl.getBoundingClientRect(); dragRect = dragEl.getBoundingClientRect();
@ -388,43 +384,43 @@
return; return;
} }
if( (el.children.length === 0) || (el.children[0] === ghostEl) || if ((el.children.length === 0) || (el.children[0] === ghostEl) ||
(el === evt.target) && _ghostInBottom(el, evt) (el === evt.target) && _ghostInBottom(el, evt)
){ ) {
target && (targetRect = target.getBoundingClientRect()); target && (targetRect = target.getBoundingClientRect());
el.appendChild(dragEl); el.appendChild(dragEl);
this._animate(dragRect, dragEl); this._animate(dragRect, dragEl);
target && this._animate(targetRect, target); target && this._animate(targetRect, target);
} }
else if( target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0) ){ else if (target && !target.animated && target !== dragEl && (target.parentNode[expando] !== void 0)) {
if( lastEl !== target ){ if (lastEl !== target) {
lastEl = target; lastEl = target;
lastCSS = _css(target); lastCSS = _css(target);
} }
var targetRect = target.getBoundingClientRect() var targetRect = target.getBoundingClientRect(),
, width = targetRect.right - targetRect.left width = targetRect.right - targetRect.left,
, height = targetRect.bottom - targetRect.top height = targetRect.bottom - targetRect.top,
, floating = /left|right|inline/.test(lastCSS.cssFloat + lastCSS.display) floating = /left|right|inline/.test(lastCSS.cssFloat + lastCSS.display),
, isWide = (target.offsetWidth > dragEl.offsetWidth) isWide = (target.offsetWidth > dragEl.offsetWidth),
, isLong = (target.offsetHeight > dragEl.offsetHeight) isLong = (target.offsetHeight > dragEl.offsetHeight),
, halfway = (floating ? (evt.clientX - targetRect.left)/width : (evt.clientY - targetRect.top)/height) > .5 halfway = (floating ? (evt.clientX - targetRect.left) / width : (evt.clientY - targetRect.top) / height) > 0.5,
, nextSibling = target.nextElementSibling nextSibling = target.nextElementSibling,
, after after
; ;
_silent = true; _silent = true;
setTimeout(_unsilent, 30); setTimeout(_unsilent, 30);
if( floating ){ if (floating) {
after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide after = (target.previousElementSibling === dragEl) && !isWide || halfway && isWide;
} else { } else {
after = (nextSibling !== dragEl) && !isLong || halfway && isLong; after = (nextSibling !== dragEl) && !isLong || halfway && isLong;
} }
if( after && !nextSibling ){ if (after && !nextSibling) {
el.appendChild(dragEl); el.appendChild(dragEl);
} else { } else {
target.parentNode.insertBefore(dragEl, after ? nextSibling : target); target.parentNode.insertBefore(dragEl, after ? nextSibling : target);
@ -468,7 +464,7 @@
_off(document, 'touchcancel', this._onDrop); _off(document, 'touchcancel', this._onDrop);
}, },
_onDrop: function (evt/**Event*/){ _onDrop: function (/**Event*/evt) {
clearInterval(this._loopId); clearInterval(this._loopId);
// Unbind events // Unbind events
@ -481,17 +477,17 @@
this._offUpEvents(); this._offUpEvents();
if( evt ){ if (evt) {
evt.preventDefault(); evt.preventDefault();
evt.stopPropagation(); evt.stopPropagation();
ghostEl && ghostEl.parentNode.removeChild(ghostEl); ghostEl && ghostEl.parentNode.removeChild(ghostEl);
if( dragEl ){ if (dragEl) {
_disableDraggable(dragEl); _disableDraggable(dragEl);
_toggleClass(dragEl, this.options.ghostClass, false); _toggleClass(dragEl, this.options.ghostClass, false);
if( !rootEl.contains(dragEl) ){ if (!rootEl.contains(dragEl)) {
_dispatchEvent(dragEl, 'sort'); _dispatchEvent(dragEl, 'sort');
_dispatchEvent(rootEl, 'sort'); _dispatchEvent(rootEl, 'sort');
@ -501,7 +497,7 @@
// Remove event // Remove event
_dispatchEvent(rootEl, 'remove', dragEl); _dispatchEvent(rootEl, 'remove', dragEl);
} }
else if( dragEl.nextSibling !== nextEl ){ else if (dragEl.nextSibling !== nextEl) {
// Update event // Update event
_dispatchEvent(dragEl, 'update'); _dispatchEvent(dragEl, 'update');
_dispatchEvent(dragEl, 'sort'); _dispatchEvent(dragEl, 'sort');
@ -542,8 +538,7 @@
el, el,
children = this.el.children, children = this.el.children,
i = 0, i = 0,
n = children.length n = children.length;
;
for (; i < n; i++) { for (; i < n; i++) {
el = children[i]; el = children[i];
@ -610,7 +605,7 @@
_off(el, 'dragenter', this._onDragOver); _off(el, 'dragenter', this._onDragOver);
//remove draggable attributes //remove draggable attributes
Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function(el) { Array.prototype.forEach.call(el.querySelectorAll('[draggable]'), function (el) {
el.removeAttribute('draggable'); el.removeAttribute('draggable');
}); });
@ -623,81 +618,79 @@
}; };
function _bind(ctx, fn){ function _bind(ctx, fn) {
var args = slice.call(arguments, 2); var args = slice.call(arguments, 2);
return fn.bind ? fn.bind.apply(fn, [ctx].concat(args)) : function (){ return fn.bind ? fn.bind.apply(fn, [ctx].concat(args)) : function () {
return fn.apply(ctx, args.concat(slice.call(arguments))); return fn.apply(ctx, args.concat(slice.call(arguments)));
}; };
} }
function _closest(el, selector, ctx){ function _closest(el, selector, ctx) {
if( selector === '*' ){ if (selector === '*') {
return el; return el;
} }
else if( el ){ else if (el) {
ctx = ctx || document; ctx = ctx || document;
selector = selector.split('.'); selector = selector.split('.');
var var tag = selector.shift().toUpperCase(),
tag = selector.shift().toUpperCase() re = new RegExp('\\s(' + selector.join('|') + ')\\s', 'g');
, re = new RegExp('\\s('+selector.join('|')+')\\s', 'g')
;
do { do {
if( if (
(tag === '' || el.nodeName == tag) (tag === '' || el.nodeName == tag) &&
&& (!selector.length || ((' '+el.className+' ').match(re) || []).length == selector.length) (!selector.length || ((' ' + el.className + ' ').match(re) || []).length == selector.length)
){ ) {
return el; return el;
} }
} }
while( el !== ctx && (el = el.parentNode) ); while (el !== ctx && (el = el.parentNode));
} }
return null; return null;
} }
function _globalDragOver(evt){ function _globalDragOver(evt) {
evt.dataTransfer.dropEffect = 'move'; evt.dataTransfer.dropEffect = 'move';
evt.preventDefault(); evt.preventDefault();
} }
function _on(el, event, fn){ function _on(el, event, fn) {
el.addEventListener(event, fn, false); el.addEventListener(event, fn, false);
} }
function _off(el, event, fn){ function _off(el, event, fn) {
el.removeEventListener(event, fn, false); el.removeEventListener(event, fn, false);
} }
function _toggleClass(el, name, state){ function _toggleClass(el, name, state) {
if( el ){ if (el) {
if( el.classList ){ if (el.classList) {
el.classList[state ? 'add' : 'remove'](name); el.classList[state ? 'add' : 'remove'](name);
} }
else { else {
var className = (' '+el.className+' ').replace(/\s+/g, ' ').replace(' '+name+' ', ''); var className = (' ' + el.className + ' ').replace(/\s+/g, ' ').replace(' ' + name + ' ', '');
el.className = className + (state ? ' '+name : '') el.className = className + (state ? ' ' + name : '');
} }
} }
} }
function _css(el, prop, val){ function _css(el, prop, val) {
var style = el && el.style; var style = el && el.style;
if( style ){ if (style) {
if( val === void 0 ){ if (val === void 0) {
if( document.defaultView && document.defaultView.getComputedStyle ){ if (document.defaultView && document.defaultView.getComputedStyle) {
val = document.defaultView.getComputedStyle(el, ''); val = document.defaultView.getComputedStyle(el, '');
} }
else if( el.currentStyle ){ else if (el.currentStyle) {
val = el.currentStyle; val = el.currentStyle;
} }
return prop === void 0 ? val : val[prop]; return prop === void 0 ? val : val[prop];
@ -713,31 +706,32 @@
} }
function _find(ctx, tagName, iterator){ function _find(ctx, tagName, iterator) {
if( ctx ){ if (ctx) {
var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length; var list = ctx.getElementsByTagName(tagName), i = 0, n = list.length;
if( iterator ){ if (iterator) {
for( ; i < n; i++ ){ for (; i < n; i++) {
iterator(list[i], i); iterator(list[i], i);
} }
} }
return list; return list;
} }
return [];
return [];
} }
function _disableDraggable(el){ function _disableDraggable(el) {
return el.draggable = false; return (el.draggable = false);
} }
function _unsilent(){ function _unsilent() {
_silent = false; _silent = false;
} }
function _ghostInBottom(el, evt){ function _ghostInBottom(el, evt) {
var last = el.lastElementChild.getBoundingClientRect(); var last = el.lastElementChild.getBoundingClientRect();
return evt.clientY - (last.top + last.height) > 5; // min delta return evt.clientY - (last.top + last.height) > 5; // min delta
} }
@ -752,8 +746,7 @@
function _generateId(el) { function _generateId(el) {
var str = el.tagName + el.className + el.src + el.href + el.textContent, var str = el.tagName + el.className + el.src + el.href + el.textContent,
i = str.length, i = str.length,
sum = 0 sum = 0;
;
while (i--) { while (i--) {
sum += str.charCodeAt(i); sum += str.charCodeAt(i);
@ -785,7 +778,7 @@
* @param {Object} [options] * @param {Object} [options]
*/ */
Sortable.create = function (el, options) { Sortable.create = function (el, options) {
return new Sortable(el, options) return new Sortable(el, options);
}; };
// Export // Export

Loading…
Cancel
Save