-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
131 lines (105 loc) · 2.33 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
/**
* Module Dependencies
*/
var classes = require('classes')
, Emitter = require('emitter')
, events = require('events');
/**
* Expose `Dragdrop`.
*/
module.exports = Dragdrop;
/**
* Initialize a new `Dragdrop`.
*/
function Dragdrop(el, opts){
if (!(this instanceof Dragdrop)) return new Dragdrop(el, opts);
Emitter.call(this);
this.el = el;
this.classes = classes(el);
this.events = events(el, this);
this.events.bind('drop');
this.events.bind('dragstart');
this.events.bind('dragenter');
this.events.bind('dragover');
this.events.bind('dragleave');
this.events.bind('dragend');
}
/**
* Inherits `Emitter`.
*/
Emitter(Dragdrop.prototype);
/**
* Dragstart handler.
*/
Dragdrop.prototype.ondragstart = function(e){
this.src = parent(e.target);
classes(this.src).add('dragging');
this.emit('start', this.src);
};
/**
* Dragenter handler.
*/
Dragdrop.prototype.ondragenter = function(e){
e.preventDefault();
e.stopPropagation();
this.emit('enter', parent(e.target));
};
/**
* Dragover handler.
*/
Dragdrop.prototype.ondragover = function(e){
e.preventDefault();
e.stopPropagation();
var target = parent(e.target);
this.drop = target;
classes(target).add('over');
this.emit('over', target);
};
/**
* Dragleave handler.
*/
Dragdrop.prototype.ondragleave = function(e){
e.preventDefault();
e.stopPropagation();
var target = parent(e.target);
classes(target).remove('over');
this.emit('leave', target);
};
/**
* Dragend handler.
*/
Dragdrop.prototype.ondragend = function(e){
e.preventDefault();
e.stopPropagation();
if (this.src) classes(this.src).remove('dragging');
this.emit('end', this.src);
};
/**
* Drop handler.
*/
Dragdrop.prototype.ondrop = function(e){
e.preventDefault();
e.stopPropagation();
var target = parent(e.target);
if (target) classes(target).remove('over');
if (this.src) classes(this.src).remove('dragging').remove('over');
this.emit('drop', this.src, this.drop);
};
/**
* Finds draggable or droppable parent node.
*/
function parent(el) {
var p = el.parentNode;
var parents = [];
var drop;
while (p !== null) {
var n = p;
parents.push(n);
p = n.parentNode;
}
for (var i=0; i < parents.length; i++) {
var node = parents[i];
if ((node.draggable || node.droppable) && !drop) drop = node;
}
return drop || el;
}