Upgrade to ExtJS 3.0.0 - Released 07/06/2009
[extjs.git] / src / core / core / EventManager.js
1 /*!
2  * Ext JS Library 3.0.0
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 type of 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 event
241          * @param {String} eventName The type of event
242          * @param {Function} fn The handler function to remove
243          */
244         removeListener : function(element, eventName, fn, scope){            
245             var el = Ext.getDom(element),
246                 id = Ext.id(el),
247                     wrap;      
248                 
249                 Ext.each((elHash[id] || {})[eventName], function (v,i,a) {
250                             if (Ext.isArray(v) && v[0] == fn && (!scope || v[2] == scope)) {                                                    
251                                 E.un(el, eventName, wrap = v[1]);
252                                 a.splice(i,1);
253                                 return false;                           
254                         }
255                 });     
256
257             // jQuery workaround that should be removed from Ext Core
258                 if(eventName == "mousewheel" && el.addEventListener && wrap){
259                     el.removeEventListener("DOMMouseScroll", wrap, false);
260                 }
261                         
262                 if(eventName == "mousedown" && el == DOC && wrap){ // fix stopped mousedowns on the document
263                     Ext.EventManager.stoppedMouseDownEvent.removeListener(wrap);
264                 }
265         },
266         
267         /**
268          * Removes all event handers from an element.  Typically you will use {@link Ext.Element#removeAllListeners}
269          * directly on an Element in favor of calling this version.
270          * @param {String/HTMLElement} el The id or html element from which to remove the event
271          */
272         removeAll : function(el){
273                 var id = Ext.id(el = Ext.getDom(el)), 
274                                 es = elHash[id],                                
275                                 ename;
276                
277                 for(ename in es){
278                     if(es.hasOwnProperty(ename)){                           
279                         Ext.each(es[ename], function(v) {
280                             E.un(el, ename, v.wrap);                    
281                         });
282                     }            
283                 }
284                 elHash[id] = null;       
285         },
286
287         /**
288          * Fires when the document is ready (before onload and before images are loaded). Can be
289          * accessed shorthanded as Ext.onReady().
290          * @param {Function} fn The method the event invokes
291          * @param {Object} scope (optional) An object that becomes the scope of the handler
292          * @param {boolean} options (optional) An object containing standard {@link #addListener} options
293          */
294         onDocumentReady : function(fn, scope, options){
295             if(docReadyState){ // if it already fired
296                 docReadyEvent.addListener(fn, scope, options);
297                 docReadyEvent.fire();
298                 docReadyEvent.clearListeners();               
299             } else {
300                 if(!docReadyEvent) initDocReady();
301                 options = options || {};
302                     options.delay = options.delay || 1;             
303                     docReadyEvent.addListener(fn, scope, options);
304             }
305         },
306         
307         elHash : elHash   
308     };
309      /**
310      * Appends an event handler to an element.  Shorthand for {@link #addListener}.
311      * @param {String/HTMLElement} el The html element or id to assign the event handler to
312      * @param {String} eventName The type of event to listen for
313      * @param {Function} handler The handler function the event invokes
314      * @param {Object} scope (optional) The scope in which to execute the handler
315      * function (the handler function's "this" context)
316      * @param {Object} options (optional) An object containing standard {@link #addListener} options
317      * @member Ext.EventManager
318      * @method on
319      */
320     pub.on = pub.addListener;
321     /**
322      * Removes an event handler from an element.  Shorthand for {@link #removeListener}.
323      * @param {String/HTMLElement} el The id or html element from which to remove the event
324      * @param {String} eventName The type of event
325      * @param {Function} fn The handler function to remove
326      * @return {Boolean} True if a listener was actually removed, else false
327      * @member Ext.EventManager
328      * @method un
329      */
330     pub.un = pub.removeListener;
331
332     pub.stoppedMouseDownEvent = new Ext.util.Event();
333     return pub;
334 }();
335 /**
336   * Fires when the document is ready (before onload and before images are loaded).  Shorthand of {@link Ext.EventManager#onDocumentReady}.
337   * @param {Function} fn The method the event invokes
338   * @param {Object} scope An object that becomes the scope of the handler
339   * @param {boolean} options (optional) An object containing standard {@link #addListener} options
340   * @member Ext
341   * @method onReady
342  */
343 Ext.onReady = Ext.EventManager.onDocumentReady;
344
345
346 //Initialize doc classes
347 (function(){
348     
349     var initExtCss = function(){
350         // find the body element
351         var bd = document.body || document.getElementsByTagName('body')[0];
352         if(!bd){ return false; }
353         var cls = [' ',
354                 Ext.isIE ? "ext-ie " + (Ext.isIE6 ? 'ext-ie6' : (Ext.isIE7 ? 'ext-ie7' : 'ext-ie8'))
355                 : Ext.isGecko ? "ext-gecko " + (Ext.isGecko2 ? 'ext-gecko2' : 'ext-gecko3')
356                 : Ext.isOpera ? "ext-opera"
357                 : Ext.isWebKit ? "ext-webkit" : ""];
358
359         if(Ext.isSafari){
360             cls.push("ext-safari " + (Ext.isSafari2 ? 'ext-safari2' : (Ext.isSafari3 ? 'ext-safari3' : 'ext-safari4')));
361         }else if(Ext.isChrome){
362             cls.push("ext-chrome");
363         }
364
365         if(Ext.isMac){
366             cls.push("ext-mac");
367         }
368         if(Ext.isLinux){
369             cls.push("ext-linux");
370         }
371
372         if(Ext.isStrict || Ext.isBorderBox){ // add to the parent to allow for selectors like ".ext-strict .ext-ie"
373             var p = bd.parentNode;
374             if(p){
375                 p.className += Ext.isStrict ? ' ext-strict' : ' ext-border-box';
376             }
377         }
378         bd.className += cls.join(' ');
379         return true;
380     }
381
382     if(!initExtCss()){
383         Ext.onReady(initExtCss);
384     }
385 })();
386
387
388 /**
389  * @class Ext.EventObject
390  * Just as {@link Ext.Element} wraps around a native DOM node, Ext.EventObject 
391  * wraps the browser's native event-object normalizing cross-browser differences,
392  * such as which mouse button is clicked, keys pressed, mechanisms to stop
393  * event-propagation along with a method to prevent default actions from taking place.
394  * <p>For example:</p>
395  * <pre><code>
396 function handleClick(e, t){ // e is not a standard event object, it is a Ext.EventObject
397     e.preventDefault();
398     var target = e.getTarget(); // same as t (the target HTMLElement)
399     ...
400 }
401 var myDiv = {@link Ext#get Ext.get}("myDiv");  // get reference to an {@link Ext.Element}
402 myDiv.on(         // 'on' is shorthand for addListener
403     "click",      // perform an action on click of myDiv
404     handleClick   // reference to the action handler
405 );  
406 // other methods to do the same:
407 Ext.EventManager.on("myDiv", 'click', handleClick);
408 Ext.EventManager.addListener("myDiv", 'click', handleClick);
409  </code></pre>
410  * @singleton
411  */
412 Ext.EventObject = function(){
413     var E = Ext.lib.Event,
414         // safari keypress events for special keys return bad keycodes
415         safariKeys = {
416                 3 : 13, // enter
417                 63234 : 37, // left
418                 63235 : 39, // right
419                 63232 : 38, // up
420                 63233 : 40, // down
421                 63276 : 33, // page up
422                 63277 : 34, // page down
423                 63272 : 46, // delete
424                 63273 : 36, // home
425                 63275 : 35  // end
426         },
427         // normalize button clicks
428         btnMap = Ext.isIE ? {1:0,4:1,2:2} :
429                 (Ext.isWebKit ? {1:0,2:1,3:2} : {0:0,1:1,2:2});
430
431     Ext.EventObjectImpl = function(e){
432         if(e){
433             this.setEvent(e.browserEvent || e);
434         }
435     };
436
437     Ext.EventObjectImpl.prototype = {
438            /** @private */
439         setEvent : function(e){
440                 var me = this;
441             if(e == me || (e && e.browserEvent)){ // already wrapped
442                 return e;
443             }
444             me.browserEvent = e;
445             if(e){
446                 // normalize buttons
447                 me.button = e.button ? btnMap[e.button] : (e.which ? e.which - 1 : -1);
448                 if(e.type == 'click' && me.button == -1){
449                     me.button = 0;
450                 }
451                 me.type = e.type;
452                 me.shiftKey = e.shiftKey;
453                 // mac metaKey behaves like ctrlKey
454                 me.ctrlKey = e.ctrlKey || e.metaKey || false;
455                 me.altKey = e.altKey;
456                 // in getKey these will be normalized for the mac
457                 me.keyCode = e.keyCode;
458                 me.charCode = e.charCode;
459                 // cache the target for the delayed and or buffered events
460                 me.target = E.getTarget(e);
461                 // same for XY
462                 me.xy = E.getXY(e);
463             }else{
464                 me.button = -1;
465                 me.shiftKey = false;
466                 me.ctrlKey = false;
467                 me.altKey = false;
468                 me.keyCode = 0;
469                 me.charCode = 0;
470                 me.target = null;
471                 me.xy = [0, 0];
472             }
473             return me;
474         },
475
476         /**
477          * Stop the event (preventDefault and stopPropagation)
478          */
479         stopEvent : function(){
480                 var me = this;
481             if(me.browserEvent){
482                 if(me.browserEvent.type == 'mousedown'){
483                     Ext.EventManager.stoppedMouseDownEvent.fire(me);
484                 }
485                 E.stopEvent(me.browserEvent);
486             }
487         },
488
489         /**
490          * Prevents the browsers default handling of the event.
491          */
492         preventDefault : function(){
493             if(this.browserEvent){
494                 E.preventDefault(this.browserEvent);
495             }
496         },        
497
498         /**
499          * Cancels bubbling of the event.
500          */
501         stopPropagation : function(){
502                 var me = this;
503             if(me.browserEvent){
504                 if(me.browserEvent.type == 'mousedown'){
505                     Ext.EventManager.stoppedMouseDownEvent.fire(me);
506                 }
507                 E.stopPropagation(me.browserEvent);
508             }
509         },
510
511         /**
512          * Gets the character code for the event.
513          * @return {Number}
514          */
515         getCharCode : function(){
516             return this.charCode || this.keyCode;
517         },
518
519         /**
520          * Returns a normalized keyCode for the event.
521          * @return {Number} The key code
522          */
523         getKey : function(){
524             return this.normalizeKey(this.keyCode || this.charCode)
525         },
526                 
527                 // private
528                 normalizeKey: function(k){
529                         return Ext.isSafari ? (safariKeys[k] || k) : k; 
530                 },
531
532         /**
533          * Gets the x coordinate of the event.
534          * @return {Number}
535          */
536         getPageX : function(){
537             return this.xy[0];
538         },
539
540         /**
541          * Gets the y coordinate of the event.
542          * @return {Number}
543          */
544         getPageY : function(){
545             return this.xy[1];
546         },
547
548         /**
549          * Gets the page coordinates of the event.
550          * @return {Array} The xy values like [x, y]
551          */
552         getXY : function(){
553             return this.xy;
554         },
555
556         /**
557          * Gets the target for the event.
558          * @param {String} selector (optional) A simple selector to filter the target or look for an ancestor of the target
559          * @param {Number/Mixed} maxDepth (optional) The max depth to
560                 search as a number or element (defaults to 10 || document.body)
561          * @param {Boolean} returnEl (optional) True to return a Ext.Element object instead of DOM node
562          * @return {HTMLelement}
563          */
564         getTarget : function(selector, maxDepth, returnEl){
565             return selector ? Ext.fly(this.target).findParent(selector, maxDepth, returnEl) : (returnEl ? Ext.get(this.target) : this.target);
566         },
567
568         /**
569          * Gets the related target.
570          * @return {HTMLElement}
571          */
572         getRelatedTarget : function(){
573             return this.browserEvent ? E.getRelatedTarget(this.browserEvent) : null;
574         },
575
576         /**
577          * Normalizes mouse wheel delta across browsers
578          * @return {Number} The delta
579          */
580         getWheelDelta : function(){
581             var e = this.browserEvent;
582             var delta = 0;
583             if(e.wheelDelta){ /* IE/Opera. */
584                 delta = e.wheelDelta/120;
585             }else if(e.detail){ /* Mozilla case. */
586                 delta = -e.detail/3;
587             }
588             return delta;
589         },
590                 
591                 /**
592                 * 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.
593                 * Example usage:<pre><code>
594                 // Handle click on any child of an element
595                 Ext.getBody().on('click', function(e){
596                         if(e.within('some-el')){
597                                 alert('Clicked on a child of some-el!');
598                         }
599                 });
600                 
601                 // Handle click directly on an element, ignoring clicks on child nodes
602                 Ext.getBody().on('click', function(e,t){
603                         if((t.id == 'some-el') && !e.within(t, true)){
604                                 alert('Clicked directly on some-el!');
605                         }
606                 });
607                 </code></pre>
608                  * @param {Mixed} el The id, DOM element or Ext.Element to check
609                  * @param {Boolean} related (optional) true to test if the related target is within el instead of the target
610                  * @param {Boolean} allowEl {optional} true to also check if the passed element is the target or related target
611                  * @return {Boolean}
612                  */
613                 within : function(el, related, allowEl){
614             if(el){
615                             var t = this[related ? "getRelatedTarget" : "getTarget"]();
616                             return t && ((allowEl ? (t == Ext.getDom(el)) : false) || Ext.fly(el).contains(t));
617             }
618             return false;
619                 }
620          };
621
622     return new Ext.EventObjectImpl();
623 }();