The code is now completely covered in specs
[lyrix.git] / public / javascripts / lowpro / draggable.js
blobbcb63a136b24191aff4ee04b61bf09f3b30e169d
1 Draggable = Behavior.create({
2 initialize : function(options) {
3 this.options = Object.extend({
4 onStart : Prototype.K,
5 onComplete : Prototype.K,
6 units : 'px',
7 zindex : 1000,
8 revert : true
9 }, options || {});
11 this.handle = this.options.handle || this.element;
12 Draggable.Handle.attach(this.handle, this);
14 this.element.makePositioned();
16 this.startX = this.element.getStyle('left') || '0px';
17 this.startY = this.element.getStyle('top') || '0px';
18 this.startZ = this.element.getStyle('z-index');
20 Draggable.draggables.push(this);
22 move : function(x, y) {
23 this.element.setStyle({
24 left : (parseInt(this.element.getStyle('left')) || 0) + x + this.options.units,
25 top : (parseInt(this.element.getStyle('top')) || 0) + y + this.options.units
26 });
28 drag : function(e) {
29 this.clientX = e.clientX;
30 this.clientY = e.clientY;
31 this.move(this.clientX - this.lastMouseX, this.clientY - this.lastMouseY)
32 this.set(e);
33 return false;
35 set :function(e) {
36 this.lastMouseX = e.clientX;
37 this.lastMouseY = e.clientY;
39 stop : function() {
40 this.unbindDocumentEvents();
42 Draggable.targets.each(function(target) {
43 if (Position.within(target.element, this.clientX, this.clientY)) {
44 target.onDrop(this);
46 }.bind(this));
48 this.options.onComplete(this);
50 if (this.options.revert) {
51 if (typeof this.options.revert == 'function') {
52 this.options.revert(this);
53 } else this.element.setStyle({
54 left : this.startX,
55 top : this.startY
56 });
59 this.element.style.zIndex = this.startZ;
61 bindDocumentEvents : function() {
62 document.onmousemove = this.drag.bindAsEventListener(this);
63 document.onmouseup = this.stop.bindAsEventListener(this);
65 unbindDocumentEvents : function() {
66 document.onmousemove = document.onmouseup = null;
68 });
70 Draggable.Handle = Behavior.create({
71 initialize : function(draggable) {
72 this.draggable = draggable;
74 onmousedown : function(e) {
75 this.draggable.bindDocumentEvents();
76 this.draggable.set(e);
77 this.draggable.element.style.zIndex = this.draggable.options.zindex;
78 this.draggable.options.onStart(this.draggable);
79 return false;
81 });
83 Draggable.draggables = [];
84 Draggable.targets = [];
86 Draggable.DropTarget = Behavior.create({
87 initialize : function(options) {
88 this.options = Object.extend({
89 onDrop : Prototype.K
90 }, options || {});
92 Draggable.targets.push(this);
94 onDrop : function(draggable) {
95 if (this.canDrop(draggable))
96 return this.options.onDrop.call(this, draggable);
97 else return false;
99 canDrop : function(draggable) {
100 return !this.options.accepts || draggable.element.hasClassName(this.options.accepts);