Debian Codegraph @

closure-library/closure/goog/ui/keyboardshortcuthandler.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Generic keyboard shortcut handler.
17 *
18 * @author [email protected] (Emil A Eklund)
19 * @see ../demos/keyboardshortcuts.html
20 */
21
22 goog.provide('goog.ui.KeyboardShortcutEvent');
23 goog.provide('goog.ui.KeyboardShortcutHandler');
24 goog.provide('goog.ui.KeyboardShortcutHandler.EventType');
25 goog.provide('goog.ui.KeyboardShortcutHandler.Modifiers');
26
27 goog.require('goog.Timer');
28 goog.require('goog.array');
29 goog.require('goog.asserts');
30 goog.require('goog.dom.TagName');
31 goog.require('goog.events');
32 goog.require('goog.events.Event');
33 goog.require('goog.events.EventTarget');
34 goog.require('goog.events.EventType');
35 goog.require('goog.events.KeyCodes');
36 goog.require('goog.events.KeyNames');
37 goog.require('goog.events.Keys');
38 goog.require('goog.object');
39 goog.require('goog.userAgent');
40
41
42
43 /**
44 * Component for handling keyboard shortcuts. A shortcut is registered and bound
45 * to a specific identifier. Once the shortcut is triggered an event is fired
46 * with the identifier for the shortcut. This allows keyboard shortcuts to be
47 * customized without modifying the code that listens for them.
48 *
49 * Supports keyboard shortcuts triggered by a single key, a stroke stroke (key
50 * plus at least one modifier) and a sequence of keys or strokes.
51 *
52 * @param {goog.events.EventTarget|EventTarget} keyTarget Event target that the
53 * key event listener is attached to, typically the applications root
54 * container.
55 * @constructor
56 * @extends {goog.events.EventTarget}
57 */
58 goog.ui.KeyboardShortcutHandler = function(keyTarget) {
59 goog.events.EventTarget.call(this);
60
61 /**
62 * Registered keyboard shortcuts tree. Stored as a map with the keyCode and
63 * modifier(s) as the key and either a list of further strokes or the shortcut
64 * task identifier as the value.
65 * @type {!goog.ui.KeyboardShortcutHandler.SequenceTree_}
66 * @see #makeStroke_
67 * @private
68 */
69 this.shortcuts_ = {};
70
71 /**
72 * The currently active shortcut sequence tree, which represents the position
73 * in the complete shortcuts_ tree reached by recent key strokes.
74 * @type {!goog.ui.KeyboardShortcutHandler.SequenceTree_}
75 * @private
76 */
77 this.currentTree_ = this.shortcuts_;
78
79 /**
80 * The time (in ms, epoch time) of the last keystroke which made progress in
81 * the shortcut sequence tree (i.e. the time that currentTree_ was last set).
82 * Used for timing out stroke sequences.
83 * @type {number}
84 * @private
85 */
86 this.lastStrokeTime_ = 0;
87
88 /**
89 * List of numeric key codes for keys that are safe to always regarded as
90 * shortcuts, even if entered in a textarea or input field.
91 * @type {Object}
92 * @private
93 */
94 this.globalKeys_ = goog.object.createSet(
95 goog.ui.KeyboardShortcutHandler.DEFAULT_GLOBAL_KEYS_);
96
97 /**
98 * List of input types that should only accept ENTER as a shortcut.
99 * @type {Object}
100 * @private
101 */
102 this.textInputs_ = goog.object.createSet(
103 goog.ui.KeyboardShortcutHandler.DEFAULT_TEXT_INPUTS_);
104
105 /**
106 * Whether to always prevent the default action if a shortcut event is fired.
107 * @type {boolean}
108 * @private
109 */
110 this.alwaysPreventDefault_ = true;
111
112 /**
113 * Whether to always stop propagation if a shortcut event is fired.
114 * @type {boolean}
115 * @private
116 */
117 this.alwaysStopPropagation_ = false;
118
119 /**
120 * Whether to treat all shortcuts as if they had been passed
121 * to setGlobalKeys().
122 * @type {boolean}
123 * @private
124 */
125 this.allShortcutsAreGlobal_ = false;
126
127 /**
128 * Whether to treat shortcuts with modifiers as if they had been passed
129 * to setGlobalKeys(). Ignored if allShortcutsAreGlobal_ is true. Applies
130 * only to form elements (not content-editable).
131 * @type {boolean}
132 * @private
133 */
134 this.modifierShortcutsAreGlobal_ = true;
135
136 /**
137 * Whether to treat space key as a shortcut when the focused element is a
138 * checkbox, radiobutton or button.
139 * @type {boolean}
140 * @private
141 */
142 this.allowSpaceKeyOnButtons_ = false;
143
144 /**
145 * Tracks the currently pressed shortcut key, for Firefox.
146 * @type {?number}
147 * @private
148 */
149 this.activeShortcutKeyForGecko_ = null;
150
151 this.initializeKeyListener(keyTarget);
152 };
153 goog.inherits(goog.ui.KeyboardShortcutHandler, goog.events.EventTarget);
154 goog.tagUnsealableClass(goog.ui.KeyboardShortcutHandler);
155
156
157
158 /**
159 * A node in a keyboard shortcut sequence tree. A node is either:
160 * 1. A terminal node with a non-nullable shortcut string which is the
161 * identifier for the shortcut triggered by traversing the tree to that node.
162 * 2. An internal node with a null shortcut string and a
163 * {@code goog.ui.KeyboardShortcutHandler.SequenceTree_} representing the
164 * continued stroke sequences from this node.
165 * For clarity, the static factory methods for creating internal and terminal
166 * nodes below should be used rather than using this constructor directly.
167 * @param {string=} opt_shortcut The shortcut identifier, for terminal nodes.
168 * @constructor
169 * @struct
170 * @private
171 */
172 goog.ui.KeyboardShortcutHandler.SequenceNode_ = function(opt_shortcut) {
173 /** @const {?string} The shorcut action identifier, for terminal nodes. */
174 this.shortcut = opt_shortcut || null;
175
176 /** @const {goog.ui.KeyboardShortcutHandler.SequenceTree_} */
177 this.next = opt_shortcut ? null : {};
178 };
179
180
181 /**
182 * Creates a terminal shortcut sequence node for the given shortcut identifier.
183 * @param {string} shortcut The shortcut identifier.
184 * @return {!goog.ui.KeyboardShortcutHandler.SequenceNode_}
185 * @private
186 */
187 goog.ui.KeyboardShortcutHandler.createTerminalNode_ = function(shortcut) {
188 return new goog.ui.KeyboardShortcutHandler.SequenceNode_(shortcut);
189 };
190
191
192 /**
193 * Creates an internal shortcut sequence node - a non-terminal part of a
194 * keyboard sequence.
195 * @return {!goog.ui.KeyboardShortcutHandler.SequenceNode_}
196 * @private
197 */
198 goog.ui.KeyboardShortcutHandler.createInternalNode_ = function() {
199 return new goog.ui.KeyboardShortcutHandler.SequenceNode_();
200 };
201
202
203 /**
204 * A map of strokes (represented as strings) to the nodes reached by those
205 * strokes.
206 * @typedef {Object<string, goog.ui.KeyboardShortcutHandler.SequenceNode_>}
207 * @private
208 */
209 goog.ui.KeyboardShortcutHandler.SequenceTree_;
210
211
212 /**
213 * Maximum allowed delay, in milliseconds, allowed between the first and second
214 * key in a key sequence.
215 * @type {number}
216 */
217 goog.ui.KeyboardShortcutHandler.MAX_KEY_SEQUENCE_DELAY = 1500; // 1.5 sec
218
219
220 /**
221 * Bit values for modifier keys.
222 * @enum {number}
223 */
224 goog.ui.KeyboardShortcutHandler.Modifiers = {
225 NONE: 0,
226 SHIFT: 1,
227 CTRL: 2,
228 ALT: 4,
229 META: 8
230 };
231
232
233 /**
234 * Keys marked as global by default.
235 * @type {Array<goog.events.KeyCodes>}
236 * @private
237 */
238 goog.ui.KeyboardShortcutHandler.DEFAULT_GLOBAL_KEYS_ = [
239 goog.events.KeyCodes.ESC, goog.events.KeyCodes.F1, goog.events.KeyCodes.F2,
240 goog.events.KeyCodes.F3, goog.events.KeyCodes.F4, goog.events.KeyCodes.F5,
241 goog.events.KeyCodes.F6, goog.events.KeyCodes.F7, goog.events.KeyCodes.F8,
242 goog.events.KeyCodes.F9, goog.events.KeyCodes.F10, goog.events.KeyCodes.F11,
243 goog.events.KeyCodes.F12, goog.events.KeyCodes.PAUSE
244 ];
245
246
247 /**
248 * Text input types to allow only ENTER shortcuts.
249 * Web Forms 2.0 for HTML5: Section 4.10.7 from 29 May 2012.
250 * @type {Array<string>}
251 * @private
252 */
253 goog.ui.KeyboardShortcutHandler.DEFAULT_TEXT_INPUTS_ = [
254 'color', 'date', 'datetime', 'datetime-local', 'email', 'month', 'number',
255 'password', 'search', 'tel', 'text', 'time', 'url', 'week'
256 ];
257
258
259 /**
260 * Events.
261 * @enum {string}
262 */
263 goog.ui.KeyboardShortcutHandler.EventType = {
264 SHORTCUT_TRIGGERED: 'shortcut',
265 SHORTCUT_PREFIX: 'shortcut_'
266 };
267
268
269 /**
270 * Cache for name to key code lookup.
271 * @type {Object<number>}
272 * @private
273 */
274 goog.ui.KeyboardShortcutHandler.nameToKeyCodeCache_;
275
276
277 /**
278 * Target on which to listen for key events.
279 * @type {goog.events.EventTarget|EventTarget}
280 * @private
281 */
282 goog.ui.KeyboardShortcutHandler.prototype.keyTarget_;
283
284
285 /**
286 * Due to a bug in the way that Gecko on Mac handles cut/copy/paste key events
287 * using the meta key, it is necessary to fake the keyDown for the action key
288 * (C,V,X) by capturing it on keyUp.
289 * Because users will often release the meta key a slight moment before they
290 * release the action key, we need this variable that will store whether the
291 * meta key has been released recently.
292 * It will be cleared after a short delay in the key handling logic.
293 * @type {boolean}
294 * @private
295 */
296 goog.ui.KeyboardShortcutHandler.prototype.metaKeyRecentlyReleased_;
297
298
299 /**
300 * Whether a key event is a printable-key event. Windows uses ctrl+alt
301 * (alt-graph) keys to type characters on European keyboards. For such keys, we
302 * cannot identify whether these keys are used for typing characters when
303 * receiving keydown events. Therefore, we set this flag when we receive their
304 * respective keypress events and fire shortcut events only when we do not
305 * receive them.
306 * @type {boolean}
307 * @private
308 */
309 goog.ui.KeyboardShortcutHandler.prototype.isPrintableKey_;
310
311
312 /**
313 * Static method for getting the key code for a given key.
314 * @param {string} name Name of key.
315 * @return {number} The key code.
316 */
317 goog.ui.KeyboardShortcutHandler.getKeyCode = function(name) {
318 // Build reverse lookup object the first time this method is called.
319 if (!goog.ui.KeyboardShortcutHandler.nameToKeyCodeCache_) {
320 var map = {};
321 for (var key in goog.events.KeyNames) {
322 // Explicitly convert the stringified map keys to numbers and normalize.
323 map[goog.events.KeyNames[key]] =
324 goog.events.KeyCodes.normalizeKeyCode(parseInt(key, 10));
325 }
326 goog.ui.KeyboardShortcutHandler.nameToKeyCodeCache_ = map;
327 }
328
329 // Check if key is in cache.
330 return goog.ui.KeyboardShortcutHandler.nameToKeyCodeCache_[name];
331 };
332
333
334 /**
335 * Sets whether to always prevent the default action when a shortcut event is
336 * fired. If false, the default action is prevented only if preventDefault is
337 * called on either of the corresponding SHORTCUT_TRIGGERED or SHORTCUT_PREFIX
338 * events. If true, the default action is prevented whenever a shortcut event
339 * is fired. The default value is true.
340 * @param {boolean} alwaysPreventDefault Whether to always call preventDefault.
341 */
342 goog.ui.KeyboardShortcutHandler.prototype.setAlwaysPreventDefault = function(
343 alwaysPreventDefault) {
344 this.alwaysPreventDefault_ = alwaysPreventDefault;
345 };
346
347
348 /**
349 * Returns whether the default action will always be prevented when a shortcut
350 * event is fired. The default value is true.
351 * @see #setAlwaysPreventDefault
352 * @return {boolean} Whether preventDefault will always be called.
353 */
354 goog.ui.KeyboardShortcutHandler.prototype.getAlwaysPreventDefault = function() {
355 return this.alwaysPreventDefault_;
356 };
357
358
359 /**
360 * Sets whether to always stop propagation for the event when fired. If false,
361 * the propagation is stopped only if stopPropagation is called on either of the
362 * corresponding SHORT_CUT_TRIGGERED or SHORTCUT_PREFIX events. If true, the
363 * event is prevented from propagating beyond its target whenever it is fired.
364 * The default value is false.
365 * @param {boolean} alwaysStopPropagation Whether to always call
366 * stopPropagation.
367 */
368 goog.ui.KeyboardShortcutHandler.prototype.setAlwaysStopPropagation = function(
369 alwaysStopPropagation) {
370 this.alwaysStopPropagation_ = alwaysStopPropagation;
371 };
372
373
374 /**
375 * Returns whether the event will always be stopped from propagating beyond its
376 * target when a shortcut event is fired. The default value is false.
377 * @see #setAlwaysStopPropagation
378 * @return {boolean} Whether stopPropagation will always be called.
379 */
380 goog.ui.KeyboardShortcutHandler.prototype.getAlwaysStopPropagation =
381 function() {
382 return this.alwaysStopPropagation_;
383 };
384
385
386 /**
387 * Sets whether to treat all shortcuts (including modifier shortcuts) as if the
388 * keys had been passed to the setGlobalKeys function.
389 * @param {boolean} allShortcutsGlobal Whether to treat all shortcuts as global.
390 */
391 goog.ui.KeyboardShortcutHandler.prototype.setAllShortcutsAreGlobal = function(
392 allShortcutsGlobal) {
393 this.allShortcutsAreGlobal_ = allShortcutsGlobal;
394 };
395
396
397 /**
398 * Returns whether all shortcuts (including modifier shortcuts) are treated as
399 * if the keys had been passed to the setGlobalKeys function.
400 * @see #setAllShortcutsAreGlobal
401 * @return {boolean} Whether all shortcuts are treated as globals.
402 */
403 goog.ui.KeyboardShortcutHandler.prototype.getAllShortcutsAreGlobal =
404 function() {
405 return this.allShortcutsAreGlobal_;
406 };
407
408
409 /**
410 * Sets whether to treat shortcuts with modifiers as if the keys had been
411 * passed to the setGlobalKeys function. Ignored if you have called
412 * setAllShortcutsAreGlobal(true). Applies only to form elements (not
413 * content-editable).
414 * @param {boolean} modifierShortcutsGlobal Whether to treat shortcuts with
415 * modifiers as global.
416 */
417 goog.ui.KeyboardShortcutHandler.prototype.setModifierShortcutsAreGlobal =
418 function(modifierShortcutsGlobal) {
419 this.modifierShortcutsAreGlobal_ = modifierShortcutsGlobal;
420 };
421
422
423 /**
424 * Returns whether shortcuts with modifiers are treated as if the keys had been
425 * passed to the setGlobalKeys function. Ignored if you have called
426 * setAllShortcutsAreGlobal(true). Applies only to form elements (not
427 * content-editable).
428 * @see #setModifierShortcutsAreGlobal
429 * @return {boolean} Whether shortcuts with modifiers are treated as globals.
430 */
431 goog.ui.KeyboardShortcutHandler.prototype.getModifierShortcutsAreGlobal =
432 function() {
433 return this.modifierShortcutsAreGlobal_;
434 };
435
436
437 /**
438 * Sets whether to treat space key as a shortcut when the focused element is a
439 * checkbox, radiobutton or button.
440 * @param {boolean} allowSpaceKeyOnButtons Whether to treat space key as a
441 * shortcut when the focused element is a checkbox, radiobutton or button.
442 */
443 goog.ui.KeyboardShortcutHandler.prototype.setAllowSpaceKeyOnButtons = function(
444 allowSpaceKeyOnButtons) {
445 this.allowSpaceKeyOnButtons_ = allowSpaceKeyOnButtons;
446 };
447
448
449 /**
450 * Registers a keyboard shortcut.
451 * @param {string} identifier Identifier for the task performed by the keyboard
452 * combination. Multiple shortcuts can be provided for the same
453 * task by specifying the same identifier.
454 * @param {...(number|string|Array<number>)} var_args See below.
455 *
456 * param {number} keyCode Numeric code for key
457 * param {number=} opt_modifiers Bitmap indicating required modifier keys.
458 * goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT, CTRL, ALT,
459 * or META.
460 *
461 * The last two parameters can be repeated any number of times to create a
462 * shortcut using a sequence of strokes. Instead of varargs the second parameter
463 * could also be an array where each element would be regarded as a parameter.
464 *
465 * A string representation of the shortcut can be supplied instead of the last
466 * two parameters. In that case the method only takes two arguments, the
467 * identifier and the string.
468 *
469 * Examples:
470 * g registerShortcut(str, G_KEYCODE)
471 * Ctrl+g registerShortcut(str, G_KEYCODE, CTRL)
472 * Ctrl+Shift+g registerShortcut(str, G_KEYCODE, CTRL | SHIFT)
473 * Ctrl+g a registerShortcut(str, G_KEYCODE, CTRL, A_KEYCODE)
474 * Ctrl+g Shift+a registerShortcut(str, G_KEYCODE, CTRL, A_KEYCODE, SHIFT)
475 * g a registerShortcut(str, G_KEYCODE, NONE, A_KEYCODE)
476 *
477 * Examples using string representation for shortcuts:
478 * g registerShortcut(str, 'g')
479 * Ctrl+g registerShortcut(str, 'ctrl+g')
480 * Ctrl+Shift+g registerShortcut(str, 'ctrl+shift+g')
481 * Ctrl+g a registerShortcut(str, 'ctrl+g a')
482 * Ctrl+g Shift+a registerShortcut(str, 'ctrl+g shift+a')
483 * g a registerShortcut(str, 'g a').
484 */
485 goog.ui.KeyboardShortcutHandler.prototype.registerShortcut = function(
486 identifier, var_args) {
487
488 // Add shortcut to shortcuts_ tree
489 goog.ui.KeyboardShortcutHandler.setShortcut_(
490 this.shortcuts_, this.interpretStrokes_(1, arguments), identifier);
491 };
492
493
494 /**
495 * Unregisters a keyboard shortcut by keyCode and modifiers or string
496 * representation of sequence.
497 *
498 * param {number} keyCode Numeric code for key
499 * param {number=} opt_modifiers Bitmap indicating required modifier keys.
500 * goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT, CTRL, ALT,
501 * or META.
502 *
503 * The two parameters can be repeated any number of times to create a shortcut
504 * using a sequence of strokes.
505 *
506 * A string representation of the shortcut can be supplied instead see
507 * {@link #registerShortcut} for syntax. In that case the method only takes one
508 * argument.
509 *
510 * @param {...(number|string|Array<number>)} var_args String representation, or
511 * array or list of alternating key codes and modifiers.
512 */
513 goog.ui.KeyboardShortcutHandler.prototype.unregisterShortcut = function(
514 var_args) {
515 // Remove shortcut from tree.
516 goog.ui.KeyboardShortcutHandler.unsetShortcut_(
517 this.shortcuts_, this.interpretStrokes_(0, arguments));
518 };
519
520
521 /**
522 * Verifies if a particular keyboard shortcut is registered already. It has
523 * the same interface as the unregistering of shortcuts.
524 *
525 * param {number} keyCode Numeric code for key
526 * param {number=} opt_modifiers Bitmap indicating required modifier keys.
527 * goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT, CTRL, ALT,
528 * or META.
529 *
530 * The two parameters can be repeated any number of times to create a shortcut
531 * using a sequence of strokes.
532 *
533 * A string representation of the shortcut can be supplied instead see
534 * {@link #registerShortcut} for syntax. In that case the method only takes one
535 * argument.
536 *
537 * @param {...(number|string|Array<number>)} var_args String representation, or
538 * array or list of alternating key codes and modifiers.
539 * @return {boolean} Whether the specified keyboard shortcut is registered.
540 */
541 goog.ui.KeyboardShortcutHandler.prototype.isShortcutRegistered = function(
542 var_args) {
543 return this.checkShortcut_(
544 this.shortcuts_, this.interpretStrokes_(0, arguments));
545 };
546
547
548 /**
549 * Parses the variable arguments for registerShortcut and unregisterShortcut.
550 * @param {number} initialIndex The first index of "args" to treat as
551 * variable arguments.
552 * @param {Object} args The "arguments" array passed
553 * to registerShortcut or unregisterShortcut. Please see the comments in
554 * registerShortcut for list of allowed forms.
555 * @return {!Array<Array<string>>} The sequence of strokes,
556 * represented as arrays of strings.
557 * @private
558 */
559 goog.ui.KeyboardShortcutHandler.prototype.interpretStrokes_ = function(
560 initialIndex, args) {
561 var strokes;
562
563 // Build strokes array from string.
564 if (goog.isString(args[initialIndex])) {
565 strokes = goog.array.map(
566 goog.ui.KeyboardShortcutHandler.parseStringShortcut(args[initialIndex]),
567 function(stroke) {
568 goog.asserts.assertNumber(
569 stroke.keyCode, 'A non-modifier key is needed in each stroke.');
570 return goog.ui.KeyboardShortcutHandler.makeStroke_(
571 stroke.key || '', stroke.keyCode, stroke.modifiers);
572 });
573
574 // Build strokes array from arguments list or from array.
575 } else {
576 var strokesArgs = args, i = initialIndex;
577 if (goog.isArray(args[initialIndex])) {
578 strokesArgs = args[initialIndex];
579 i = 0;
580 }
581
582 strokes = [];
583 for (; i < strokesArgs.length; i += 2) {
584 // keyName == '' because this branch is only run on numbers
585 // (corresponding to keyCodes).
586 strokes.push(goog.ui.KeyboardShortcutHandler.makeStroke_(
587 '', strokesArgs[i], strokesArgs[i + 1]));
588 }
589 }
590
591 return strokes;
592 };
593
594
595 /**
596 * Unregisters all keyboard shortcuts.
597 */
598 goog.ui.KeyboardShortcutHandler.prototype.unregisterAll = function() {
599 this.shortcuts_ = {};
600 };
601
602
603 /**
604 * Sets the global keys; keys that are safe to always regarded as shortcuts,
605 * even if entered in a textarea or input field.
606 * @param {Array<number>} keys List of keys.
607 */
608 goog.ui.KeyboardShortcutHandler.prototype.setGlobalKeys = function(keys) {
609 this.globalKeys_ = goog.object.createSet(keys);
610 };
611
612
613 /**
614 * @return {!Array<string>} The global keys, i.e. keys that are safe to always
615 * regard as shortcuts, even if entered in a textarea or input field.
616 */
617 goog.ui.KeyboardShortcutHandler.prototype.getGlobalKeys = function() {
618 return goog.object.getKeys(this.globalKeys_);
619 };
620
621
622 /** @override */
623 goog.ui.KeyboardShortcutHandler.prototype.disposeInternal = function() {
624 goog.ui.KeyboardShortcutHandler.superClass_.disposeInternal.call(this);
625 this.unregisterAll();
626 this.clearKeyListener();
627 };
628
629
630 /**
631 * Returns event type for a specific shortcut.
632 * @param {string} identifier Identifier for the shortcut task.
633 * @return {string} The event type.
634 */
635 goog.ui.KeyboardShortcutHandler.prototype.getEventType = function(identifier) {
636
637 return goog.ui.KeyboardShortcutHandler.EventType.SHORTCUT_PREFIX + identifier;
638 };
639
640
641 /**
642 * Builds stroke array from string representation of shortcut.
643 * @param {string} s String representation of shortcut.
644 * @return {!Array<!{key: ?string, keyCode: ?number, modifiers: number}>} The
645 * stroke array. A null keyCode means no non-modifier key was part of the
646 * stroke.
647 */
648 goog.ui.KeyboardShortcutHandler.parseStringShortcut = function(s) {
649 // Normalize whitespace and force to lower case.
650 s = s.replace(/[ +]*\+[ +]*/g, '+').replace(/[ ]+/g, ' ').toLowerCase();
651
652 // Build strokes array from string, space separates strokes, plus separates
653 // individual keys.
654 var groups = s.split(' ');
655 var strokes = [];
656 for (var group, i = 0; group = groups[i]; i++) {
657 var keys = group.split('+');
658 // Explicitly re-initialize key data (JS does not have block scoping).
659 var keyName = null;
660 var keyCode = null;
661 var modifiers = goog.ui.KeyboardShortcutHandler.Modifiers.NONE;
662 for (var key, j = 0; key = keys[j]; j++) {
663 switch (key) {
664 case 'shift':
665 modifiers |= goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT;
666 continue;
667 case 'ctrl':
668 modifiers |= goog.ui.KeyboardShortcutHandler.Modifiers.CTRL;
669 continue;
670 case 'alt':
671 modifiers |= goog.ui.KeyboardShortcutHandler.Modifiers.ALT;
672 continue;
673 case 'meta':
674 modifiers |= goog.ui.KeyboardShortcutHandler.Modifiers.META;
675 continue;
676 }
677 if (!goog.isNull(keyCode)) {
678 goog.asserts.fail('At most one non-modifier key can be in a stroke.');
679 }
680 keyCode = goog.ui.KeyboardShortcutHandler.getKeyCode(key);
681 goog.asserts.assertNumber(
682 keyCode, 'Key name not found in goog.events.KeyNames: ' + key);
683 keyName = key;
684 break;
685 }
686 strokes.push({key: keyName, keyCode: keyCode, modifiers: modifiers});
687 }
688
689 return strokes;
690 };
691
692
693 /**
694 * Adds a key event listener that triggers {@link #handleKeyDown_} when keys
695 * are pressed.
696 * @param {goog.events.EventTarget|EventTarget} keyTarget Event target that the
697 * event listener should be attached to.
698 * @protected
699 */
700 goog.ui.KeyboardShortcutHandler.prototype.initializeKeyListener = function(
701 keyTarget) {
702 this.keyTarget_ = keyTarget;
703
704 goog.events.listen(
705 this.keyTarget_, goog.events.EventType.KEYDOWN, this.handleKeyDown_,
706 undefined /* opt_capture */, this);
707
708 // Windows uses ctrl+alt keys (a.k.a. alt-graph keys) for typing characters
709 // on European keyboards (e.g. ctrl+alt+e for an an euro sign.) Unfortunately,
710 // Windows browsers do not have any methods except listening to keypress and
711 // keyup events to identify if ctrl+alt keys are really used for inputting
712 // characters. Therefore, we listen to these events and prevent firing
713 // shortcut-key events if ctrl+alt keys are used for typing characters.
714 if (goog.userAgent.WINDOWS) {
715 goog.events.listen(
716 this.keyTarget_, goog.events.EventType.KEYPRESS,
717 this.handleWindowsKeyPress_, undefined /* opt_capture */, this);
718 }
719
720 goog.events.listen(
721 this.keyTarget_, goog.events.EventType.KEYUP, this.handleKeyUp_,
722 undefined /* opt_capture */, this);
723 };
724
725
726 /**
727 * Handler for when a keyup event is fired. Currently only handled on Windows
728 * (all browsers) or Gecko (all platforms).
729 * @param {!goog.events.BrowserEvent} e The key event.
730 * @private
731 */
732 goog.ui.KeyboardShortcutHandler.prototype.handleKeyUp_ = function(e) {
733 if (goog.userAgent.GECKO) {
734 this.handleGeckoKeyUp_(e);
735 }
736
737 if (goog.userAgent.WINDOWS) {
738 this.handleWindowsKeyUp_(e);
739 }
740 };
741
742
743 /**
744 * Handler for when a keyup event is fired in Firefox (Gecko).
745 * @param {!goog.events.BrowserEvent} e The key event.
746 * @private
747 */
748 goog.ui.KeyboardShortcutHandler.prototype.handleGeckoKeyUp_ = function(e) {
749 // Due to a bug in the way that Gecko on Mac handles cut/copy/paste key events
750 // using the meta key, it is necessary to fake the keyDown for the action keys
751 // (C,V,X) by capturing it on keyUp.
752 // This is because the keyDown events themselves are not fired by the browser
753 // in this case.
754 // Because users will often release the meta key a slight moment before they
755 // release the action key, we need to store whether the meta key has been
756 // released recently to avoid "flaky" cutting/pasting behavior.
757 if (goog.userAgent.MAC) {
758 if (e.keyCode == goog.events.KeyCodes.MAC_FF_META) {
759 this.metaKeyRecentlyReleased_ = true;
760 goog.Timer.callOnce(function() {
761 this.metaKeyRecentlyReleased_ = false;
762 }, 400, this);
763 return;
764 }
765
766 var metaKey = e.metaKey || this.metaKeyRecentlyReleased_;
767 if ((e.keyCode == goog.events.KeyCodes.C ||
768 e.keyCode == goog.events.KeyCodes.X ||
769 e.keyCode == goog.events.KeyCodes.V) &&
770 metaKey) {
771 e.metaKey = metaKey;
772 this.handleKeyDown_(e);
773 }
774 }
775
776 // Firefox triggers buttons on space keyUp instead of keyDown. So if space
777 // keyDown activated a shortcut, do NOT also trigger the focused button.
778 if (goog.events.KeyCodes.SPACE == this.activeShortcutKeyForGecko_ &&
779 goog.events.KeyCodes.SPACE == e.keyCode) {
780 e.preventDefault();
781 }
782 this.activeShortcutKeyForGecko_ = null;
783 };
784
785
786 /**
787 * Returns whether this event is possibly used for typing a printable character.
788 * Windows uses ctrl+alt (a.k.a. alt-graph) keys for typing characters on
789 * European keyboards. Since only Firefox provides a method that can identify
790 * whether ctrl+alt keys are used for typing characters, we need to check
791 * whether Windows sends a keypress event to prevent firing shortcut event if
792 * this event is used for typing characters.
793 * @param {!goog.events.BrowserEvent} e The key event.
794 * @return {boolean} Whether this event is a possible printable-key event.
795 * @private
796 */
797 goog.ui.KeyboardShortcutHandler.prototype.isPossiblePrintableKey_ = function(
798 e) {
799 return goog.userAgent.WINDOWS && e.ctrlKey && e.altKey;
800 };
801
802
803 /**
804 * Handler for when a keypress event is fired on Windows.
805 * @param {!goog.events.BrowserEvent} e The key event.
806 * @private
807 */
808 goog.ui.KeyboardShortcutHandler.prototype.handleWindowsKeyPress_ = function(e) {
809 // When this keypress event consists of a printable character, set the flag to
810 // prevent firing shortcut key events when we receive the succeeding keyup
811 // event. We accept all Unicode characters except control ones since this
812 // keyCode may be a non-ASCII character.
813 if (e.keyCode > 0x20 && this.isPossiblePrintableKey_(e)) {
814 this.isPrintableKey_ = true;
815 }
816 };
817
818
819 /**
820 * Handler for when a keyup event is fired on Windows.
821 * @param {!goog.events.BrowserEvent} e The key event.
822 * @private
823 */
824 goog.ui.KeyboardShortcutHandler.prototype.handleWindowsKeyUp_ = function(e) {
825 // For possible printable-key events, try firing a shortcut-key event only
826 // when this event is not used for typing a character.
827 if (!this.isPrintableKey_ && this.isPossiblePrintableKey_(e)) {
828 this.handleKeyDown_(e);
829 }
830 };
831
832
833 /**
834 * Removes the listener that was added by link {@link #initializeKeyListener}.
835 * @protected
836 */
837 goog.ui.KeyboardShortcutHandler.prototype.clearKeyListener = function() {
838 goog.events.unlisten(
839 this.keyTarget_, goog.events.EventType.KEYDOWN, this.handleKeyDown_,
840 false, this);
841 if (goog.userAgent.WINDOWS) {
842 goog.events.unlisten(
843 this.keyTarget_, goog.events.EventType.KEYPRESS,
844 this.handleWindowsKeyPress_, false, this);
845 }
846 goog.events.unlisten(
847 this.keyTarget_, goog.events.EventType.KEYUP, this.handleKeyUp_, false,
848 this);
849 this.keyTarget_ = null;
850 };
851
852
853 /**
854 * Adds a shortcut stroke sequence to the given sequence tree. Recursive.
855 * @param {!goog.ui.KeyboardShortcutHandler.SequenceTree_} tree The stroke
856 * sequence tree to add to.
857 * @param {Array<Array<string>>} strokes Array of strokes for shortcut.
858 * @param {string} identifier Identifier for the task performed by shortcut.
859 * @private
860 */
861 goog.ui.KeyboardShortcutHandler.setShortcut_ = function(
862 tree, strokes, identifier) {
863 var stroke = strokes.shift();
864 goog.array.forEach(stroke, function(s) {
865 var node = tree[s];
866 if (node && (strokes.length == 0 || node.shortcut)) {
867 // This new shortcut would override an existing shortcut or shortcut
868 // prefix (since the new strokes end at an existing node), or an existing
869 // shortcut would be triggered by the prefix to this new shortcut (since
870 // there is already a terminal node on the path we are trying to create).
871 throw new Error('Keyboard shortcut conflicts with existing shortcut');
872 }
873 });
874
875 if (strokes.length) {
876 goog.array.forEach(stroke, function(s) {
877 var node = goog.object.setIfUndefined(
878 tree, s.toString(),
879 goog.ui.KeyboardShortcutHandler.createInternalNode_());
880 // setShortcut_ modifies strokes
881 var strokesCopy = strokes.slice(0);
882 goog.ui.KeyboardShortcutHandler.setShortcut_(
883 goog.asserts.assert(
884 node.next, 'An internal node must have a next map'),
885 strokesCopy, identifier);
886 });
887 } else {
888 goog.array.forEach(stroke, function(s) {
889 // Add a terminal node.
890 tree[s] = goog.ui.KeyboardShortcutHandler.createTerminalNode_(identifier);
891 });
892 }
893 };
894
895
896 /**
897 * Removes a shortcut stroke sequence from the given sequence tree, pruning any
898 * dead branches of the tree. Recursive.
899 * @param {!goog.ui.KeyboardShortcutHandler.SequenceTree_} tree The stroke
900 * sequence tree to remove from.
901 * @param {Array<Array<string>>} strokes Array of strokes for shortcut to
902 * remove.
903 * @private
904 */
905 goog.ui.KeyboardShortcutHandler.unsetShortcut_ = function(tree, strokes) {
906 var stroke = strokes.shift();
907 goog.array.forEach(stroke, function(s) {
908 var node = tree[s];
909
910 if (!node) {
911 // The given stroke sequence is not in the tree.
912 return;
913 }
914 if (strokes.length == 0) {
915 // Base case - the end of the stroke sequence.
916 if (!node.shortcut) {
917 // The given stroke sequence does not end at a terminal node.
918 return;
919 }
920 delete tree[s];
921 } else {
922 if (!node.next) {
923 // The given stroke sequence is not in the tree.
924 return;
925 }
926 // Recursively remove the rest of the shortcut sequence from the node.next
927 // subtree.
928 // unsetShortcut_ modifies strokes
929 var strokesCopy = strokes.slice(0);
930 goog.ui.KeyboardShortcutHandler.unsetShortcut_(node.next, strokesCopy);
931 if (goog.object.isEmpty(node.next)) {
932 // The node.next subtree is now empty (the last stroke in it was just
933 // removed), so prune this dead branch of the tree.
934 delete tree[s];
935 }
936 }
937 });
938 };
939
940
941 /**
942 * Checks tree for a node matching one of stroke.
943 * @param {!goog.ui.KeyboardShortcutHandler.SequenceTree_} tree The
944 * stroke sequence tree to find the node in.
945 * @param {Array<string>} stroke Stroke to find.
946 * @return {goog.ui.KeyboardShortcutHandler.SequenceNode_|undefined} Node matching stroke.
947 * @private
948 */
949 goog.ui.KeyboardShortcutHandler.prototype.getNode_ = function(tree, stroke) {
950 for (var i = 0; i < stroke.length; i++) {
951 var node = tree[stroke[i]];
952 if (!node) {
953 continue;
954 }
955 return node;
956 }
957 return undefined;
958 };
959
960 /**
961 * Checks if a particular keyboard shortcut is registered.
962 * @param {goog.ui.KeyboardShortcutHandler.SequenceTree_|null} tree The
963 * stroke sequence tree to find the keyboard shortcut in.
964 * @param {Array<Array<string>>} strokes Strokes array.
965 * @return {boolean} True iff the keyboard shortcut is registred.
966 * @private
967 */
968 goog.ui.KeyboardShortcutHandler.prototype.checkShortcut_ = function(
969 tree, strokes) {
970 while (strokes.length > 0 && tree) {
971 var stroke = strokes.shift();
972 var node = this.getNode_(tree, stroke);
973 if (!node) {
974 continue;
975 }
976 if (strokes.length == 0 && node.shortcut) {
977 return true;
978 }
979 // checkShortcut_ modifies strokes
980 var strokesCopy = strokes.slice(0);
981 if (this.checkShortcut_(node.next, strokesCopy)) {
982 return true;
983 }
984 }
985 return false;
986 };
987
988
989 /**
990 * Constructs key identification string from key name, key code and modifiers.
991 *
992 * @param {string} keyName Key name.
993 * @param {number} keyCode Numeric key code.
994 * @param {number} modifiers Required modifiers.
995 * @return {Array<string>} An array of strings identifying the key/modifier
996 * combinations.
997 * @private
998 */
999 goog.ui.KeyboardShortcutHandler.makeStroke_ = function(
1000 keyName, keyCode, modifiers) {
1001 var mods = modifiers || 0;
1002 // entries must be usable as key in a map
1003 var strokes = ['c_' + keyCode + '_' + mods];
1004
1005 if (keyName != '') {
1006 strokes.push('n_' + keyName + '_' + mods);
1007 }
1008
1009 return strokes;
1010 };
1011
1012
1013 /**
1014 * Keypress handler.
1015 * @param {!goog.events.BrowserEvent} event Keypress event.
1016 * @private
1017 */
1018 goog.ui.KeyboardShortcutHandler.prototype.handleKeyDown_ = function(event) {
1019 if (!this.isValidShortcut_(event)) {
1020 return;
1021 }
1022 // For possible printable-key events, we cannot identify whether the events
1023 // are used for typing characters until we receive respective keyup events.
1024 // Therefore, we handle this event when we receive a succeeding keyup event
1025 // to verify this event is not used for typing characters. preventDefault is
1026 // not called on the event to avoid disrupting a character input.
1027 if (event.type == 'keydown' && this.isPossiblePrintableKey_(event)) {
1028 this.isPrintableKey_ = false;
1029 return;
1030 }
1031
1032 var keyCode = goog.events.KeyCodes.normalizeKeyCode(event.keyCode);
1033 var keyName = event.key;
1034
1035 var modifiers =
1036 (event.shiftKey ? goog.ui.KeyboardShortcutHandler.Modifiers.SHIFT : 0) |
1037 (event.ctrlKey ? goog.ui.KeyboardShortcutHandler.Modifiers.CTRL : 0) |
1038 (event.altKey ? goog.ui.KeyboardShortcutHandler.Modifiers.ALT : 0) |
1039 (event.metaKey ? goog.ui.KeyboardShortcutHandler.Modifiers.META : 0);
1040 var stroke =
1041 goog.ui.KeyboardShortcutHandler.makeStroke_(keyName, keyCode, modifiers);
1042 var node = this.getNode_(this.currentTree_, stroke);
1043
1044 if (!node || this.hasSequenceTimedOut_()) {
1045 // Either this stroke does not continue any active sequence, or the
1046 // currently active sequence has timed out. Reset shortcut tree progress.
1047 this.setCurrentTree_(this.shortcuts_);
1048 }
1049
1050 node = this.getNode_(this.currentTree_, stroke);
1051
1052 if (node && node.next) {
1053 // This stroke does not trigger a shortcut, but entered stroke(s) are a part
1054 // of a sequence. Progress in the sequence tree and record time to allow the
1055 // following stroke(s) to trigger the shortcut.
1056 this.setCurrentTree_(node.next);
1057 }
1058
1059 if (!node) {
1060 // This stroke does not correspond to a shortcut or continued sequence.
1061 return;
1062 } else if (node.next) {
1063 // Prevent default action so that the rest of the stroke sequence can be
1064 // completed.
1065 event.preventDefault();
1066 return;
1067 }
1068
1069 // This stroke triggers a shortcut. Any active sequence has been completed, so
1070 // reset the sequence tree.
1071 this.setCurrentTree_(this.shortcuts_);
1072
1073 // Dispatch the triggered keyboard shortcut event. In addition to the generic
1074 // keyboard shortcut event a more specific fine grained one, specific for the
1075 // shortcut identifier, is fired.
1076 if (this.alwaysPreventDefault_) {
1077 event.preventDefault();
1078 }
1079
1080 if (this.alwaysStopPropagation_) {
1081 event.stopPropagation();
1082 }
1083
1084 var shortcut = goog.asserts.assertString(
1085 node.shortcut, 'A terminal node must have a string shortcut identifier.');
1086 // Dispatch SHORTCUT_TRIGGERED event
1087 var target = /** @type {Node} */ (event.target);
1088 var triggerEvent = new goog.ui.KeyboardShortcutEvent(
1089 goog.ui.KeyboardShortcutHandler.EventType.SHORTCUT_TRIGGERED, shortcut,
1090 target);
1091 var retVal = this.dispatchEvent(triggerEvent);
1092
1093 // Dispatch SHORTCUT_PREFIX_<identifier> event
1094 var prefixEvent = new goog.ui.KeyboardShortcutEvent(
1095 goog.ui.KeyboardShortcutHandler.EventType.SHORTCUT_PREFIX + shortcut,
1096 shortcut, target);
1097 retVal &= this.dispatchEvent(prefixEvent);
1098
1099 // The default action is prevented if 'preventDefault' was
1100 // called on either event, or if a listener returned false.
1101 if (!retVal) {
1102 event.preventDefault();
1103 }
1104
1105 // For Firefox, track which shortcut key was pushed.
1106 if (goog.userAgent.GECKO) {
1107 this.activeShortcutKeyForGecko_ = keyCode;
1108 }
1109 };
1110
1111
1112 /**
1113 * Checks if a given keypress event may be treated as a shortcut.
1114 * @param {!goog.events.BrowserEvent} event Keypress event.
1115 * @return {boolean} Whether to attempt to process the event as a shortcut.
1116 * @private
1117 */
1118 goog.ui.KeyboardShortcutHandler.prototype.isValidShortcut_ = function(event) {
1119 // Ignore Ctrl, Shift and ALT
1120 var keyCode = event.keyCode;
1121 if (event.key != '') {
1122 var keyName = event.key;
1123 if (keyName == goog.events.Keys.CTRL || keyName == goog.events.Keys.SHIFT ||
1124 keyName == goog.events.Keys.ALT ||
1125 keyName == goog.events.Keys.ALTGRAPH) {
1126 return false;
1127 }
1128 } else {
1129 if (keyCode == goog.events.KeyCodes.SHIFT ||
1130 keyCode == goog.events.KeyCodes.CTRL ||
1131 keyCode == goog.events.KeyCodes.ALT) {
1132 return false;
1133 }
1134 }
1135 var el = /** @type {Element} */ (event.target);
1136 var isFormElement = el.tagName == goog.dom.TagName.TEXTAREA ||
1137 el.tagName == goog.dom.TagName.INPUT ||
1138 el.tagName == goog.dom.TagName.BUTTON ||
1139 el.tagName == goog.dom.TagName.SELECT;
1140
1141 var isContentEditable = !isFormElement &&
1142 (el.isContentEditable ||
1143 (el.ownerDocument && el.ownerDocument.designMode == 'on'));
1144
1145 if (!isFormElement && !isContentEditable) {
1146 return true;
1147 }
1148 // Always allow keys registered as global to be used (typically Esc, the
1149 // F-keys and other keys that are not typically used to manipulate text).
1150 if (this.globalKeys_[keyCode] || this.allShortcutsAreGlobal_) {
1151 return true;
1152 }
1153 if (isContentEditable) {
1154 // For events originating from an element in editing mode we only let
1155 // global key codes through.
1156 return false;
1157 }
1158 // Event target is one of (TEXTAREA, INPUT, BUTTON, SELECT).
1159 // Allow modifier shortcuts, unless we shouldn't.
1160 if (this.modifierShortcutsAreGlobal_ &&
1161 (event.altKey || event.ctrlKey || event.metaKey)) {
1162 return true;
1163 }
1164 // Allow ENTER to be used as shortcut for text inputs.
1165 if (el.tagName == goog.dom.TagName.INPUT && this.textInputs_[el.type]) {
1166 return keyCode == goog.events.KeyCodes.ENTER;
1167 }
1168 // Checkboxes, radiobuttons and buttons. Allow all but SPACE as shortcut.
1169 if (el.tagName == goog.dom.TagName.INPUT ||
1170 el.tagName == goog.dom.TagName.BUTTON) {
1171 // TODO(gboyer): If more flexibility is needed, create protected helper
1172 // methods for each case (e.g. button, input, etc).
1173 if (this.allowSpaceKeyOnButtons_) {
1174 return true;
1175 } else {
1176 return keyCode != goog.events.KeyCodes.SPACE;
1177 }
1178 }
1179 // Don't allow any additional shortcut keys for textareas or selects.
1180 return false;
1181 };
1182
1183
1184 /**
1185 * @return {boolean} True iff the current stroke sequence has timed out.
1186 * @private
1187 */
1188 goog.ui.KeyboardShortcutHandler.prototype.hasSequenceTimedOut_ = function() {
1189 return goog.now() - this.lastStrokeTime_ >=
1190 goog.ui.KeyboardShortcutHandler.MAX_KEY_SEQUENCE_DELAY;
1191 };
1192
1193
1194 /**
1195 * Sets the current keyboard shortcut sequence tree and updates the last stroke
1196 * time.
1197 * @param {!goog.ui.KeyboardShortcutHandler.SequenceTree_} tree
1198 * @private
1199 */
1200 goog.ui.KeyboardShortcutHandler.prototype.setCurrentTree_ = function(tree) {
1201 this.currentTree_ = tree;
1202 this.lastStrokeTime_ = goog.now();
1203 };
1204
1205
1206
1207 /**
1208 * Object representing a keyboard shortcut event.
1209 * @param {string} type Event type.
1210 * @param {string} identifier Task identifier for the triggered shortcut.
1211 * @param {Node|goog.events.EventTarget} target Target the original key press
1212 * event originated from.
1213 * @extends {goog.events.Event}
1214 * @constructor
1215 * @final
1216 */
1217 goog.ui.KeyboardShortcutEvent = function(type, identifier, target) {
1218 goog.events.Event.call(this, type, target);
1219
1220 /**
1221 * Task identifier for the triggered shortcut
1222 * @type {string}
1223 */
1224 this.identifier = identifier;
1225 };
1226 goog.inherits(goog.ui.KeyboardShortcutEvent, goog.events.Event);