Upgrade to ExtJS 3.0.3 - Released 10/11/2009
[extjs.git] / src / core / core / EventManager.js
1 /*!
2  * Ext JS Library 3.0.3
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**
8  * @class Ext.EventManager
9  * Registers event handlers that want to receive a normalized EventObject instead of the standard browser event and provides
10  * several useful events directly.
11  * See {@link Ext.EventObject} for more details on normalized event objects.
12  * @singleton
13  */
14 Ext.EventManager = function(){
15     var docReadyEvent, 
16         docReadyProcId, 
17         docReadyState = false,        
18         E = Ext.lib.Event,
19         D = Ext.lib.Dom,
20         DOC = document,
21         WINDOW = window,
22         IEDEFERED = "ie-deferred-loader",
23         DOMCONTENTLOADED = "DOMContentLoaded",
24         elHash = {},
25         propRe = /^(?:scope|delay|buffer|single|stopEvent|preventDefault|stopPropagation|normalized|args|delegate)$/;
26
27     /// There is some jquery work around stuff here that isn't needed in Ext Core.
28     function addListener(el, ename, fn, wrap, scope){        
29         var id = Ext.id(el),
30             es = elHash[id] = elHash[id] || {};         
31        
32         (es[ename] = es[ename] || []).push([fn, wrap, scope]);
33         E.on(el, ename, wrap);
34
35         // this is a workaround for jQuery and should somehow be removed from Ext Core in the future
36         // without breaking ExtJS.
37         if(ename == "mousewheel" && el.addEventListener){ // workaround for jQuery
38             var args = ["DOMMouseScroll", wrap, false];
39             el.addEventListener.apply(el, args);
40             E.on(window, 'unload', function(){
41                 el.removeEventListener.apply(el, args);                
42             });
43         }
44         if(ename == "mousedown" && el == document){ // fix stopped mousedowns on the document
45             Ext.EventManager.stoppedMouseDownEvent.addListener(wrap);
46         }
47     };
48     
49     function fireDocReady(){
50         if(!docReadyState){            
51             Ext.isReady = docReadyState = true;
52             if(docReadyProcId){
53                 clearInterval(docReadyProcId);
54             }
55             if(Ext.isGecko || Ext.isOpera) {
56                 DOC.removeEventListener(DOMCONTENTLOADED, fireDocReady, false);
57             }
58             if(Ext.isIE){
59                 var defer = DOC.getElementById(IEDEFERED);
60                 if(defer){
61                     defer.onreadystatechange = null;
62                     defer.parentNode.removeChild(defer);
63                 }
64             }
65             if(docReadyEvent){
66                 docReadyEvent.fire();
67                 docReadyEvent.clearListeners();
68             }
69         }
70     };
71
72     function initDocReady(){
73         var COMPLETE = "complete";
74             
75         docReadyEvent = new Ext.util.Event();
76         if (Ext.isGecko || Ext.isOpera) {
77             DOC.addEventListener(DOMCONTENTLOADED, fireDocReady, false);
78         } else if (Ext.isIE){
79             DOC.write("<s"+'cript id=' + IEDEFERED + ' defer="defer" src="/'+'/:"></s'+"cript>");            
80             DOC.getElementById(IEDEFERED).onreadystatechange = function(){
81                 if(this.readyState == COMPLETE){
82                     fireDocReady();
83                 }
84             };
85         } else if (Ext.isWebKit){
86             docReadyProcId = setInterval(function(){                
87                 if(DOC.readyState == COMPLETE) {
88                     fireDocReady();
89                  }
90             }, 10);
91         }
92         // no matter what, make sure it fires on load
93         E.on(WINDOW, "load", fireDocReady);
94     };
95
96     function createTargeted(h, o){
97         return function(){
98             var args = Ext.toArray(arguments);
99             if(o.target == Ext.EventObject.setEvent(args[0]).target){
100                 h.apply(this, args);
101             }
102         };
103     };    
104     
105     function createBuffered(h, o){
106         var task = new Ext.util.DelayedTask(h);
107         return function(e){
108             // create new event object impl so new events don't wipe out properties            
109             task.delay(o.buffer, h, null, [new Ext.EventObjectImpl(e)]);
110         };
111     };
112
113     function createSingle(h, el, ename, fn, scope){
114         return function(e){
115             Ext.EventManager.removeListener(el, ename, fn, scope);
116             h(e);
117         };
118     };
119
120     function createDelayed(h, o){
121         return function(e){
122             // create new event object impl so new events don't wipe out properties   
123             e = new Ext.EventObjectImpl(e);
124             setTimeout(function(){
125                 h(e);
126             }, o.delay || 10);
127         };
128     };
129
130     function listen(element, ename, opt, fn, scope){
131         var o = !Ext.isObject(opt) ? {} : opt,
132             el = Ext.getDom(element);
133             
134         fn = fn || o.fn; 
135         scope = scope || o.scope;
136         
137         if(!el){
138             throw "Error listening for \"" + ename + '\". Element "' + element + '" doesn\'t exist.';
139         }
140         function h(e){
141             // prevent errors while unload occurring
142             if(!Ext){// !window[xname]){  ==> can't we do this? 
143                 return;
144             }
145             e = Ext.EventObject.setEvent(e);
146             var t;
147             if (o.delegate) {
148                 if(!(t = e.getTarget(o.delegate, el))){
149                     return;
150                 }
151             } else {
152                 t = e.target;
153             }            
154             if (o.stopEvent) {
155                 e.stopEvent();
156             }
157             if (o.preventDefault) {
158                e.preventDefault();
159             }
160             if (o.stopPropagation) {
161                 e.stopPropagation();
162             }
163             if (o.normalized) {
164                 e = e.browserEvent;
165             }
166             
167             fn.call(scope || el, e, t, o);
168         };
169         if(o.target){
170             h = createTargeted(h, o);
171         }
172         if(o.delay){
173             h = createDelayed(h, o);
174         }
175         if(o.single){
176             h = createSingle(h, el, ename, fn, scope);
177         }
178         if(o.buffer){
179             h = createBuffered(h, o);
180         }
181
182         addListener(el, ename, fn, h, scope);
183         return h;
184     };
185
186     var pub = {
187         /**
188          * Appends an event handler to an element.  The shorthand version {@link #on} is equivalent.  Typically you will
189          * use {@link Ext.Element#addListener} directly on an Element in favor of calling this version.
190          * @param {String/HTMLElement} el The html element or id to assign the event handler to.
191          * @param {String} eventName The name of the event to listen for.
192          * @param {Function} handler The handler function the event invokes. This function is passed
193          * the following parameters:<ul>
194          * <li>evt : EventObject<div class="sub-desc">The {@link Ext.EventObject EventObject} describing the event.</div></li>
195          * <li>t : Element<div class="sub-desc">The {@link Ext.Element Element} which was the target of the event.
196          * Note that this may be filtered by using the <tt>delegate</tt> option.</div></li>
197          * <li>o : Object<div class="sub-desc">The options object from the addListener call.</div></li>
198          * </ul>
199          * @param {Object} scope (optional) The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.
200          * @param {Object} options (optional) An object containing handler configuration properties.
201          * This may contain any of the following properties:<ul>
202          * <li>scope : Object<div class="sub-desc">The scope (<b><code>this</code></b> reference) in which the handler function is executed. <b>Defaults to the Element</b>.</div></li>
203          * <li>delegate : String<div class="sub-desc">A simple selector to filter the target or look for a descendant of the target</div></li>
204          * <li>stopEvent : Boolean<div class="sub-desc">True to stop the event. That is stop propagation, and prevent the default action.</div></li>
205          * <li>preventDefault : Boolean<div class="sub-desc">True to prevent the default action</div></li>
206          * <li>stopPropagation : Boolean<div class="sub-desc">True to prevent event propagation</div></li>
207          * <li>normalized : Boolean<div class="sub-desc">False to pass a browser event to the handler function instead of an Ext.EventObject</div></li>
208          * <li>delay : Number<div class="sub-desc">The number of milliseconds to delay the invocation of the handler after te event fires.</div></li>
209          * <li>single : Boolean<div class="sub-desc">True to add a handler to handle just the next firing of the event, and then remove itself.</div></li>
210          * <li>buffer : Number<div class="sub-desc">Causes the handler to be scheduled to run in an {@link Ext.util.DelayedTask} delayed
211          * by the specified number of milliseconds. If the event fires again within that time, the original
212          * handler is <em>not</em> invoked, but the new handler is scheduled in its place.</div></li>
213          * <li>target : Element<div class="sub-desc">Only call the handler if the event was fired on the target Element, <i>not</i> if the event was bubbled up from a child node.</div></li>
214          * </ul><br>
215          * <p>See {@link Ext.Element#addListener} for examples of how to use these options.</p>
216          */
217         addListener : function(element, eventName, fn, scope, options){                                       
218             if(Ext.isObject(eventName)){                
219                 var o = eventName, e, val;
220                 for(e in o){
221                     val = o[e];
222                     if(!propRe.test(e)){                                             
223                         if(Ext.isFunction(val)){
224                             // shared options
225                             listen(element, e, o, val, o.scope);
226                         }else{
227                             // individual options
228                             listen(element, e, val);
229                         }
230                     }
231                 }
232             } else {
233                 listen(element, eventName, options, fn, scope);
234             }
235         },
236         
237         /**
238          * Removes an event handler from an element.  The shorthand version {@link #un} is equivalent.  Typically
239          * you will use {@link Ext.Element#removeListener} directly on an Element in favor of calling this version.
240          * @param {String/HTMLElement} el The id or html element from which to remove the listener.
241          * @param {String} eventName The name of the event.
242          * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #addListener} call.</b>
243          * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
244          * then this must refer to the same object.
245          */
246         removeListener : function(element, eventName, fn, scope){            
247             var el = Ext.getDom(element),
248                 id = Ext.id(el),
249                 wrap;      
250             
251             Ext.each((elHash[id] || {})[eventName], function (v,i,a) {
252                 if (Ext.isArray(v) && v[0] == fn && (!scope || v[2] == scope)) {                                    
253                     E.un(el, eventName, wrap = v[1]);
254                     a.splice(i,1);
255                     return false;                    
256                 }
257             });    
258
259             // jQuery workaround that should be removed from Ext Core
260             if(eventName == "mousewheel" && el.addEventListener && wrap){
261                 el.removeEventListener("DOMMouseScroll", wrap, false);
262             }
263                         
264             if(eventName == "mousedown" && el == DOC && wrap){ // fix stopped mousedowns on the document
265                 Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
266             }
267         },
268         
269         /**
270          * Removes all event handers from an element.  Typically you will use {@link Ext.Element#removeAllListeners}
271          * directly on an Element in favor of calling this version.
272          * @param {String/HTMLElement} el The id or html element from which to remove all event handlers.
273          */
274         removeAll : function(el){
275             var id = Ext.id(el = Ext.getDom(el)), 
276                 es = elHash[id],                 
277                 ename;
278            
279             for(ename in es){
280                 if(es.hasOwnProperty(ename)){                        
281                     Ext.each(es[ename], function(v) {
282                         E.un(el, ename, v.wrap);                    
283                     });
284                 }            
285             }
286             elHash[id] = null;       
287         },
288
289         /**
290          * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Can be
291          * accessed shorthanded as Ext.onReady().
292          * @param {Function} fn The method the event invokes.
293          * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
294          * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
295          * <code>{single: true}</code> be used so that the handler is removed on first invocation.
296          */
297         onDocumentReady : function(fn, scope, options){
298             if(docReadyState){ // if it already fired
299                 docReadyEvent.addListener(fn, scope, options);
300                 docReadyEvent.fire();
301                 docReadyEvent.clearListeners();               
302             } else {
303                 if(!docReadyEvent) initDocReady();
304                 options = options || {};
305                 options.delay = options.delay || 1;                
306                 docReadyEvent.addListener(fn, scope, options);
307             }
308         },
309         
310         elHash : elHash   
311     };
312      /**
313      * Appends an event handler to an element.  Shorthand for {@link #addListener}.
314      * @param {String/HTMLElement} el The html element or id to assign the event handler to
315      * @param {String} eventName The name of the event to listen for.
316      * @param {Function} handler The handler function the event invokes.
317      * @param {Object} scope (optional) (<code>this</code> reference) in which the handler function executes. <b>Defaults to the Element</b>.
318      * @param {Object} options (optional) An object containing standard {@link #addListener} options
319      * @member Ext.EventManager
320      * @method on
321      */
322     pub.on = pub.addListener;
323     /**
324      * Removes an event handler from an element.  Shorthand for {@link #removeListener}.
325      * @param {String/HTMLElement} el The id or html element from which to remove the listener.
326      * @param {String} eventName The name of the event.
327      * @param {Function} fn The handler function to remove. <b>This must be a reference to the function passed into the {@link #on} call.</b>
328      * @param {Object} scope If a scope (<b><code>this</code></b> reference) was specified when the listener was added,
329      * then this must refer to the same object.
330      * @member Ext.EventManager
331      * @method un
332      */
333     pub.un = pub.removeListener;
334
335     pub.stoppedMouseDownEvent = new Ext.util.Event();
336     return pub;
337 }();
338 /**
339   * Adds a listener to be notified when the document is ready (before onload and before images are loaded). Shorthand of {@link Ext.EventManager#onDocumentReady}.
340   * @param {Function} fn The method the event invokes.
341   * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the handler function executes. Defaults to the browser window.
342   * @param {boolean} options (optional) Options object as passed to {@link Ext.Element#addListener}. It is recommended that the options
343   * <code>{single: true}</code> be used so that the handler is removed on first invocation.
344   * @member Ext
345   * @method onReady
346  */
347 Ext.onReady = Ext.EventManager.onDocumentReady;
348
349
350 //Initialize doc classes
351 (function(){
352     
353     var initExtCss = function(){
354         // find the body element
355         var bd = document.body || document.getElementsByTagName('body')[0];
356         if(!bd){ return false; }
357         var cls = [' ',
358                 Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : (Ext.isIE7 ? 'ext-ie7' : 'ext-ie8'))
359                 : Ext.isGecko ? "ext-gecko " + (Ext.isGecko2 ? 'ext-gecko2' : 'ext-gecko3')
360                 : Ext.isOpera ? "ext-opera"
361                 : Ext.isWebKit ? "ext-webkit" : ""];
362
363         if(Ext.isSafari){
364             cls.push("ext-safari " + (Ext.isSafari2 ? 'ext-safari2' : (Ext.isSafari3 ? 'ext-safari3' : 'ext-safari4')));
365         }else if(Ext.isChrome){
366             cls.push("ext-chrome");
367         }
368
369         if(Ext.isMac){
370             cls.push("ext-mac");
371         }
372         if(Ext.isLinux){
373             cls.push("ext-linux");
374         }
375
376         if(Ext.isStrict || Ext.isBorderBox){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
377             var p = bd.parentNode;
378             if(p){
379                 p.className += Ext.isStrict ? ' ext-strict' : ' ext-border-box';
380             }
381         }
382         bd.className += cls.join(' ');
383         return true;
384     }
385
386     if(!initExtCss()){
387         Ext.onReady(initExtCss);
388     }
389 })();
390
391
392 /**
393  * @class Ext.EventObject
394  * Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject 
395  * wraps the browser's native event-object normalizing cross-browser differences,
396  * such as which mouse button is clicked, keys pressed, mechanisms to stop
397  * event-propagation along with a method to prevent default actions from taking place.
398  * <p>For example:</p>
399  * <pre><code>
400 function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
401     e.preventDefault();
402     var target = e.getTarget(); // same as t (the target HTMLElement)
403     ...
404 }
405 var myDiv = {@link Ext#get Ext.get}("myDiv");  // get reference to an {@link Ext.Element}
406 myDiv.on(         // 'on' is shorthand for addListener
407     "click",      // perform an action on click of myDiv
408     handleClick   // reference to the action handler
409 );  
410 // other methods to do the same:
411 Ext.EventManager.on("myDiv", 'click', handleClick);
412 Ext.EventManager.addListener("myDiv", 'click', handleClick);
413  </code></pre>
414  * @singleton
415  */
416 Ext.EventObject = function(){
417     var E = Ext.lib.Event,
418         // safari keypress events for special keys return bad keycodes
419         safariKeys = {
420             3 : 13, // enter
421             63234 : 37, // left
422             63235 : 39, // right
423             63232 : 38, // up
424             63233 : 40, // down
425             63276 : 33, // page up
426             63277 : 34, // page down
427             63272 : 46, // delete
428             63273 : 36, // home
429             63275 : 35  // end
430         },
431         // normalize button clicks
432         btnMap = Ext.isIE ? {1:0,4:1,2:2} :
433                 (Ext.isWebKit ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
434
435     Ext.EventObjectImpl = function(e){
436         if(e){
437             this.setEvent(e.browserEvent || e);
438         }
439     };
440
441     Ext.EventObjectImpl.prototype = {
442            /** @private */
443         setEvent : function(e){
444             var me = this;
445             if(e == me || (e && e.browserEvent)){ // already wrapped
446                 return e;
447             }
448             me.browserEvent = e;
449             if(e){
450                 // normalize buttons
451                 me.button = e.button ? btnMap[e.button] : (e.which ? e.which - 1 : -1);
452                 if(e.type == 'click' && me.button == -1){
453                     me.button = 0;
454                 }
455                 me.type = e.type;
456                 me.shiftKey = e.shiftKey;
457                 // mac metaKey behaves like ctrlKey
458                 me.ctrlKey = e.ctrlKey || e.metaKey || false;
459                 me.altKey = e.altKey;
460                 // in getKey these will be normalized for the mac
461                 me.keyCode = e.keyCode;
462                 me.charCode = e.charCode;
463                 // cache the target for the delayed and or buffered events
464                 me.target = E.getTarget(e);
465                 // same for XY
466                 me.xy = E.getXY(e);
467             }else{
468                 me.button = -1;
469                 me.shiftKey = false;
470                 me.ctrlKey = false;
471                 me.altKey = false;
472                 me.keyCode = 0;
473                 me.charCode = 0;
474                 me.target = null;
475                 me.xy = [0, 0];
476             }
477             return me;
478         },
479
480         /**
481          * Stop the event (preventDefault and stopPropagation)
482          */
483         stopEvent : function(){
484             var me = this;
485             if(me.browserEvent){
486                 if(me.browserEvent.type == 'mousedown'){
487                     Ext.EventManager.stoppedMouseDownEvent.fire(me);
488                 }
489                 E.stopEvent(me.browserEvent);
490             }
491         },
492
493         /**
494          * Prevents the browsers default handling of the event.
495          */
496         preventDefault : function(){
497             if(this.browserEvent){
498                 E.preventDefault(this.browserEvent);
499             }
500         },        
501
502         /**
503          * Cancels bubbling of the event.
504          */
505         stopPropagation : function(){
506             var me = this;
507             if(me.browserEvent){
508                 if(me.browserEvent.type == 'mousedown'){
509                     Ext.EventManager.stoppedMouseDownEvent.fire(me);
510                 }
511                 E.stopPropagation(me.browserEvent);
512             }
513         },
514
515         /**
516          * Gets the character code for the event.
517          * @return {Number}
518          */
519         getCharCode : function(){
520             return this.charCode || this.keyCode;
521         },
522
523         /**
524          * Returns a normalized keyCode for the event.
525          * @return {Number} The key code
526          */
527         getKey : function(){
528             return this.normalizeKey(this.keyCode || this.charCode)
529         },
530         
531         // private
532         normalizeKey: function(k){
533             return Ext.isSafari ? (safariKeys[k] || k) : k; 
534         },
535
536         /**
537          * Gets the x coordinate of the event.
538          * @return {Number}
539          */
540         getPageX : function(){
541             return this.xy[0];
542         },
543
544         /**
545          * Gets the y coordinate of the event.
546          * @return {Number}
547          */
548         getPageY : function(){
549             return this.xy[1];
550         },
551
552         /**
553          * Gets the page coordinates of the event.
554          * @return {Array} The xy values like [x, y]
555          */
556         getXY : function(){
557             return this.xy;
558         },
559
560         /**
561          * Gets the target for the event.
562          * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
563          * @param {Number/Mixed} maxDepth (optional) The max depth to
564                 search as a number or element (defaults to 10 || document.body)
565          * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
566          * @return {HTMLelement}
567          */
568         getTarget : function(selector, maxDepth, returnEl){
569             return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target);
570         },
571
572         /**
573          * Gets the related target.
574          * @return {HTMLElement}
575          */
576         getRelatedTarget : function(){
577             return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null;
578         },
579
580         /**
581          * Normalizes mouse wheel delta across browsers
582          * @return {Number} The delta
583          */
584         getWheelDelta : function(){
585             var e = this.browserEvent;
586             var delta = 0;
587             if(e.wheelDelta){ /* IE/Opera. */
588                 delta = e.wheelDelta/120;
589             }else if(e.detail){ /* Mozilla case. */
590                 delta = -e.detail/3;
591             }
592             return delta;
593         },
594         
595         /**
596         * Returns true if the target of this event is a child of el.  Unless the allowEl parameter is set, it will return false if if the target is el.
597         * Example usage:<pre><code>
598         // Handle click on any child of an element
599         Ext.getBody().on('click', function(e){
600             if(e.within('some-el')){
601                 alert('Clicked on a child of some-el!');
602             }
603         });
604         
605         // Handle click directly on an element, ignoring clicks on child nodes
606         Ext.getBody().on('click', function(e,t){
607             if((t.id == 'some-el') && !e.within(t, true)){
608                 alert('Clicked directly on some-el!');
609             }
610         });
611         </code></pre>
612          * @param {Mixed} el The id, DOM element or Ext.Element to check
613          * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
614          * @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target
615          * @return {Boolean}
616          */
617         within : function(el, related, allowEl){
618             if(el){
619                 var t = this[related ? "getRelatedTarget" : "getTarget"]();
620                 return t && ((allowEl ? (t == Ext.getDom(el)) : false) || Ext.fly(el).contains(t));
621             }
622             return false;
623         }
624      };
625
626     return new Ext.EventObjectImpl();
627 }();