Upgrade to ExtJS 4.0.2 - Released 06/09/2011
[extjs.git] / src / dd / DragTracker.js
1 /*
2
3 This file is part of Ext JS 4
4
5 Copyright (c) 2011 Sencha Inc
6
7 Contact:  http://www.sencha.com/contact
8
9 GNU General Public License Usage
10 This file may be used under the terms of the GNU General Public License version 3.0 as published by the Free Software Foundation and appearing in the file LICENSE included in the packaging of this file.  Please review the following information to ensure the GNU General Public License version 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
11
12 If you are unsure which license is appropriate for your use, please contact the sales department at http://www.sencha.com/contact.
13
14 */
15 /**
16  * @class Ext.dd.DragTracker
17  * A DragTracker listens for drag events on an Element and fires events at the start and end of the drag,
18  * as well as during the drag. This is useful for components such as {@link Ext.slider.Multi}, where there is
19  * an element that can be dragged around to change the Slider's value.
20  * DragTracker provides a series of template methods that should be overridden to provide functionality
21  * in response to detected drag operations. These are onBeforeStart, onStart, onDrag and onEnd.
22  * See {@link Ext.slider.Multi}'s initEvents function for an example implementation.
23  */
24 Ext.define('Ext.dd.DragTracker', {
25
26     uses: ['Ext.util.Region'],
27
28     mixins: {
29         observable: 'Ext.util.Observable'
30     },
31
32     /**
33      * @property active
34      * @type Boolean
35      * Read-only property indicated whether the user is currently dragging this
36      * tracker.
37      */
38     active: false,
39
40     /**
41      * @property dragTarget
42      * @type HtmlElement
43      * <p><b>Only valid during drag operations. Read-only.</b></p>
44      * <p>The element being dragged.</p>
45      * <p>If the {@link #delegate} option is used, this will be the delegate element which was mousedowned.</p>
46      */
47
48     /**
49      * @cfg {Boolean} trackOver
50      * <p>Defaults to <code>false</code>. Set to true to fire mouseover and mouseout events when the mouse enters or leaves the target element.</p>
51      * <p>This is implicitly set when an {@link #overCls} is specified.</p>
52      * <b>If the {@link #delegate} option is used, these events fire only when a delegate element is entered of left.</b>.
53      */
54     trackOver: false,
55
56     /**
57      * @cfg {String} overCls
58      * <p>A CSS class to add to the DragTracker's target element when the element (or, if the {@link #delegate} option is used,
59      * when a delegate element) is mouseovered.</p>
60      * <b>If the {@link #delegate} option is used, these events fire only when a delegate element is entered of left.</b>.
61      */
62
63     /**
64      * @cfg {Ext.util.Region/Element} constrainTo
65      * <p>A {@link Ext.util.Region Region} (Or an element from which a Region measurement will be read) which is used to constrain
66      * the result of the {@link #getOffset} call.</p>
67      * <p>This may be set any time during the DragTracker's lifecycle to set a dynamic constraining region.</p>
68      */
69
70     /**
71      * @cfg {Number} tolerance
72      * Number of pixels the drag target must be moved before dragging is
73      * considered to have started. Defaults to <code>5</code>.
74      */
75     tolerance: 5,
76
77     /**
78      * @cfg {Boolean/Number} autoStart
79      * Defaults to <code>false</code>. Specify <code>true</code> to defer trigger start by 1000 ms.
80      * Specify a Number for the number of milliseconds to defer trigger start.
81      */
82     autoStart: false,
83
84     /**
85      * @cfg {String} delegate
86      * Optional. <p>A {@link Ext.DomQuery DomQuery} selector which identifies child elements within the DragTracker's encapsulating
87      * Element which are the tracked elements. This limits tracking to only begin when the matching elements are mousedowned.</p>
88      * <p>This may also be a specific child element within the DragTracker's encapsulating element to use as the tracked element.</p>
89      */
90
91     /**
92      * @cfg {Boolean} preventDefault
93      * Specify <code>false</code> to enable default actions on onMouseDown events. Defaults to <code>true</code>.
94      */
95
96     /**
97      * @cfg {Boolean} stopEvent
98      * Specify <code>true</code> to stop the <code>mousedown</code> event from bubbling to outer listeners from the target element (or its delegates). Defaults to <code>false</code>.
99      */
100
101     constructor : function(config){
102         Ext.apply(this, config);
103         this.addEvents(
104             /**
105              * @event mouseover <p><b>Only available when {@link #trackOver} is <code>true</code></b></p>
106              * <p>Fires when the mouse enters the DragTracker's target element (or if {@link #delegate} is
107              * used, when the mouse enters a delegate element).</p>
108              * @param {Object} this
109              * @param {Object} e event object
110              * @param {HtmlElement} target The element mouseovered.
111              */
112             'mouseover',
113
114             /**
115              * @event mouseout <p><b>Only available when {@link #trackOver} is <code>true</code></b></p>
116              * <p>Fires when the mouse exits the DragTracker's target element (or if {@link #delegate} is
117              * used, when the mouse exits a delegate element).</p>
118              * @param {Object} this
119              * @param {Object} e event object
120              */
121             'mouseout',
122
123             /**
124              * @event mousedown <p>Fires when the mouse button is pressed down, but before a drag operation begins. The
125              * drag operation begins after either the mouse has been moved by {@link #tolerance} pixels, or after
126              * the {@link #autoStart} timer fires.</p>
127              * <p>Return false to veto the drag operation.</p>
128              * @param {Object} this
129              * @param {Object} e event object
130              */
131             'mousedown',
132
133             /**
134              * @event mouseup
135              * @param {Object} this
136              * @param {Object} e event object
137              */
138             'mouseup',
139
140             /**
141              * @event mousemove Fired when the mouse is moved. Returning false cancels the drag operation.
142              * @param {Object} this
143              * @param {Object} e event object
144              */
145             'mousemove',
146
147             /**
148              * @event beforestart
149              * @param {Object} this
150              * @param {Object} e event object
151              */
152             'beforedragstart',
153
154             /**
155              * @event dragstart
156              * @param {Object} this
157              * @param {Object} e event object
158              */
159             'dragstart',
160
161             /**
162              * @event dragend
163              * @param {Object} this
164              * @param {Object} e event object
165              */
166             'dragend',
167
168             /**
169              * @event drag
170              * @param {Object} this
171              * @param {Object} e event object
172              */
173             'drag'
174         );
175
176         this.dragRegion = Ext.create('Ext.util.Region', 0,0,0,0);
177
178         if (this.el) {
179             this.initEl(this.el);
180         }
181
182         // Dont pass the config so that it is not applied to 'this' again
183         this.mixins.observable.constructor.call(this);
184         if (this.disabled) {
185             this.disable();
186         }
187
188     },
189
190     /**
191      * Initializes the DragTracker on a given element.
192      * @param {Ext.core.Element/HTMLElement} el The element
193      */
194     initEl: function(el) {
195         this.el = Ext.get(el);
196
197         // The delegate option may also be an element on which to listen
198         this.handle = Ext.get(this.delegate);
199
200         // If delegate specified an actual element to listen on, we do not use the delegate listener option
201         this.delegate = this.handle ? undefined : this.delegate;
202
203         if (!this.handle) {
204             this.handle = this.el;
205         }
206
207         // Add a mousedown listener which reacts only on the elements targeted by the delegate config.
208         // We process mousedown to begin tracking.
209         this.mon(this.handle, {
210             mousedown: this.onMouseDown,
211             delegate: this.delegate,
212             scope: this
213         });
214
215         // If configured to do so, track mouse entry and exit into the target (or delegate).
216         // The mouseover and mouseout CANNOT be replaced with mouseenter and mouseleave
217         // because delegate cannot work with those pseudoevents. Entry/exit checking is done in the handler.
218         if (this.trackOver || this.overCls) {
219             this.mon(this.handle, {
220                 mouseover: this.onMouseOver,
221                 mouseout: this.onMouseOut,
222                 delegate: this.delegate,
223                 scope: this
224             });
225         }
226     },
227
228     disable: function() {
229         this.disabled = true;
230     },
231
232     enable: function() {
233         this.disabled = false;
234     },
235
236     destroy : function() {
237         this.clearListeners();
238         delete this.el;
239     },
240
241     // When the pointer enters a tracking element, fire a mouseover if the mouse entered from outside.
242     // This is mouseenter functionality, but we cannot use mouseenter because we are using "delegate" to filter mouse targets
243     onMouseOver: function(e, target) {
244         var me = this;
245         if (!me.disabled) {
246             if (Ext.EventManager.contains(e) || me.delegate) {
247                 me.mouseIsOut = false;
248                 if (me.overCls) {
249                     me.el.addCls(me.overCls);
250                 }
251                 me.fireEvent('mouseover', me, e, me.delegate ? e.getTarget(me.delegate, target) : me.handle);
252             }
253         }
254     },
255
256     // When the pointer exits a tracking element, fire a mouseout.
257     // This is mouseleave functionality, but we cannot use mouseleave because we are using "delegate" to filter mouse targets
258     onMouseOut: function(e) {
259         if (this.mouseIsDown) {
260             this.mouseIsOut = true;
261         } else {
262             if (this.overCls) {
263                 this.el.removeCls(this.overCls);
264             }
265             this.fireEvent('mouseout', this, e);
266         }
267     },
268
269     onMouseDown: function(e, target){
270         // If this is disabled, or the mousedown has been processed by an upstream DragTracker, return
271         if (this.disabled ||e.dragTracked) {
272             return;
273         }
274
275         // This information should be available in mousedown listener and onBeforeStart implementations
276         this.dragTarget = this.delegate ? target : this.handle.dom;
277         this.startXY = this.lastXY = e.getXY();
278         this.startRegion = Ext.fly(this.dragTarget).getRegion();
279
280         if (this.fireEvent('mousedown', this, e) === false ||
281             this.fireEvent('beforedragstart', this, e) === false ||
282             this.onBeforeStart(e) === false) {
283             return;
284         }
285
286         // Track when the mouse is down so that mouseouts while the mouse is down are not processed.
287         // The onMouseOut method will only ever be called after mouseup.
288         this.mouseIsDown = true;
289
290         // Flag for downstream DragTracker instances that the mouse is being tracked.
291         e.dragTracked = true;
292
293         if (this.preventDefault !== false) {
294             e.preventDefault();
295         }
296         Ext.getDoc().on({
297             scope: this,
298             mouseup: this.onMouseUp,
299             mousemove: this.onMouseMove,
300             selectstart: this.stopSelect
301         });
302         if (this.autoStart) {
303             this.timer =  Ext.defer(this.triggerStart, this.autoStart === true ? 1000 : this.autoStart, this, [e]);
304         }
305     },
306
307     onMouseMove: function(e, target){
308         // BrowserBug: IE hack to see if button was released outside of window.
309         // Needed in IE6-9 in quirks and strictmode
310         if (this.active && Ext.isIE && !e.browserEvent.button) {
311             e.preventDefault();
312             this.onMouseUp(e);
313             return;
314         }
315
316         e.preventDefault();
317         var xy = e.getXY(),
318             s = this.startXY;
319
320         this.lastXY = xy;
321         if (!this.active) {
322             if (Math.max(Math.abs(s[0]-xy[0]), Math.abs(s[1]-xy[1])) > this.tolerance) {
323                 this.triggerStart(e);
324             } else {
325                 return;
326             }
327         }
328
329         // Returning false from a mousemove listener deactivates 
330         if (this.fireEvent('mousemove', this, e) === false) {
331             this.onMouseUp(e);
332         } else {
333             this.onDrag(e);
334             this.fireEvent('drag', this, e);
335         }
336     },
337
338     onMouseUp: function(e) {
339         // Clear the flag which ensures onMouseOut fires only after the mouse button
340         // is lifted if the mouseout happens *during* a drag.
341         this.mouseIsDown = false;
342
343         // If we mouseouted the el *during* the drag, the onMouseOut method will not have fired. Ensure that it gets processed.
344         if (this.mouseIsOut) {
345             this.mouseIsOut = false;
346             this.onMouseOut(e);
347         }
348         e.preventDefault();
349         this.fireEvent('mouseup', this, e);
350         this.endDrag(e);
351     },
352
353     /**
354      * @private
355      * Stop the drag operation, and remove active mouse listeners.
356      */
357     endDrag: function(e) {
358         var doc = Ext.getDoc(),
359         wasActive = this.active;
360
361         doc.un('mousemove', this.onMouseMove, this);
362         doc.un('mouseup', this.onMouseUp, this);
363         doc.un('selectstart', this.stopSelect, this);
364         this.clearStart();
365         this.active = false;
366         if (wasActive) {
367             this.onEnd(e);
368             this.fireEvent('dragend', this, e);
369         }
370         // Private property calculated when first required and only cached during a drag
371         delete this._constrainRegion;
372
373         // Remove flag from event singleton.  Using "Ext.EventObject" here since "endDrag" is called directly in some cases without an "e" param
374         delete Ext.EventObject.dragTracked;
375     },
376
377     triggerStart: function(e) {
378         this.clearStart();
379         this.active = true;
380         this.onStart(e);
381         this.fireEvent('dragstart', this, e);
382     },
383
384     clearStart : function() {
385         if (this.timer) {
386             clearTimeout(this.timer);
387             delete this.timer;
388         }
389     },
390
391     stopSelect : function(e) {
392         e.stopEvent();
393         return false;
394     },
395
396     /**
397      * Template method which should be overridden by each DragTracker instance. Called when the user first clicks and
398      * holds the mouse button down. Return false to disallow the drag
399      * @param {Ext.EventObject} e The event object
400      */
401     onBeforeStart : function(e) {
402
403     },
404
405     /**
406      * Template method which should be overridden by each DragTracker instance. Called when a drag operation starts
407      * (e.g. the user has moved the tracked element beyond the specified tolerance)
408      * @param {Ext.EventObject} e The event object
409      */
410     onStart : function(xy) {
411
412     },
413
414     /**
415      * Template method which should be overridden by each DragTracker instance. Called whenever a drag has been detected.
416      * @param {Ext.EventObject} e The event object
417      */
418     onDrag : function(e) {
419
420     },
421
422     /**
423      * Template method which should be overridden by each DragTracker instance. Called when a drag operation has been completed
424      * (e.g. the user clicked and held the mouse down, dragged the element and then released the mouse button)
425      * @param {Ext.EventObject} e The event object
426      */
427     onEnd : function(e) {
428
429     },
430
431     /**
432      * </p>Returns the drag target. This is usually the DragTracker's encapsulating element.</p>
433      * <p>If the {@link #delegate} option is being used, this may be a child element which matches the
434      * {@link #delegate} selector.</p>
435      * @return {Ext.core.Element} The element currently being tracked.
436      */
437     getDragTarget : function(){
438         return this.dragTarget;
439     },
440
441     /**
442      * @private
443      * @returns {Element} The DragTracker's encapsulating element.
444      */
445     getDragCt : function(){
446         return this.el;
447     },
448
449     /**
450      * @private
451      * Return the Region into which the drag operation is constrained.
452      * Either the XY pointer itself can be constrained, or the dragTarget element
453      * The private property _constrainRegion is cached until onMouseUp
454      */
455     getConstrainRegion: function() {
456         if (this.constrainTo) {
457             if (this.constrainTo instanceof Ext.util.Region) {
458                 return this.constrainTo;
459             }
460             if (!this._constrainRegion) {
461                 this._constrainRegion = Ext.fly(this.constrainTo).getViewRegion();
462             }
463         } else {
464             if (!this._constrainRegion) {
465                 this._constrainRegion = this.getDragCt().getViewRegion();
466             }
467         }
468         return this._constrainRegion;
469     },
470
471     getXY : function(constrain){
472         return constrain ? this.constrainModes[constrain](this, this.lastXY) : this.lastXY;
473     },
474
475     /**
476      * <p>Returns the X, Y offset of the current mouse position from the mousedown point.</p>
477      * <p>This method may optionally constrain the real offset values, and returns a point coerced in one
478      * of two modes:</p><ul>
479      * <li><code>point</code><div class="sub-desc">The current mouse position is coerced into the
480      * {@link #constrainRegion}, and the resulting position is returned.</div></li>
481      * <li><code>dragTarget</code><div class="sub-desc">The new {@link Ext.util.Region Region} of the
482      * {@link #getDragTarget dragTarget} is calculated based upon the current mouse position, and then
483      * coerced into the {@link #constrainRegion}. The returned mouse position is then adjusted by the
484      * same delta as was used to coerce the region.</div></li>
485      * </ul>
486      * @param constrainMode {String} Optional. If omitted the true mouse position is returned. May be passed
487      * as <code>'point'</code> or <code>'dragTarget'. See above.</code>.
488      * @returns {Array} The <code>X, Y</code> offset from the mousedown point, optionally constrained.
489      */
490     getOffset : function(constrain){
491         var xy = this.getXY(constrain),
492             s = this.startXY;
493
494         return [xy[0]-s[0], xy[1]-s[1]];
495     },
496
497     constrainModes: {
498         // Constrain the passed point to within the constrain region
499         point: function(me, xy) {
500             var dr = me.dragRegion,
501                 constrainTo = me.getConstrainRegion();
502
503             // No constraint
504             if (!constrainTo) {
505                 return xy;
506             }
507
508             dr.x = dr.left = dr[0] = dr.right = xy[0];
509             dr.y = dr.top = dr[1] = dr.bottom = xy[1];
510             dr.constrainTo(constrainTo);
511
512             return [dr.left, dr.top];
513         },
514
515         // Constrain the dragTarget to within the constrain region. Return the passed xy adjusted by the same delta.
516         dragTarget: function(me, xy) {
517             var s = me.startXY,
518                 dr = me.startRegion.copy(),
519                 constrainTo = me.getConstrainRegion(),
520                 adjust;
521
522             // No constraint
523             if (!constrainTo) {
524                 return xy;
525             }
526
527             // See where the passed XY would put the dragTarget if translated by the unconstrained offset.
528             // If it overflows, we constrain the passed XY to bring the potential
529             // region back within the boundary.
530             dr.translateBy(xy[0]-s[0], xy[1]-s[1]);
531
532             // Constrain the X coordinate by however much the dragTarget overflows
533             if (dr.right > constrainTo.right) {
534                 xy[0] += adjust = (constrainTo.right - dr.right);    // overflowed the right
535                 dr.left += adjust;
536             }
537             if (dr.left < constrainTo.left) {
538                 xy[0] += (constrainTo.left - dr.left);      // overflowed the left
539             }
540
541             // Constrain the Y coordinate by however much the dragTarget overflows
542             if (dr.bottom > constrainTo.bottom) {
543                 xy[1] += adjust = (constrainTo.bottom - dr.bottom);  // overflowed the bottom
544                 dr.top += adjust;
545             }
546             if (dr.top < constrainTo.top) {
547                 xy[1] += (constrainTo.top - dr.top);        // overflowed the top
548             }
549             return xy;
550         }
551     }
552 });