Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

draggable-helper

Package Overview
Dependencies
Maintainers
1
Versions
45
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

draggable-helper - npm Package Compare versions

Comparing version 1.0.20 to 1.1.1

dist/draggable-helper.esm.js

109

dist/draggable-helper.cjs.js
/*!
* draggable-helper v1.0.20
* (c) 2018-present phphe <phphe@outlook.com> (https://github.com/phphe)
* draggable-helper v1.1.1
* (c) phphe <phphe@outlook.com> (https://github.com/phphe)
* Released under the MIT License.

@@ -15,4 +15,4 @@ */

const destroy = draggableHelper(HTMLElement dragHandlerEl, Object opt = {})
opt.drag(e, opt, store)
[Object] opt.style || opt.getStyle(opt) set style of moving el style
opt.drag(startEvent, moveEvent, opt, store) return false to prevent drag
[Object] opt.style || opt.getStyle(opt, store) set style of moving el style
[Boolean] opt.clone

@@ -22,7 +22,11 @@ opt.draggingClass, default dragging

opt.drop(e, opt, store)
opt.getEl(dragHandlerEl, opt) get the el that will be moved. default is dragHandlerEl
opt.getEl(dragHandlerEl, opt, store) get the el that will be moved. default is dragHandlerEl
afterGetEl(startEvent, opt, store)
opt.minTranslate default 10, unit px
add other prop into opt, you get opt in callback
[Boolean] opt.triggerBySelf: false if trigger only by self, can not be triggered by children
add other prop into opt, you can get opt in callback
store{
el
originalEl
initialMouse

@@ -51,14 +55,14 @@ initialPosition

var IGNORE_TRIGGERS = ['INPUT', 'TEXTAREA', 'SELECT', 'OPTGROUP', 'OPTION'];
var UNDRAGGABLE_CLASS = 'undraggable';
function index (dragHandlerEl) {
var opt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (opt.minTranslate == null) {
opt.minTranslate = 10;
}
opt = Object.assign({
minTranslate: 10,
draggingClass: 'dragging'
}, opt);
var store = getPureStore();
var destroy = function destroy() {
DragEventService.off(dragHandlerEl, 'end', dragHandlerEl._draggbleEventHandler);
hp.offDOM(dragHandlerEl, 'selectstart', preventSelect);
DragEventService.off(dragHandlerEl, 'start', dragHandlerEl._draggbleEventHandler);
delete dragHandlerEl._draggbleEventHandler;

@@ -72,8 +76,35 @@ };

dragHandlerEl._draggbleEventHandler = start;
DragEventService.on(dragHandlerEl, 'start', dragHandlerEl._draggbleEventHandler);
hp.onDOM(dragHandlerEl, 'selectstart', preventSelect);
DragEventService.on(dragHandlerEl, 'start', start);
return destroy;
function start(e, mouse) {
// e.stopPropagation()
// detect draggable =================================
if (opt.triggerBySelf && e.target !== dragHandlerEl) {
return;
}
if (IGNORE_TRIGGERS.includes(e.target.tagName)) {
return;
}
if (hp.hasClass(e.target, UNDRAGGABLE_CLASS)) {
return;
}
var isParentUndraggable = hp.findParent(e.target, function (el) {
if (hp.hasClass(el, UNDRAGGABLE_CLASS)) {
return true;
}
if (el === dragHandlerEl) {
return 'break';
}
});
if (isParentUndraggable) {
return;
} // detect draggable end =================================
e.preventDefault();
store.mouse = {

@@ -83,7 +114,14 @@ x: mouse.x,

};
store.startEvent = e;
store.initialMouse = Object.assign({}, store.mouse);
/*
must set passive false for touch, else the follow error occurs in Chrome:
Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080
*/
DragEventService.on(document, 'move', moving, {
passive: false
}); // passive: false is for touchmove event
touchArgs: [{
passive: false
}]
});
DragEventService.on(window, 'end', drop);

@@ -93,2 +131,8 @@ }

function drag(e) {
var r = opt.drag && opt.drag(store.startEvent, e, opt, store);
if (r === false) {
return false;
}
var _resolveDragedElAndIn = resolveDragedElAndInitialPosition(),

@@ -100,9 +144,4 @@ el = _resolveDragedElAndIn.el,

store.initialPosition = Object.assign({}, position);
var r = opt.drag && opt.drag(e, opt, store);
opt.afterGetEl && opt.afterGetEl(e, opt, store); // dom actions
if (r === false) {
return false;
} // dom actions
var size = hp.getElSize(el);

@@ -117,3 +156,3 @@ var style = Object.assign({

top: position.y + 'px'
}, opt.style || opt.getStyle && opt.getStyle(opt) || {});
}, opt.style || opt.getStyle && opt.getStyle(opt, store) || {});
hp.backupAttr(el, 'style');

@@ -131,2 +170,3 @@

function moving(e, mouse) {
e.preventDefault();
store.mouse = {

@@ -158,7 +198,4 @@ x: mouse.x,

} // move started
// e.preventDefault() to prevent text selection and page scrolling when touch
e.preventDefault();
if (canMove && opt.moving) {

@@ -185,3 +222,5 @@ if (opt.moving(e, opt, store) === false) {

DragEventService.off(document, 'move', moving, {
passive: false
touchArgs: [{
passive: false
}]
});

@@ -209,7 +248,7 @@ DragEventService.off(window, 'end', drop); // drag executed if movedCount > 0

function resolveDragedElAndInitialPosition() {
var el0 = opt.getEl ? opt.getEl(dragHandlerEl, opt) : dragHandlerEl;
var el0 = opt.getEl ? opt.getEl(dragHandlerEl, opt, store) : dragHandlerEl;
var el = el0;
store.originalEl = el0;
if (opt.clone) {
store.triggerEl = el0;
el = el0.cloneNode(true);

@@ -220,3 +259,3 @@ el0.parentElement.appendChild(el);

return {
position: hp.getPosition(el),
position: hp.getPosition(el0),
el: el

@@ -231,8 +270,4 @@ };

}
function preventSelect(e) {
e.preventDefault();
}
}
module.exports = index;
/*!
* draggable-helper v1.0.20
* (c) 2018-present phphe <phphe@outlook.com> (https://github.com/phphe)
* draggable-helper v1.1.1
* (c) phphe <phphe@outlook.com> (https://github.com/phphe)
* Released under the MIT License.

@@ -9,131 +9,11 @@ */

typeof define === 'function' && define.amd ? define(factory) :
(global.draggableHelper = factory());
}(this, (function () { 'use strict';
(global = global || self, global['helper-js'] = factory());
}(this, function () { 'use strict';
/*!
* helper-js v1.3.7
* (c) 2018-present phphe <phphe@outlook.com> (https://github.com/phphe)
* helper-js v1.4.2
* (c) phphe <phphe@outlook.com> (https://github.com/phphe)
* Released under the MIT License.
*/
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _get(object, property, receiver) {
if (object === null) object = Function.prototype;
var desc = Object.getOwnPropertyDescriptor(object, property);
if (desc === undefined) {
var parent = Object.getPrototypeOf(object);
if (parent === null) {
return undefined;
} else {
return _get(parent, property, receiver);
}
} else if ("value" in desc) {
return desc.value;
} else {
var getter = desc.get;
if (getter === undefined) {
return undefined;
}
return getter.call(receiver);
}
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
}
return _assertThisInitialized(self);
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
return arr2;
}
}
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
// local store
var store = {}; // get global
function glb() {
if (store.glb) {
return store.glb;
} else {
// resolve global
var t;
try {
t = global;
} catch (e) {
t = window;
}
store.glb = t;
return t;
}
} // is 各种判断
function getOffsetParent(el) {

@@ -172,2 +52,17 @@ var offsetParent = el.offsetParent;

} // get position of a el if its offset is given. like jQuery.offset.
function findParent(el, callback, opt) {
var cur = opt && opt.withSelf ? el : el.parentElement;
while (cur) {
var r = callback(cur);
if (r === 'break') {
return;
} else if (r) {
return cur;
} else {
cur = cur.parentElement;
}
}
}
function backupAttr(el, name) {

@@ -210,2 +105,8 @@ var key = "original_".concat(name);

/*!
* helper-js v1.3.9
* (c) 2018-present phphe <phphe@outlook.com> (https://github.com/phphe)
* Released under the MIT License.
*/
function onDOM(el, name, handler) {

@@ -237,226 +138,29 @@ for (var _len5 = arguments.length, args = new Array(_len5 > 3 ? _len5 - 3 : 0), _key6 = 3; _key6 < _len5; _key6++) {

}
var URLHelper =
/*#__PURE__*/
function () {
// protocol, hostname, port, pastname
function URLHelper(baseUrl) {
var _this3 = this;
_classCallCheck(this, URLHelper);
/*!
* drag-event-service v1.0.0
* (c) 2018-present phphe <phphe@outlook.com> (https://github.com/phphe)
* Released under the MIT License.
*/
Object.defineProperty(this, "baseUrl", {
configurable: true,
enumerable: true,
writable: true,
value: ''
});
Object.defineProperty(this, "search", {
configurable: true,
enumerable: true,
writable: true,
value: {}
});
var t = decodeURI(baseUrl).split('?');
this.baseUrl = t[0];
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
}
if (t[1]) {
t[1].split('&').forEach(function (v) {
var t2 = v.split('=');
_this3.search[t2[0]] = t2[1] == null ? '' : decodeURIComponent(t2[1]);
});
}
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) {
for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];
_createClass(URLHelper, [{
key: "getHref",
value: function getHref() {
var _this4 = this;
var t = [this.baseUrl];
var searchStr = Object.keys(this.search).map(function (k) {
return "".concat(k, "=").concat(encodeURIComponent(_this4.search[k]));
}).join('&');
if (searchStr) {
t.push(searchStr);
}
return t.join('?');
}
}]);
return URLHelper;
}(); // 解析函数参数, 帮助重载
var EventProcessor =
/*#__PURE__*/
function () {
function EventProcessor() {
_classCallCheck(this, EventProcessor);
Object.defineProperty(this, "eventStore", {
configurable: true,
enumerable: true,
writable: true,
value: []
});
return arr2;
}
}
_createClass(EventProcessor, [{
key: "on",
value: function on(name, handler) {
this.eventStore.push({
name: name,
handler: handler
});
}
}, {
key: "once",
value: function once(name, handler) {
var _this5 = this;
function _iterableToArray(iter) {
if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
}
var off = function off() {
_this5.off(name, wrappedHandler);
};
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance");
}
var wrappedHandler = function wrappedHandler() {
handler();
off();
};
this.on(name, wrappedHandler);
return off;
}
}, {
key: "off",
value: function off(name, handler) {
var indexes = []; // to remove indexes; reverse; 倒序的
var len = this.eventStore.length;
for (var i = 0; i < len; i++) {
var item = this.eventStore[i];
if (item.name === name && item.handler === handler) {
indexes.unshift(i);
}
}
for (var _i8 = 0; _i8 < indexes.length; _i8++) {
var index = indexes[_i8];
this.eventStore.splice(index, 1);
}
}
}, {
key: "emit",
value: function emit(name) {
// 重要: 先找到要执行的项放在新数组里, 因为执行项会改变事件项存储数组
var items = [];
var _iteratorNormalCompletion9 = true;
var _didIteratorError9 = false;
var _iteratorError9 = undefined;
try {
for (var _iterator9 = this.eventStore[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
var item = _step9.value;
if (item.name === name) {
items.push(item);
}
}
} catch (err) {
_didIteratorError9 = true;
_iteratorError9 = err;
} finally {
try {
if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
_iterator9.return();
}
} finally {
if (_didIteratorError9) {
throw _iteratorError9;
}
}
}
for (var _len8 = arguments.length, args = new Array(_len8 > 1 ? _len8 - 1 : 0), _key9 = 1; _key9 < _len8; _key9++) {
args[_key9 - 1] = arguments[_key9];
}
for (var _i9 = 0; _i9 < items.length; _i9++) {
var _item = items[_i9];
_item.handler.apply(_item, args);
}
}
}]);
return EventProcessor;
}();
var CrossWindow =
/*#__PURE__*/
function (_EventProcessor) {
_inherits(CrossWindow, _EventProcessor);
function CrossWindow() {
var _this6;
_classCallCheck(this, CrossWindow);
_this6 = _possibleConstructorReturn(this, (CrossWindow.__proto__ || Object.getPrototypeOf(CrossWindow)).call(this));
Object.defineProperty(_assertThisInitialized(_this6), "storageName", {
configurable: true,
enumerable: true,
writable: true,
value: '_crossWindow'
});
var cls = CrossWindow;
if (!cls._listen) {
cls._listen = true;
onDOM(window, 'storage', function (ev) {
if (ev.key === _this6.storageName) {
var _get2;
var event = JSON.parse(ev.newValue);
(_get2 = _get(CrossWindow.prototype.__proto__ || Object.getPrototypeOf(CrossWindow.prototype), "emit", _assertThisInitialized(_this6))).call.apply(_get2, [_this6, event.name].concat(_toConsumableArray(event.args)));
}
});
}
return _this6;
}
_createClass(CrossWindow, [{
key: "emit",
value: function emit(name) {
var _get3;
for (var _len9 = arguments.length, args = new Array(_len9 > 1 ? _len9 - 1 : 0), _key10 = 1; _key10 < _len9; _key10++) {
args[_key10 - 1] = arguments[_key10];
}
(_get3 = _get(CrossWindow.prototype.__proto__ || Object.getPrototypeOf(CrossWindow.prototype), "emit", this)).call.apply(_get3, [this, name].concat(args));
glb().localStorage.setItem(this.storageName, JSON.stringify({
name: name,
args: args,
// use random make storage event triggered every time
// 加入随机保证触发storage事件
random: Math.random()
}));
}
}]);
return CrossWindow;
}(EventProcessor);
/*!
* drag-event-service v0.0.6
* (c) 2018-present phphe <phphe@outlook.com> (https://github.com/phphe)
* Released under the MIT License.
*/
// support desktop and mobile
var events = {

@@ -478,7 +182,12 @@ start: ['mousedown', 'touchstart'],

},
on: function on(el, name, handler) {
on: function on(el, name, handler, options) {
var _hp$onDOM, _hp$onDOM2;
var store$$1 = this._getStore(el);
var _resolveOptions = resolveOptions(options),
args = _resolveOptions.args,
mouseArgs = _resolveOptions.mouseArgs,
touchArgs = _resolveOptions.touchArgs;
var store = this._getStore(el);
var ts = this;

@@ -512,3 +221,3 @@

store$$1.push({
store.push({
handler: handler,

@@ -520,19 +229,15 @@ wrapper: wrapper

for (var _len = arguments.length, args = new Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
args[_key - 3] = arguments[_key];
}
(_hp$onDOM = onDOM).call.apply(_hp$onDOM, [null, el, events[name][0], wrapper].concat(_toConsumableArray(args).concat(_toConsumableArray(mouseArgs))));
(_hp$onDOM = onDOM).call.apply(_hp$onDOM, [null, el, events[name][0], wrapper].concat(args));
(_hp$onDOM2 = onDOM).call.apply(_hp$onDOM2, [null, el, events[name][1], wrapper].concat(args));
(_hp$onDOM2 = onDOM).call.apply(_hp$onDOM2, [null, el, events[name][1], wrapper].concat(_toConsumableArray(args).concat(_toConsumableArray(touchArgs))));
},
off: function off(el, name, handler) {
var store$$1 = this._getStore(el);
off: function off(el, name, handler, options) {
var _resolveOptions2 = resolveOptions(options),
args = _resolveOptions2.args,
mouseArgs = _resolveOptions2.mouseArgs;
for (var _len2 = arguments.length, args = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) {
args[_key2 - 3] = arguments[_key2];
}
var store = this._getStore(el);
for (var i = store$$1.length - 1; i >= 0; i--) {
var _store$i = store$$1[i],
for (var i = store.length - 1; i >= 0; i--) {
var _store$i = store[i],
handler2 = _store$i.handler,

@@ -544,7 +249,7 @@ wrapper = _store$i.wrapper;

(_hp$offDOM = offDOM).call.apply(_hp$offDOM, [null, el, events[name][0], wrapper].concat(args));
(_hp$offDOM = offDOM).call.apply(_hp$offDOM, [null, el, events[name][0], wrapper].concat(_toConsumableArray(args).concat(_toConsumableArray(mouseArgs))));
(_hp$offDOM2 = offDOM).call.apply(_hp$offDOM2, [null, el, events[name][1], wrapper].concat(args));
(_hp$offDOM2 = offDOM).call.apply(_hp$offDOM2, [null, el, events[name][1], wrapper].concat(_toConsumableArray(args).concat(_toConsumableArray(mouseArgs))));
store$$1.splice(i, 1);
store.splice(i, 1);
}

@@ -555,6 +260,21 @@ }

function resolveOptions(options) {
if (!options) {
options = {};
}
var args = options.args || [];
var mouseArgs = options.mouseArgs || [];
var touchArgs = options.touchArgs || [];
return {
args: args,
mouseArgs: mouseArgs,
touchArgs: touchArgs
};
}
/***
const destroy = draggableHelper(HTMLElement dragHandlerEl, Object opt = {})
opt.drag(e, opt, store)
[Object] opt.style || opt.getStyle(opt) set style of moving el style
opt.drag(startEvent, moveEvent, opt, store) return false to prevent drag
[Object] opt.style || opt.getStyle(opt, store) set style of moving el style
[Boolean] opt.clone

@@ -564,7 +284,11 @@ opt.draggingClass, default dragging

opt.drop(e, opt, store)
opt.getEl(dragHandlerEl, opt) get the el that will be moved. default is dragHandlerEl
opt.getEl(dragHandlerEl, opt, store) get the el that will be moved. default is dragHandlerEl
afterGetEl(startEvent, opt, store)
opt.minTranslate default 10, unit px
add other prop into opt, you get opt in callback
[Boolean] opt.triggerBySelf: false if trigger only by self, can not be triggered by children
add other prop into opt, you can get opt in callback
store{
el
originalEl
initialMouse

@@ -593,14 +317,14 @@ initialPosition

var IGNORE_TRIGGERS = ['INPUT', 'TEXTAREA', 'SELECT', 'OPTGROUP', 'OPTION'];
var UNDRAGGABLE_CLASS = 'undraggable';
function index$1 (dragHandlerEl) {
var opt = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
opt = Object.assign({
minTranslate: 10,
draggingClass: 'dragging'
}, opt);
var store = getPureStore();
if (opt.minTranslate == null) {
opt.minTranslate = 10;
}
var store$$1 = getPureStore();
var destroy = function destroy() {
index.off(dragHandlerEl, 'end', dragHandlerEl._draggbleEventHandler);
offDOM(dragHandlerEl, 'selectstart', preventSelect);
index.off(dragHandlerEl, 'start', dragHandlerEl._draggbleEventHandler);
delete dragHandlerEl._draggbleEventHandler;

@@ -614,17 +338,51 @@ };

dragHandlerEl._draggbleEventHandler = start;
index.on(dragHandlerEl, 'start', dragHandlerEl._draggbleEventHandler);
onDOM(dragHandlerEl, 'selectstart', preventSelect);
index.on(dragHandlerEl, 'start', start);
return destroy;
function start(e, mouse) {
// e.stopPropagation()
store$$1.mouse = {
// detect draggable =================================
if (opt.triggerBySelf && e.target !== dragHandlerEl) {
return;
}
if (IGNORE_TRIGGERS.includes(e.target.tagName)) {
return;
}
if (hasClass(e.target, UNDRAGGABLE_CLASS)) {
return;
}
var isParentUndraggable = findParent(e.target, function (el) {
if (hasClass(el, UNDRAGGABLE_CLASS)) {
return true;
}
if (el === dragHandlerEl) {
return 'break';
}
});
if (isParentUndraggable) {
return;
} // detect draggable end =================================
e.preventDefault();
store.mouse = {
x: mouse.x,
y: mouse.y
};
store$$1.initialMouse = Object.assign({}, store$$1.mouse);
store.startEvent = e;
store.initialMouse = Object.assign({}, store.mouse);
/*
must set passive false for touch, else the follow error occurs in Chrome:
Unable to preventDefault inside passive event listener due to target being treated as passive. See https://www.chromestatus.com/features/5093566007214080
*/
index.on(document, 'move', moving, {
passive: false
}); // passive: false is for touchmove event
touchArgs: [{
passive: false
}]
});
index.on(window, 'end', drop);

@@ -634,2 +392,8 @@ }

function drag(e) {
var r = opt.drag && opt.drag(store.startEvent, e, opt, store);
if (r === false) {
return false;
}
var _resolveDragedElAndIn = resolveDragedElAndInitialPosition(),

@@ -639,11 +403,6 @@ el = _resolveDragedElAndIn.el,

store$$1.el = el;
store$$1.initialPosition = Object.assign({}, position);
var r = opt.drag && opt.drag(e, opt, store$$1);
store.el = el;
store.initialPosition = Object.assign({}, position);
opt.afterGetEl && opt.afterGetEl(e, opt, store); // dom actions
if (r === false) {
return false;
} // dom actions
var size = getElSize(el);

@@ -658,3 +417,3 @@ var style = Object.assign({

top: position.y + 'px'
}, opt.style || opt.getStyle && opt.getStyle(opt) || {});
}, opt.style || opt.getStyle && opt.getStyle(opt, store) || {});
backupAttr(el, 'style');

@@ -672,14 +431,15 @@

function moving(e, mouse) {
store$$1.mouse = {
e.preventDefault();
store.mouse = {
x: mouse.x,
y: mouse.y
};
var move = store$$1.move = {
x: store$$1.mouse.x - store$$1.initialMouse.x,
y: store$$1.mouse.y - store$$1.initialMouse.y
var move = store.move = {
x: store.mouse.x - store.initialMouse.x,
y: store.mouse.y - store.initialMouse.y
};
if (store$$1.movedCount === 0 && opt.minTranslate) {
var x2 = Math.pow(store$$1.move.x, 2);
var y2 = Math.pow(store$$1.move.y, 2);
if (store.movedCount === 0 && opt.minTranslate) {
var x2 = Math.pow(store.move.x, 2);
var y2 = Math.pow(store.move.y, 2);
var dtc = Math.pow(x2 + y2, 0.5);

@@ -694,3 +454,3 @@

if (store$$1.movedCount === 0) {
if (store.movedCount === 0) {
if (drag(e) === false) {

@@ -700,9 +460,6 @@ canMove = false;

} // move started
// e.preventDefault() to prevent text selection and page scrolling when touch
e.preventDefault();
if (canMove && opt.moving) {
if (opt.moving(e, opt, store$$1) === false) {
if (opt.moving(e, opt, store) === false) {
canMove = false;

@@ -713,11 +470,11 @@ }

if (canMove) {
if (!store$$1 || !store$$1.el) {
if (!store || !store.el) {
return;
}
Object.assign(store$$1.el.style, {
left: store$$1.initialPosition.x + move.x + 'px',
top: store$$1.initialPosition.y + move.y + 'px'
Object.assign(store.el.style, {
left: store.initialPosition.x + move.x + 'px',
top: store.initialPosition.y + move.y + 'px'
});
store$$1.movedCount++;
store.movedCount++;
}

@@ -728,9 +485,11 @@ }

index.off(document, 'move', moving, {
passive: false
touchArgs: [{
passive: false
}]
});
index.off(window, 'end', drop); // drag executed if movedCount > 0
if (store$$1.movedCount > 0) {
store$$1.movedCount = 0;
var _store = store$$1,
if (store.movedCount > 0) {
store.movedCount = 0;
var _store = store,
el = _store.el;

@@ -745,14 +504,14 @@

opt.drop && opt.drop(e, opt, store$$1);
opt.drop && opt.drop(e, opt, store);
}
store$$1 = getPureStore();
store = getPureStore();
}
function resolveDragedElAndInitialPosition() {
var el0 = opt.getEl ? opt.getEl(dragHandlerEl, opt) : dragHandlerEl;
var el0 = opt.getEl ? opt.getEl(dragHandlerEl, opt, store) : dragHandlerEl;
var el = el0;
store.originalEl = el0;
if (opt.clone) {
store$$1.triggerEl = el0;
el = el0.cloneNode(true);

@@ -763,3 +522,3 @@ el0.parentElement.appendChild(el);

return {
position: getPosition(el),
position: getPosition(el0),
el: el

@@ -774,6 +533,2 @@ };

}
function preventSelect(e) {
e.preventDefault();
}
}

@@ -783,2 +538,2 @@

})));
}));
/*!
* draggable-helper v1.0.20
* (c) 2018-present phphe <phphe@outlook.com> (https://github.com/phphe)
* draggable-helper v1.1.1
* (c) phphe <phphe@outlook.com> (https://github.com/phphe)
* Released under the MIT License.
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.draggableHelper=t()}(this,function(){"use strict";function e(e){for(var t=function(e){var t=e.offsetParent;return(!t||t===document.body&&"static"===getComputedStyle(document.body).position)&&(t=document.body.parentElement),t}(e),n={x:e.offsetLeft,y:e.offsetTop},o=e;(o=o.parentElement)!==t&&o;)n.x-=o.scrollLeft,n.y-=o.scrollTop;return n}function t(e,t){e["original_".concat(t)]=e.getAttribute(t)}function n(e,t){var n="original_".concat(t);e.setAttribute(t,e[n])}function o(e,t){(function(e,t){return e.classList?e.classList.contains(t):new RegExp("(^| )"+t+"( |$)","gi").test(e.className)})(e,t)||(e.classList?e.classList.add(t):e.className+=" "+t)}function a(e,t,n){for(var o=arguments.length,a=new Array(o>3?o-3:0),r=3;r<o;r++)a[r-3]=arguments[r];e.addEventListener?e.addEventListener.apply(e,[t,n].concat(a)):e.attachEvent&&e.attachEvent.apply(e,["on".concat(t),n].concat(a))}function r(e,t,n){for(var o=arguments.length,a=new Array(o>3?o-3:0),r=3;r<o;r++)a[r-3]=arguments[r];e.removeEventListener?e.removeEventListener.apply(e,[t,n].concat(a)):e.detachEvent&&e.detachEvent.apply(e,["on".concat(t),n].concat(a))}var i={start:["mousedown","touchstart"],move:["mousemove","touchmove"],end:["mouseup","touchend"]},l={isTouch:function(e){return e.type&&e.type.startsWith("touch")},_getStore:function(e){return e._wrapperStore||(e._wrapperStore=[]),e._wrapperStore},on:function(e,t,n){var o,r,l=this,s=function(e){var o;if(l.isTouch(e))o={x:e.changedTouches[0].pageX,y:e.changedTouches[0].pageY};else if(o={x:e.pageX,y:e.pageY},"start"===t&&1!==e.which)return;return n.call(this,e,o)};this._getStore(e).push({handler:n,wrapper:s});for(var c=arguments.length,u=new Array(c>3?c-3:0),p=3;p<c;p++)u[p-3]=arguments[p];(o=a).call.apply(o,[null,e,i[t][0],s].concat(u)),(r=a).call.apply(r,[null,e,i[t][1],s].concat(u))},off:function(e,t,n){for(var o=this._getStore(e),a=arguments.length,l=new Array(a>3?a-3:0),s=3;s<a;s++)l[s-3]=arguments[s];for(var c=o.length-1;c>=0;c--){var u,p,d=o[c],f=d.handler,v=d.wrapper;if(n===f)(u=r).call.apply(u,[null,e,i[t][0],v].concat(l)),(p=r).call.apply(p,[null,e,i[t][1],v].concat(l)),o.splice(c,1)}}};return function(i){var s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};null==s.minTranslate&&(s.minTranslate=10);var c={movedCount:0},u=function(){l.off(i,"end",i._draggbleEventHandler),r(i,"selectstart",v),delete i._draggbleEventHandler};return i._draggbleEventHandler&&u(),i._draggbleEventHandler=function(e,t){c.mouse={x:t.x,y:t.y},c.initialMouse=Object.assign({},c.mouse),l.on(document,"move",d,{passive:!1}),l.on(window,"end",f)},l.on(i,"start",i._draggbleEventHandler),a(i,"selectstart",v),u;function p(n){var a=function(){var t=s.getEl?s.getEl(i,s):i,n=t;return s.clone&&(c.triggerEl=t,n=t.cloneNode(!0),t.parentElement.appendChild(n)),{position:e(n),el:n}}(),r=a.el,l=a.position;if(c.el=r,c.initialPosition=Object.assign({},l),!1===(s.drag&&s.drag(n,s,c)))return!1;var u=function(e){var t=e.style.display;e.style.display="block";var n={width:e.offsetWidth,height:e.offsetHeight};return e.style.display=t,n}(r),p=Object.assign({width:"".concat(u.width,"px"),height:"".concat(u.height,"px"),zIndex:9999,opacity:.6,position:"absolute",left:l.x+"px",top:l.y+"px"},s.style||s.getStyle&&s.getStyle(s)||{});for(var d in t(r,"style"),p)r.style[d]=p[d];t(r,"class"),o(r,s.draggingClass)}function d(e,t){c.mouse={x:t.x,y:t.y};var n=c.move={x:c.mouse.x-c.initialMouse.x,y:c.mouse.y-c.initialMouse.y};if(0===c.movedCount&&s.minTranslate){var o=Math.pow(c.move.x,2),a=Math.pow(c.move.y,2);if(Math.pow(o+a,.5)<s.minTranslate)return}var r=!0;if(0===c.movedCount&&!1===p(e)&&(r=!1),e.preventDefault(),r&&s.moving&&!1===s.moving(e,s,c)&&(r=!1),r){if(!c||!c.el)return;Object.assign(c.el.style,{left:c.initialPosition.x+n.x+"px",top:c.initialPosition.y+n.y+"px"}),c.movedCount++}}function f(e){if(l.off(document,"move",d,{passive:!1}),l.off(window,"end",f),c.movedCount>0){c.movedCount=0;var t=c.el;s.clone?t.parentElement.removeChild(t):(n(t,"style"),n(t,"class")),s.drop&&s.drop(e,s,c)}c={movedCount:0}}function v(e){e.preventDefault()}}});
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self)["helper-js"]=e()}(this,function(){"use strict";function t(t){for(var e=function(t){var e=t.offsetParent;return(!e||e===document.body&&"static"===getComputedStyle(document.body).position)&&(e=document.body.parentElement),e}(t),n={x:t.offsetLeft,y:t.offsetTop},o=t;(o=o.parentElement)!==e&&o;)n.x-=o.scrollLeft,n.y-=o.scrollTop;return n}function e(t,e){t["original_".concat(e)]=t.getAttribute(e)}function n(t,e){var n="original_".concat(e);t.setAttribute(e,t[n])}function o(t,e){return t.classList?t.classList.contains(e):new RegExp("(^| )"+e+"( |$)","gi").test(t.className)}function r(t,e,n){for(var o=arguments.length,r=new Array(o>3?o-3:0),a=3;a<o;a++)r[a-3]=arguments[a];t.addEventListener?t.addEventListener.apply(t,[e,n].concat(r)):t.attachEvent&&t.attachEvent.apply(t,["on".concat(e),n].concat(r))}function a(t,e,n){for(var o=arguments.length,r=new Array(o>3?o-3:0),a=3;a<o;a++)r[a-3]=arguments[a];t.removeEventListener?t.removeEventListener.apply(t,[e,n].concat(r)):t.detachEvent&&t.detachEvent.apply(t,["on".concat(e),n].concat(r))}function i(t){return function(t){if(Array.isArray(t)){for(var e=0,n=new Array(t.length);e<t.length;e++)n[e]=t[e];return n}}(t)||function(t){if(Symbol.iterator in Object(t)||"[object Arguments]"===Object.prototype.toString.call(t))return Array.from(t)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var s={start:["mousedown","touchstart"],move:["mousemove","touchmove"],end:["mouseup","touchend"]},c={isTouch:function(t){return t.type&&t.type.startsWith("touch")},_getStore:function(t){return t._wrapperStore||(t._wrapperStore=[]),t._wrapperStore},on:function(t,e,n,o){var a,c,u=l(o),f=u.args,p=u.mouseArgs,g=u.touchArgs,d=this._getStore(t),v=this,m=function(t){var o;if(v.isTouch(t))o={x:t.changedTouches[0].pageX,y:t.changedTouches[0].pageY};else if(o={x:t.pageX,y:t.pageY},"start"===e&&1!==t.which)return;return n.call(this,t,o)};d.push({handler:n,wrapper:m}),(a=r).call.apply(a,[null,t,s[e][0],m].concat(i(f).concat(i(p)))),(c=r).call.apply(c,[null,t,s[e][1],m].concat(i(f).concat(i(g))))},off:function(t,e,n,o){for(var r=l(o),c=r.args,u=r.mouseArgs,f=this._getStore(t),p=f.length-1;p>=0;p--){var g,d,v=f[p],m=v.handler,y=v.wrapper;if(n===m)(g=a).call.apply(g,[null,t,s[e][0],y].concat(i(c).concat(i(u)))),(d=a).call.apply(d,[null,t,s[e][1],y].concat(i(c).concat(i(u)))),f.splice(p,1)}}};function l(t){return t||(t={}),{args:t.args||[],mouseArgs:t.mouseArgs||[],touchArgs:t.touchArgs||[]}}var u=["INPUT","TEXTAREA","SELECT","OPTGROUP","OPTION"],f="undraggable";return function(r){var a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};a=Object.assign({minTranslate:10,draggingClass:"dragging"},a);var i={movedCount:0},s=function(){c.off(r,"start",r._draggbleEventHandler),delete r._draggbleEventHandler};return r._draggbleEventHandler&&s(),r._draggbleEventHandler=l,c.on(r,"start",l),s;function l(t,e){a.triggerBySelf&&t.target!==r||u.includes(t.target.tagName)||o(t.target,f)||function(t,e,n){for(var o=n&&n.withSelf?t:t.parentElement;o;){var r=e(o);if("break"===r)return;if(r)return o;o=o.parentElement}}(t.target,function(t){return!!o(t,f)||(t===r?"break":void 0)})||(t.preventDefault(),i.mouse={x:e.x,y:e.y},i.startEvent=t,i.initialMouse=Object.assign({},i.mouse),c.on(document,"move",g,{touchArgs:[{passive:!1}]}),c.on(window,"end",d))}function p(n){if(!1===(a.drag&&a.drag(i.startEvent,n,a,i)))return!1;var s=function(){var e=a.getEl?a.getEl(r,a,i):r,n=e;return i.originalEl=e,a.clone&&(n=e.cloneNode(!0),e.parentElement.appendChild(n)),{position:t(e),el:n}}(),c=s.el,l=s.position;i.el=c,i.initialPosition=Object.assign({},l),a.afterGetEl&&a.afterGetEl(n,a,i);var u=function(t){var e=t.style.display;t.style.display="block";var n={width:t.offsetWidth,height:t.offsetHeight};return t.style.display=e,n}(c),f=Object.assign({width:"".concat(u.width,"px"),height:"".concat(u.height,"px"),zIndex:9999,opacity:.6,position:"absolute",left:l.x+"px",top:l.y+"px"},a.style||a.getStyle&&a.getStyle(a,i)||{});for(var p in e(c,"style"),f)c.style[p]=f[p];e(c,"class"),function(t,e){o(t,e)||(t.classList?t.classList.add(e):t.className+=" "+e)}(c,a.draggingClass)}function g(t,e){t.preventDefault(),i.mouse={x:e.x,y:e.y};var n=i.move={x:i.mouse.x-i.initialMouse.x,y:i.mouse.y-i.initialMouse.y};if(0===i.movedCount&&a.minTranslate){var o=Math.pow(i.move.x,2),r=Math.pow(i.move.y,2);if(Math.pow(o+r,.5)<a.minTranslate)return}var s=!0;if(0===i.movedCount&&!1===p(t)&&(s=!1),s&&a.moving&&!1===a.moving(t,a,i)&&(s=!1),s){if(!i||!i.el)return;Object.assign(i.el.style,{left:i.initialPosition.x+n.x+"px",top:i.initialPosition.y+n.y+"px"}),i.movedCount++}}function d(t){if(c.off(document,"move",g,{touchArgs:[{passive:!1}]}),c.off(window,"end",d),i.movedCount>0){i.movedCount=0;var e=i.el;a.clone?e.parentElement.removeChild(e):(n(e,"style"),n(e,"class")),a.drop&&a.drop(t,a,i)}i={movedCount:0}}}});
//# sourceMappingURL=draggable-helper.min.js.map
{
"name": "draggable-helper",
"version": "1.0.20",
"version": "1.1.1",
"description": "",
"main": "dist/draggable-helper.cjs.js",
"module": "dist/draggable-helper.es.js",
"module": "dist/draggable-helper.esm.js",
"unpkg": "dist/draggable-helper.js",
"files": [
"dist"
],
"scripts": {
"build": "bili --format cjs,umd,umd-min,es --banner",
"dev": "bili --format cjs,umd --watch"
"build": "bili --format cjs --format umd --format umd-min --format esm --banner",
"dev": "bili --watch"
},
"author": "phphe <phphe@outlook.com> (https://github.com/phphe)",
"unpkg": "dist/draggable-helper.js",
"bugs": {

@@ -21,9 +24,15 @@ "url": "https://github.com/phphe/draggable-helper/issues"

"devDependencies": {
"bili": "^3.0.14"
"@babel/plugin-proposal-class-properties": "^7.5.5",
"@babel/plugin-proposal-decorators": "^7.4.4",
"@babel/plugin-proposal-export-namespace-from": "^7.5.2",
"@babel/plugin-proposal-function-sent": "^7.5.0",
"@babel/plugin-proposal-numeric-separator": "^7.2.0",
"@babel/plugin-proposal-throw-expressions": "^7.2.0",
"bili": "^4.8.1"
},
"dependencies": {
"drag-event-service": "0.0.6",
"helper-js": "^1.3.7"
"drag-event-service": "^1.0.0",
"helper-js": "^1.4.2"
},
"license": "MIT"
}
# draggable-helper
A js library to simplify your drag and drop functions. Start with a element, it will expose hooks(drag, moving, drop). You can stop drag, moving and drop by conditions. You can set minTranslate. Its code is easy, you can check source code.
# features
## features
* support touch simplify(single touch)

@@ -14,42 +14,76 @@ * to prevent page scrolling when touch

* to prevent text be selected when dragging
# install
* Advance usage: bind to parent element, make children element as trigger element or moved element. Check example.
## install
```sh
npm install draggable-helper
```
# usage & api
## usage & api
```js
import draggableHelper from 'draggable-helper'
// dragHandlerEl will be added mouse and touch event listener
const destroy = draggableHelper(HTMLElement dragHandlerEl, Object opt = {})
// opt
// opt will pass to hook, so you can attach custom data into opt, such the data of the element
// startEvent is mousedown or touchstart
opt = {
// [Object] style, set the style of dragging element
// getStyle(opt), set the style of dragging element
// [String] draggingClass, default dragging, set the class of dragging element
// [Boolean] clone, move the element or move a cloned one
// minTranslate default 10, unit px
// getEl(dragHandlerEl, opt), optional, get the el that will be moved. default is dragHandlerEl
// hook, when drag start
drag(event, opt, store){
// return false to prevent drag
},
// hook, when mouse moving
moving: (e, opt, store) => {
// return false to prevent moving
},
// hook, when drop
drop: (e, opt, store) => {
},
// [Object] style, set the style of dragging element
// getStyle(opt, store), set the style of dragging element
// [String] draggingClass, default dragging, set the class of dragging element
// [Boolean] clone, move the element or move a cloned one
// minTranslate default 10, unit px
// getEl(dragHandlerEl, opt, store), optional, get the el that will be moved. default is dragHandlerEl
// afterGetEl(startEvent, opt, store)
// [Boolean] triggerBySelf if trigger only by dragHandlerEl self, can not be triggered by children
// hook, when drag start
drag(startEvent, moveEvent, opt, store){
// when trigger drag, the position must be moved, so there are two event. startEvent also can be accessed by store.startEvent
// return false to prevent drag
},
// hook, when mouse moving
moving: (moveEvent, opt, store) => {
// return false to prevent moving
},
// hook, when drop
drop: (endEvent, opt, store) => {
},
}
// store
// store. life cycle: drag-end
store = {
el
el // the moving el
originalEl // the original moving el, used when clone
initialMouse
initialOffset
initialPosition // relative to offsetParent
mouse
move
movedCount // start from 0
startEvent // mousedown or touchstart event
}
```
# demo
## Example
### Advance usage: bind to parent element
Advance usage: bind to parent element, make children element as trigger element or moved element.
```js
import draggableHelper from 'draggable-helper'
const destroy = draggableHelper(document.body, {
drag(startEvent, moveEvent, opt, store) {
// check trigger el
if (startEvent.target not has class 'your trigger class') {
return false
}
},
// get the element which will be moved
getEl: (dragHandlerEl, opt, store) => get the el which will be moved by `store.startEvent.target`
})
```
## prevent drag
In follow case, drag event will be prevented.
* Event target element is follow
```js
const IGNORE_TRIGGERS = ['INPUT','TEXTAREA', 'SELECT', 'OPTGROUP', 'OPTION']
```
* Event target has class `undraggable` or its ancestor till dragHandlerEl has.
* opt.drag return false
## demo
[jsfiddle](https://jsfiddle.net/phphe/t694kpua/19/)

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc