-
Notifications
You must be signed in to change notification settings - Fork 0
/
DragState.js
81 lines (73 loc) · 1.6 KB
/
DragState.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
var DragState = (function () {
var dragging = null;
var hovering = null;
var delta;
return {
Setup: Setup,
Teardown: Teardown,
};
function Setup() {
Events.On('MouseMove', MouseMove);
Events.On('MouseDown', StartDragState);
}
function Teardown() {
Events.Off('MouseMove', MouseMove);
Events.Off('MouseDown', StartDragState);
SetDragging(null);
SetHovering(null);
}
function MouseMove(point) {
if (dragging) {
point.x += delta.x;
point.y += delta.y;
dragging.point = GetStatePoint(point);
} else {
var state = GetStateAt(point);
if (CanDrag(point, state)) {
SetCursor('move');
SetHovering(state);
} else if (hovering) {
SetHovering(null);
}
}
}
function StartDragState(point) {
var state = GetStateAt(point);
if (CanDrag(point, state)) {
SetDragging(state);
delta = GetDelta(state.point, point);
Events.One('MouseUp', function() {
SetDragging(null);
});
}
}
function SetHovering(state) {
if (hovering) hovering.hover = false;
if (state) {
hovering = state;
hovering.hover = true;
} else {
hovering = null;
}
}
function SetDragging(state) {
if (dragging) dragging.drag = false;
if (state) {
dragging = state;
dragging.drag = true;
} else {
dragging = null;
}
}
function CanDrag(point, state) {
if (!state) return false;
var circle = state.circle();
return circle.distanceTo(point) <= circle.radius;
}
function GetDelta(point1, point2) {
return {
x: point1.x - point2.x,
y: point1.y - point2.y
};
}
})();