KeyMap.html
17.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The source code</title>
<link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="../resources/prettify/prettify.js"></script>
<style type="text/css">
.highlight { display: block; background-color: #ddd; }
</style>
<script type="text/javascript">
function highlight() {
document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
}
</script>
</head>
<body onload="prettyPrint(); highlight();">
<pre class="prettyprint lang-js"><span id='Ext-util-KeyMap'>/**
</span> * Handles mapping key events to handling functions for an element or a Component. One KeyMap can be used for multiple
* actions.
*
* A KeyMap must be configured with a {@link #target} as an event source which may be an Element or a Component.
*
* If the target is an element, then the `keydown` event will trigger the invocation of {@link #binding}s.
*
* It is possible to configure the KeyMap with a custom {@link #eventName} to listen for. This may be useful when the
* {@link #target} is a Component.
*
* The KeyMap's event handling requires that the first parameter passed is a key event. So if the Component's event
* signature is different, specify a {@link #processEvent} configuration which accepts the event's parameters and
* returns a key event.
*
* Functions specified in {@link #binding}s are called with this signature : `(String key, Ext.EventObject e)` (if the
* match is a multi-key combination the callback will still be called only once). A KeyMap can also handle a string
* representation of keys. By default KeyMap starts enabled.
*
* Usage:
*
* // map one key by key code
* var map = new Ext.util.KeyMap({
* target: "my-element",
* key: 13, // or Ext.EventObject.ENTER
* fn: myHandler,
* scope: myObject
* });
*
* // map multiple keys to one action by string
* var map = new Ext.util.KeyMap({
* target: "my-element",
* key: "a\r\n\t",
* fn: myHandler,
* scope: myObject
* });
*
* // map multiple keys to multiple actions by strings and array of codes
* var map = new Ext.util.KeyMap({
* target: "my-element",
* binding: [{
* key: [10,13],
* fn: function(){ alert("Return was pressed"); }
* }, {
* key: "abc",
* fn: function(){ alert('a, b or c was pressed'); }
* }, {
* key: "\t",
* ctrl:true,
* shift:true,
* fn: function(){ alert('Control + shift + tab was pressed.'); }
* }]
* });
*
* Since 4.1.0, KeyMaps can bind to Components and process key-based events fired by Components.
*
* To bind to a Component, use the single parameter form of constructor and include the Component event name
* to listen for, and a `processEvent` implementation which returns the key event for further processing by
* the KeyMap:
*
* var map = new Ext.util.KeyMap({
* target: myGridView,
* eventName: 'itemkeydown',
* processEvent: function(view, record, node, index, event) {
*
* // Load the event with the extra information needed by the mappings
* event.view = view;
* event.store = view.getStore();
* event.record = record;
* event.index = index;
* return event;
* },
* binding: {
* key: Ext.EventObject.DELETE,
* fn: function(keyCode, e) {
* e.store.remove(e.record);
*
* // Attempt to select the record that's now in its place
* e.view.getSelectionModel().select(e.index);
* e.view.el.focus();
* }
* }
* });
*/
Ext.define('Ext.util.KeyMap', {
alternateClassName: 'Ext.KeyMap',
<span id='Ext-util-KeyMap-cfg-target'> /**
</span> * @cfg {Ext.Component/Ext.Element/HTMLElement/String} target
* The object on which to listen for the event specified by the {@link #eventName} config option.
*/
<span id='Ext-util-KeyMap-cfg-binding'> /**
</span> * @cfg {Object/Object[][]} binding
* Either a single object describing a handling function for s specified key (or set of keys), or
* an array of such objects.
* @cfg {String/String[]} binding.key A single keycode or an array of keycodes to handle
* @cfg {Boolean} binding.shift True to handle key only when shift is pressed, False to handle the
* key only when shift is not pressed (defaults to undefined)
* @cfg {Boolean} binding.ctrl True to handle key only when ctrl is pressed, False to handle the
* key only when ctrl is not pressed (defaults to undefined)
* @cfg {Boolean} binding.alt True to handle key only when alt is pressed, False to handle the key
* only when alt is not pressed (defaults to undefined)
* @cfg {Function} binding.handler The function to call when KeyMap finds the expected key combination
* @cfg {Function} binding.fn Alias of handler (for backwards-compatibility)
* @cfg {Object} binding.scope The scope of the callback function
* @cfg {String} binding.defaultEventAction A default action to apply to the event. Possible values
* are: stopEvent, stopPropagation, preventDefault. If no value is set no action is performed.
*/
<span id='Ext-util-KeyMap-cfg-processEventScope'> /**
</span> * @cfg {Object} [processEventScope=this]
* The scope (`this` context) in which the {@link #processEvent} method is executed.
*/
<span id='Ext-util-KeyMap-cfg-ignoreInputFields'> /**
</span> * @cfg {Boolean} [ignoreInputFields=false]
* Configure this as `true` if there are any input fields within the {@link #target}, and this KeyNav
* should not process events from input fields, (`&lt;input>, &lt;textarea> and elements with `contentEditable="true"`)
*/
<span id='Ext-util-KeyMap-cfg-eventName'> /**
</span> * @cfg {String} eventName
* The event to listen for to pick up key events.
*/
eventName: 'keydown',
constructor: function(config) {
var me = this;
// Handle legacy arg list in which the first argument is the target.
// TODO: Deprecate in V5
if ((arguments.length !== 1) || (typeof config === 'string') || config.dom || config.tagName || config === document || config.isComponent) {
me.legacyConstructor.apply(me, arguments);
return;
}
Ext.apply(me, config);
me.bindings = [];
if (!me.target.isComponent) {
me.target = Ext.get(me.target);
}
if (me.binding) {
me.addBinding(me.binding);
} else if (config.key) {
me.addBinding(config);
}
me.enable();
},
<span id='Ext-util-KeyMap-method-legacyConstructor'> /**
</span> * @private
* Old constructor signature
* @param {String/HTMLElement/Ext.Element/Ext.Component} el The element or its ID, or Component to bind to
* @param {Object} binding The binding (see {@link #addBinding})
* @param {String} [eventName="keydown"] The event to bind to
*/
legacyConstructor: function(el, binding, eventName){
var me = this;
Ext.apply(me, {
target: Ext.get(el),
eventName: eventName || me.eventName,
bindings: []
});
if (binding) {
me.addBinding(binding);
}
me.enable();
},
<span id='Ext-util-KeyMap-method-addBinding'> /**
</span> * Add a new binding to this KeyMap.
*
* Usage:
*
* // Create a KeyMap
* var map = new Ext.util.KeyMap(document, {
* key: Ext.EventObject.ENTER,
* fn: handleKey,
* scope: this
* });
*
* //Add a new binding to the existing KeyMap later
* map.addBinding({
* key: 'abc',
* shift: true,
* fn: handleKey,
* scope: this
* });
*
* @param {Object/Object[]} binding A single KeyMap config or an array of configs.
* The following config object properties are supported:
* @param {String/Array} binding.key A single keycode or an array of keycodes to handle.
* @param {Boolean} binding.shift True to handle key only when shift is pressed,
* False to handle the keyonly when shift is not pressed (defaults to undefined).
* @param {Boolean} binding.ctrl True to handle key only when ctrl is pressed,
* False to handle the key only when ctrl is not pressed (defaults to undefined).
* @param {Boolean} binding.alt True to handle key only when alt is pressed,
* False to handle the key only when alt is not pressed (defaults to undefined).
* @param {Function} binding.handler The function to call when KeyMap finds the
* expected key combination.
* @param {Function} binding.fn Alias of handler (for backwards-compatibility).
* @param {Object} binding.scope The scope of the callback function.
* @param {String} binding.defaultEventAction A default action to apply to the event.
* Possible values are: stopEvent, stopPropagation, preventDefault. If no value is
* set no action is performed..
*/
addBinding : function(binding){
var keyCode = binding.key,
processed = false,
key,
keys,
keyString,
i,
len;
if (Ext.isArray(binding)) {
for (i = 0, len = binding.length; i < len; i++) {
this.addBinding(binding[i]);
}
return;
}
if (Ext.isString(keyCode)) {
keys = [];
keyString = keyCode.toUpperCase();
for (i = 0, len = keyString.length; i < len; ++i){
keys.push(keyString.charCodeAt(i));
}
keyCode = keys;
processed = true;
}
if (!Ext.isArray(keyCode)) {
keyCode = [keyCode];
}
if (!processed) {
for (i = 0, len = keyCode.length; i < len; ++i) {
key = keyCode[i];
if (Ext.isString(key)) {
keyCode[i] = key.toUpperCase().charCodeAt(0);
}
}
}
this.bindings.push(Ext.apply({
keyCode: keyCode
}, binding));
},
<span id='Ext-util-KeyMap-method-handleTargetEvent'> /**
</span> * Process the {@link #eventName event} from the {@link #target}.
* @private
* @param {Ext.EventObject} event
*/
handleTargetEvent: (function() {
var tagRe = /input|textarea/i;
return function(event) {
var me = this,
bindings, i, len,
target, contentEditable;
if (this.enabled) { //just in case
bindings = this.bindings;
i = 0;
len = bindings.length;
// Process the event
event = me.processEvent.apply(me||me.processEventScope, arguments);
// Ignore events from input fields if configured to do so
if (me.ignoreInputFields) {
target = event.target;
contentEditable = target.contentEditable;
// contentEditable will default to inherit if not specified, only check if the
// attribute has been set or explicitly set to true
// http://html5doctor.com/the-contenteditable-attribute/
if (tagRe.test(target.tagName) || (contentEditable === '' || contentEditable === 'true')) {
return;
}
}
// If the processor does not return a keyEvent, we can't process it.
// Allow them to return false to cancel processing of the event
if (!event.getKey) {
return event;
}
for(; i < len; ++i){
this.processBinding(bindings[i], event);
}
}
}
}()),
<span id='Ext-util-KeyMap-cfg-processEvent'> /**
</span> * @cfg {Function} processEvent
* An optional event processor function which accepts the argument list provided by the
* {@link #eventName configured event} of the {@link #target}, and returns a keyEvent for processing by the KeyMap.
*
* This may be useful when the {@link #target} is a Component with s complex event signature, where the event is not
* the first parameter. Extra information from the event arguments may be injected into the event for use by the handler
* functions before returning it.
*/
processEvent: function(event){
return event;
},
<span id='Ext-util-KeyMap-method-processBinding'> /**
</span> * Process a particular binding and fire the handler if necessary.
* @private
* @param {Object} binding The binding information
* @param {Ext.EventObject} event
*/
processBinding: function(binding, event){
if (this.checkModifiers(binding, event)) {
var key = event.getKey(),
handler = binding.fn || binding.handler,
scope = binding.scope || this,
keyCode = binding.keyCode,
defaultEventAction = binding.defaultEventAction,
i,
len,
keydownEvent = new Ext.EventObjectImpl(event);
for (i = 0, len = keyCode.length; i < len; ++i) {
if (key === keyCode[i]) {
if (handler.call(scope, key, event) !== true && defaultEventAction) {
keydownEvent[defaultEventAction]();
}
break;
}
}
}
},
<span id='Ext-util-KeyMap-method-checkModifiers'> /**
</span> * Check if the modifiers on the event match those on the binding
* @private
* @param {Object} binding
* @param {Ext.EventObject} event
* @return {Boolean} True if the event matches the binding
*/
checkModifiers: function(binding, e) {
var keys = ['shift', 'ctrl', 'alt'],
i = 0,
len = keys.length,
val, key;
for (; i < len; ++i){
key = keys[i];
val = binding[key];
if (!(val === undefined || (val === e[key + 'Key']))) {
return false;
}
}
return true;
},
<span id='Ext-util-KeyMap-method-on'> /**
</span> * Shorthand for adding a single key listener.
*
* @param {Number/Number[]/Object} key Either the numeric key code, array of key codes or an object with the
* following options: `{key: (number or array), shift: (true/false), ctrl: (true/false), alt: (true/false)}`
* @param {Function} fn The function to call
* @param {Object} [scope] The scope (`this` reference) in which the function is executed.
* Defaults to the browser window.
*/
on: function(key, fn, scope) {
var keyCode, shift, ctrl, alt;
if (Ext.isObject(key) && !Ext.isArray(key)) {
keyCode = key.key;
shift = key.shift;
ctrl = key.ctrl;
alt = key.alt;
} else {
keyCode = key;
}
this.addBinding({
key: keyCode,
shift: shift,
ctrl: ctrl,
alt: alt,
fn: fn,
scope: scope
});
},
<span id='Ext-util-KeyMap-method-isEnabled'> /**
</span> * Returns true if this KeyMap is enabled
* @return {Boolean}
*/
isEnabled : function() {
return this.enabled;
},
<span id='Ext-util-KeyMap-method-enable'> /**
</span> * Enables this KeyMap
*/
enable: function() {
var me = this;
if (!me.enabled) {
me.target.on(me.eventName, me.handleTargetEvent, me);
me.enabled = true;
}
},
<span id='Ext-util-KeyMap-method-disable'> /**
</span> * Disable this KeyMap
*/
disable: function() {
var me = this;
if (me.enabled) {
me.target.removeListener(me.eventName, me.handleTargetEvent, me);
me.enabled = false;
}
},
<span id='Ext-util-KeyMap-method-setDisabled'> /**
</span> * Convenience function for setting disabled/enabled by boolean.
* @param {Boolean} disabled
*/
setDisabled : function(disabled) {
if (disabled) {
this.disable();
} else {
this.enable();
}
},
<span id='Ext-util-KeyMap-method-destroy'> /**
</span> * Destroys the KeyMap instance and removes all handlers.
* @param {Boolean} removeTarget True to also remove the {@link #target}
*/
destroy: function(removeTarget) {
var me = this,
target = me.target;
me.bindings = [];
me.disable();
if (removeTarget === true) {
if (target.isComponent) {
target.destroy();
} else {
target.remove();
}
}
delete me.target;
}
});</pre>
</body>
</html>