Upgrade to ExtJS 3.1.0 - Released 12/16/2009
[extjs.git] / src / util / KeyMap.js
1 /*!
2  * Ext JS Library 3.1.0
3  * Copyright(c) 2006-2009 Ext JS, LLC
4  * licensing@extjs.com
5  * http://www.extjs.com/license
6  */
7 /**\r
8  * @class Ext.KeyMap\r
9  * Handles mapping keys to actions for an element. One key map can be used for multiple actions.\r
10  * The constructor accepts the same config object as defined by {@link #addBinding}.\r
11  * If you bind a callback function to a KeyMap, anytime the KeyMap handles an expected key\r
12  * combination it will call the function with this signature (if the match is a multi-key\r
13  * combination the callback will still be called only once): (String key, Ext.EventObject e)\r
14  * A KeyMap can also handle a string representation of keys.<br />\r
15  * Usage:\r
16  <pre><code>\r
17 // map one key by key code\r
18 var map = new Ext.KeyMap("my-element", {\r
19     key: 13, // or Ext.EventObject.ENTER\r
20     fn: myHandler,\r
21     scope: myObject\r
22 });\r
23 \r
24 // map multiple keys to one action by string\r
25 var map = new Ext.KeyMap("my-element", {\r
26     key: "a\r\n\t",\r
27     fn: myHandler,\r
28     scope: myObject\r
29 });\r
30 \r
31 // map multiple keys to multiple actions by strings and array of codes\r
32 var map = new Ext.KeyMap("my-element", [\r
33     {\r
34         key: [10,13],\r
35         fn: function(){ alert("Return was pressed"); }\r
36     }, {\r
37         key: "abc",\r
38         fn: function(){ alert('a, b or c was pressed'); }\r
39     }, {\r
40         key: "\t",\r
41         ctrl:true,\r
42         shift:true,\r
43         fn: function(){ alert('Control + shift + tab was pressed.'); }\r
44     }\r
45 ]);\r
46 </code></pre>\r
47  * <b>Note: A KeyMap starts enabled</b>\r
48  * @constructor\r
49  * @param {Mixed} el The element to bind to\r
50  * @param {Object} config The config (see {@link #addBinding})\r
51  * @param {String} eventName (optional) The event to bind to (defaults to "keydown")\r
52  */\r
53 Ext.KeyMap = function(el, config, eventName){\r
54     this.el  = Ext.get(el);\r
55     this.eventName = eventName || "keydown";\r
56     this.bindings = [];\r
57     if(config){\r
58         this.addBinding(config);\r
59     }\r
60     this.enable();\r
61 };\r
62 \r
63 Ext.KeyMap.prototype = {\r
64     /**\r
65      * True to stop the event from bubbling and prevent the default browser action if the\r
66      * key was handled by the KeyMap (defaults to false)\r
67      * @type Boolean\r
68      */\r
69     stopEvent : false,\r
70 \r
71     /**\r
72      * Add a new binding to this KeyMap. The following config object properties are supported:\r
73      * <pre>\r
74 Property    Type             Description\r
75 ----------  ---------------  ----------------------------------------------------------------------\r
76 key         String/Array     A single keycode or an array of keycodes to handle\r
77 shift       Boolean          True to handle key only when shift is pressed, False to handle the key only when shift is not pressed (defaults to undefined)\r
78 ctrl        Boolean          True to handle key only when ctrl is pressed, False to handle the key only when ctrl is not pressed (defaults to undefined)\r
79 alt         Boolean          True to handle key only when alt is pressed, False to handle the key only when alt is not pressed (defaults to undefined)\r
80 handler     Function         The function to call when KeyMap finds the expected key combination\r
81 fn          Function         Alias of handler (for backwards-compatibility)\r
82 scope       Object           The scope of the callback function\r
83 stopEvent   Boolean          True to stop the event from bubbling and prevent the default browser action if the key was handled by the KeyMap (defaults to false)\r
84 </pre>\r
85      *\r
86      * Usage:\r
87      * <pre><code>\r
88 // Create a KeyMap\r
89 var map = new Ext.KeyMap(document, {\r
90     key: Ext.EventObject.ENTER,\r
91     fn: handleKey,\r
92     scope: this\r
93 });\r
94 \r
95 //Add a new binding to the existing KeyMap later\r
96 map.addBinding({\r
97     key: 'abc',\r
98     shift: true,\r
99     fn: handleKey,\r
100     scope: this\r
101 });\r
102 </code></pre>\r
103      * @param {Object/Array} config A single KeyMap config or an array of configs\r
104      */\r
105         addBinding : function(config){\r
106         if(Ext.isArray(config)){\r
107             Ext.each(config, function(c){\r
108                 this.addBinding(c);\r
109             }, this);\r
110             return;\r
111         }\r
112         var keyCode = config.key,\r
113             fn = config.fn || config.handler,\r
114             scope = config.scope;\r
115 \r
116         if (config.stopEvent) {\r
117             this.stopEvent = config.stopEvent;    \r
118         }       \r
119 \r
120         if(typeof keyCode == "string"){\r
121             var ks = [];\r
122             var keyString = keyCode.toUpperCase();\r
123             for(var j = 0, len = keyString.length; j < len; j++){\r
124                 ks.push(keyString.charCodeAt(j));\r
125             }\r
126             keyCode = ks;\r
127         }\r
128         var keyArray = Ext.isArray(keyCode);\r
129         \r
130         var handler = function(e){\r
131             if(this.checkModifiers(config, e)){\r
132                 var k = e.getKey();\r
133                 if(keyArray){\r
134                     for(var i = 0, len = keyCode.length; i < len; i++){\r
135                         if(keyCode[i] == k){\r
136                           if(this.stopEvent){\r
137                               e.stopEvent();\r
138                           }\r
139                           fn.call(scope || window, k, e);\r
140                           return;\r
141                         }\r
142                     }\r
143                 }else{\r
144                     if(k == keyCode){\r
145                         if(this.stopEvent){\r
146                            e.stopEvent();\r
147                         }\r
148                         fn.call(scope || window, k, e);\r
149                     }\r
150                 }\r
151             }\r
152         };\r
153         this.bindings.push(handler);\r
154         },\r
155     \r
156     // private\r
157     checkModifiers: function(config, e){\r
158         var val, key, keys = ['shift', 'ctrl', 'alt'];\r
159         for (var i = 0, len = keys.length; i < len; ++i){\r
160             key = keys[i];\r
161             val = config[key];\r
162             if(!(val === undefined || (val === e[key + 'Key']))){\r
163                 return false;\r
164             }\r
165         }\r
166         return true;\r
167     },\r
168 \r
169     /**\r
170      * Shorthand for adding a single key listener\r
171      * @param {Number/Array/Object} key Either the numeric key code, array of key codes or an object with the\r
172      * following options:\r
173      * {key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}\r
174      * @param {Function} fn The function to call\r
175      * @param {Object} scope (optional) The scope (<code>this</code> reference) in which the function is executed. Defaults to the browser window.\r
176      */\r
177     on : function(key, fn, scope){\r
178         var keyCode, shift, ctrl, alt;\r
179         if(typeof key == "object" && !Ext.isArray(key)){\r
180             keyCode = key.key;\r
181             shift = key.shift;\r
182             ctrl = key.ctrl;\r
183             alt = key.alt;\r
184         }else{\r
185             keyCode = key;\r
186         }\r
187         this.addBinding({\r
188             key: keyCode,\r
189             shift: shift,\r
190             ctrl: ctrl,\r
191             alt: alt,\r
192             fn: fn,\r
193             scope: scope\r
194         });\r
195     },\r
196 \r
197     // private\r
198     handleKeyDown : function(e){\r
199             if(this.enabled){ //just in case\r
200             var b = this.bindings;\r
201             for(var i = 0, len = b.length; i < len; i++){\r
202                 b[i].call(this, e);\r
203             }\r
204             }\r
205         },\r
206 \r
207         /**\r
208          * Returns true if this KeyMap is enabled\r
209          * @return {Boolean}\r
210          */\r
211         isEnabled : function(){\r
212             return this.enabled;\r
213         },\r
214 \r
215         /**\r
216          * Enables this KeyMap\r
217          */\r
218         enable: function(){\r
219                 if(!this.enabled){\r
220                     this.el.on(this.eventName, this.handleKeyDown, this);\r
221                     this.enabled = true;\r
222                 }\r
223         },\r
224 \r
225         /**\r
226          * Disable this KeyMap\r
227          */\r
228         disable: function(){\r
229                 if(this.enabled){\r
230                     this.el.removeListener(this.eventName, this.handleKeyDown, this);\r
231                     this.enabled = false;\r
232                 }\r
233         },\r
234     \r
235     /**\r
236      * Convenience function for setting disabled/enabled by boolean.\r
237      * @param {Boolean} disabled\r
238      */\r
239     setDisabled : function(disabled){\r
240         this[disabled ? "disable" : "enable"]();\r
241     }\r
242 };