-
Notifications
You must be signed in to change notification settings - Fork 3
/
coroutine-dragging.js
71 lines (65 loc) · 2.45 KB
/
coroutine-dragging.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
function coroutine(f) {
var o = f();
o.next();
return function(x) {
o.next(x);
}
}
function initDragging(box, animation) {
function move(event) {
var parent = box.parent().offset();
box.css({left: event.pageX - parent.left - 50,
top: event.pageY - parent.top - 50});
}
var animate;
if (animation) {
animation = [];
setInterval(function() {
if (animation.length > 0) {
var class_ = animation.shift();
if (class_) { // empty class is used to slow things down
$('.highlighted').removeClass('highlighted');
$(class_).addClass('highlighted');
}
}
}, 100);
animate = function(classes, force) {
if (force || animation.length == 0) {
if (force && animation.length > 0) // skip to end of current animation
animation.splice(0, animation.length - 1);
Array.prototype.push.apply(animation, classes);
}
}
}
else {
animate = function() {}
}
var loop = coroutine(function*() {
var event;
while (event = yield) {
if (event.type == 'mousedown') {
event.preventDefault(); // stop Chrome from trying to select text
animate(['', '.not-dragging.mousedown-1', '', '.not-dragging.mousedown-2', '.dragging.yield'], true);
while (event = yield) {
if (event.type == 'mousemove') {
animate(['', '.dragging.mousemove-1', '.dragging.mousemove-2', '.dragging.mousemove-3', '.dragging.yield']);
move(event);
}
if (event.type == 'mouseup') {
animate(['', '.dragging.mouseup-1', '.dragging.mouseup-2', '.dragging.mouseup-3', '.not-dragging.yield'], true);
break;
}
}
}
else if (event.type == 'mousemove')
animate(['', '.not-dragging.mousemove-1', '.not-dragging.mousemove-2', '.not-dragging.mousemove-3', '.not-dragging.yield']);
}
});
// register the listeners:
box.mousedown(loop);
box.parent().mousemove(loop);
$(window).mouseup(loop);
box.bind('dragstart', function(event) {
event.preventDefault(); // stop Firefox from doing weird drag-and-drop things
});
}