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