Blame view

bower_components/iron-a11y-keys-behavior/iron-a11y-keys-behavior.html 13.7 KB
73bcce88   luigser   COMPONENTS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
  <!--
  @license
  Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
  This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
  The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
  The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
  Code distributed by Google as part of the polymer project is also
  subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
  -->
  
  <link rel="import" href="../polymer/polymer.html">
  
  <script>
    (function() {
      'use strict';
  
      /**
       * Chrome uses an older version of DOM Level 3 Keyboard Events
       *
       * Most keys are labeled as text, but some are Unicode codepoints.
       * Values taken from: http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/keyset.html#KeySet-Set
       */
      var KEY_IDENTIFIER = {
a1a3bc73   Luigi Serra   graphs updates
24
        'U+0008': 'backspace',
73bcce88   luigser   COMPONENTS
25
26
27
        'U+0009': 'tab',
        'U+001B': 'esc',
        'U+0020': 'space',
73bcce88   luigser   COMPONENTS
28
29
30
31
32
33
34
35
36
37
38
        'U+007F': 'del'
      };
  
      /**
       * Special table for KeyboardEvent.keyCode.
       * KeyboardEvent.keyIdentifier is better, and KeyBoardEvent.key is even better
       * than that.
       *
       * Values from: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent.keyCode#Value_of_keyCode
       */
      var KEY_CODE = {
a1a3bc73   Luigi Serra   graphs updates
39
        8: 'backspace',
73bcce88   luigser   COMPONENTS
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
        9: 'tab',
        13: 'enter',
        27: 'esc',
        33: 'pageup',
        34: 'pagedown',
        35: 'end',
        36: 'home',
        32: 'space',
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down',
        46: 'del',
        106: '*'
      };
  
      /**
       * MODIFIER_KEYS maps the short name for modifier keys used in a key
       * combo string to the property name that references those same keys
       * in a KeyboardEvent instance.
       */
      var MODIFIER_KEYS = {
        'shift': 'shiftKey',
        'ctrl': 'ctrlKey',
        'alt': 'altKey',
        'meta': 'metaKey'
      };
  
      /**
       * KeyboardEvent.key is mostly represented by printable character made by
       * the keyboard, with unprintable keys labeled nicely.
       *
       * However, on OS X, Alt+char can make a Unicode character that follows an
a1a3bc73   Luigi Serra   graphs updates
73
       * Apple-specific mapping. In this case, we fall back to .keyCode.
73bcce88   luigser   COMPONENTS
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
       */
      var KEY_CHAR = /[a-z0-9*]/;
  
      /**
       * Matches a keyIdentifier string.
       */
      var IDENT_CHAR = /U\+/;
  
      /**
       * Matches arrow keys in Gecko 27.0+
       */
      var ARROW_KEY = /^arrow/;
  
      /**
       * Matches space keys everywhere (notably including IE10's exceptional name
       * `spacebar`).
       */
      var SPACE_KEY = /^space(bar)?/;
  
a1a3bc73   Luigi Serra   graphs updates
93
94
95
96
97
98
99
      /**
       * Transforms the key.
       * @param {string} key The KeyBoardEvent.key
       * @param {Boolean} [noSpecialChars] Limits the transformation to
       * alpha-numeric characters.
       */
      function transformKey(key, noSpecialChars) {
73bcce88   luigser   COMPONENTS
100
101
102
        var validKey = '';
        if (key) {
          var lKey = key.toLowerCase();
a1a3bc73   Luigi Serra   graphs updates
103
104
105
106
          if (lKey === ' ' || SPACE_KEY.test(lKey)) {
            validKey = 'space';
          } else if (lKey.length == 1) {
            if (!noSpecialChars || KEY_CHAR.test(lKey)) {
73bcce88   luigser   COMPONENTS
107
108
109
110
              validKey = lKey;
            }
          } else if (ARROW_KEY.test(lKey)) {
            validKey = lKey.replace('arrow', '');
73bcce88   luigser   COMPONENTS
111
112
113
114
115
116
117
118
119
120
121
122
123
          } else if (lKey == 'multiply') {
            // numpad '*' can map to Multiply on IE/Windows
            validKey = '*';
          } else {
            validKey = lKey;
          }
        }
        return validKey;
      }
  
      function transformKeyIdentifier(keyIdent) {
        var validKey = '';
        if (keyIdent) {
a1a3bc73   Luigi Serra   graphs updates
124
          if (keyIdent in KEY_IDENTIFIER) {
73bcce88   luigser   COMPONENTS
125
            validKey = KEY_IDENTIFIER[keyIdent];
a1a3bc73   Luigi Serra   graphs updates
126
127
128
          } else if (IDENT_CHAR.test(keyIdent)) {
            keyIdent = parseInt(keyIdent.replace('U+', '0x'), 16);
            validKey = String.fromCharCode(keyIdent).toLowerCase();
73bcce88   luigser   COMPONENTS
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
          } else {
            validKey = keyIdent.toLowerCase();
          }
        }
        return validKey;
      }
  
      function transformKeyCode(keyCode) {
        var validKey = '';
        if (Number(keyCode)) {
          if (keyCode >= 65 && keyCode <= 90) {
            // ascii a-z
            // lowercase is 32 offset from uppercase
            validKey = String.fromCharCode(32 + keyCode);
          } else if (keyCode >= 112 && keyCode <= 123) {
            // function keys f1-f12
            validKey = 'f' + (keyCode - 112);
          } else if (keyCode >= 48 && keyCode <= 57) {
            // top 0-9 keys
            validKey = String(48 - keyCode);
          } else if (keyCode >= 96 && keyCode <= 105) {
            // num pad 0-9
            validKey = String(96 - keyCode);
          } else {
            validKey = KEY_CODE[keyCode];
          }
        }
        return validKey;
      }
  
a1a3bc73   Luigi Serra   graphs updates
159
160
161
162
163
164
165
166
167
168
169
170
171
172
      /**
        * Calculates the normalized key for a KeyboardEvent.
        * @param {KeyboardEvent} keyEvent
        * @param {Boolean} [noSpecialChars] Set to true to limit keyEvent.key
        * transformation to alpha-numeric chars. This is useful with key
        * combinations like shift + 2, which on FF for MacOS produces
        * keyEvent.key = @
        * To get 2 returned, set noSpecialChars = true
        * To get @ returned, set noSpecialChars = false
       */
      function normalizedKeyForEvent(keyEvent, noSpecialChars) {
        // Fall back from .key, to .keyIdentifier, to .keyCode, and then to
        // .detail.key to support artificial keyboard events.
        return transformKey(keyEvent.key, noSpecialChars) ||
73bcce88   luigser   COMPONENTS
173
174
          transformKeyIdentifier(keyEvent.keyIdentifier) ||
          transformKeyCode(keyEvent.keyCode) ||
a1a3bc73   Luigi Serra   graphs updates
175
          transformKey(keyEvent.detail.key, noSpecialChars) || '';
73bcce88   luigser   COMPONENTS
176
177
      }
  
a1a3bc73   Luigi Serra   graphs updates
178
179
180
181
182
183
184
185
186
187
      function keyComboMatchesEvent(keyCombo, event) {
        // For combos with modifiers we support only alpha-numeric keys
        var keyEvent = normalizedKeyForEvent(event, keyCombo.hasModifiers);
        return keyEvent === keyCombo.key &&
          (!keyCombo.hasModifiers || (
            !!event.shiftKey === !!keyCombo.shiftKey &&
            !!event.ctrlKey === !!keyCombo.ctrlKey &&
            !!event.altKey === !!keyCombo.altKey &&
            !!event.metaKey === !!keyCombo.metaKey)
          );
73bcce88   luigser   COMPONENTS
188
189
190
      }
  
      function parseKeyComboString(keyComboString) {
a1a3bc73   Luigi Serra   graphs updates
191
192
193
194
195
196
197
        if (keyComboString.length === 1) {
          return {
            combo: keyComboString,
            key: keyComboString,
            event: 'keydown'
          };
        }
73bcce88   luigser   COMPONENTS
198
199
200
201
202
203
204
        return keyComboString.split('+').reduce(function(parsedKeyCombo, keyComboPart) {
          var eventParts = keyComboPart.split(':');
          var keyName = eventParts[0];
          var event = eventParts[1];
  
          if (keyName in MODIFIER_KEYS) {
            parsedKeyCombo[MODIFIER_KEYS[keyName]] = true;
a1a3bc73   Luigi Serra   graphs updates
205
            parsedKeyCombo.hasModifiers = true;
73bcce88   luigser   COMPONENTS
206
207
208
209
210
211
212
213
214
215
216
217
          } else {
            parsedKeyCombo.key = keyName;
            parsedKeyCombo.event = event || 'keydown';
          }
  
          return parsedKeyCombo;
        }, {
          combo: keyComboString.split(':').shift()
        });
      }
  
      function parseEventString(eventString) {
a1a3bc73   Luigi Serra   graphs updates
218
        return eventString.trim().split(' ').map(function(keyComboString) {
73bcce88   luigser   COMPONENTS
219
220
221
222
          return parseKeyComboString(keyComboString);
        });
      }
  
73bcce88   luigser   COMPONENTS
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
      /**
       * `Polymer.IronA11yKeysBehavior` provides a normalized interface for processing
       * keyboard commands that pertain to [WAI-ARIA best practices](http://www.w3.org/TR/wai-aria-practices/#kbd_general_binding).
       * The element takes care of browser differences with respect to Keyboard events
       * and uses an expressive syntax to filter key presses.
       *
       * Use the `keyBindings` prototype property to express what combination of keys
       * will trigger the event to fire.
       *
       * Use the `key-event-target` attribute to set up event handlers on a specific
       * node.
       * The `keys-pressed` event will fire when one of the key combinations set with the
       * `keys` property is pressed.
       *
       * @demo demo/index.html
e619a3b0   Luigi Serra   Controllet cross ...
238
       * @polymerBehavior
73bcce88   luigser   COMPONENTS
239
240
241
242
243
244
245
246
247
248
249
250
251
       */
      Polymer.IronA11yKeysBehavior = {
        properties: {
          /**
           * The HTMLElement that will be firing relevant KeyboardEvents.
           */
          keyEventTarget: {
            type: Object,
            value: function() {
              return this;
            }
          },
  
eb240478   Luigi Serra   public room cards...
252
253
254
255
256
257
258
259
260
          /**
           * If true, this property will cause the implementing element to
           * automatically stop propagation on any handled KeyboardEvents.
           */
          stopKeyboardEventPropagation: {
            type: Boolean,
            value: false
          },
  
73bcce88   luigser   COMPONENTS
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
          _boundKeyHandlers: {
            type: Array,
            value: function() {
              return [];
            }
          },
  
          // We use this due to a limitation in IE10 where instances will have
          // own properties of everything on the "prototype".
          _imperativeKeyBindings: {
            type: Object,
            value: function() {
              return {};
            }
          }
        },
  
        observers: [
          '_resetKeyEventListeners(keyEventTarget, _boundKeyHandlers)'
        ],
  
        keyBindings: {},
  
        registered: function() {
          this._prepKeyBindings();
        },
  
        attached: function() {
          this._listenKeyEventListeners();
        },
  
        detached: function() {
          this._unlistenKeyEventListeners();
        },
  
        /**
         * Can be used to imperatively add a key binding to the implementing
         * element. This is the imperative equivalent of declaring a keybinding
         * in the `keyBindings` prototype property.
         */
        addOwnKeyBinding: function(eventString, handlerName) {
          this._imperativeKeyBindings[eventString] = handlerName;
          this._prepKeyBindings();
          this._resetKeyEventListeners();
        },
  
        /**
         * When called, will remove all imperatively-added key bindings.
         */
        removeOwnKeyBindings: function() {
          this._imperativeKeyBindings = {};
          this._prepKeyBindings();
          this._resetKeyEventListeners();
        },
  
        keyboardEventMatchesKeys: function(event, eventString) {
          var keyCombos = parseEventString(eventString);
a1a3bc73   Luigi Serra   graphs updates
318
319
          for (var i = 0; i < keyCombos.length; ++i) {
            if (keyComboMatchesEvent(keyCombos[i], event)) {
73bcce88   luigser   COMPONENTS
320
321
322
              return true;
            }
          }
73bcce88   luigser   COMPONENTS
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
          return false;
        },
  
        _collectKeyBindings: function() {
          var keyBindings = this.behaviors.map(function(behavior) {
            return behavior.keyBindings;
          });
  
          if (keyBindings.indexOf(this.keyBindings) === -1) {
            keyBindings.push(this.keyBindings);
          }
  
          return keyBindings;
        },
  
        _prepKeyBindings: function() {
          this._keyBindings = {};
  
          this._collectKeyBindings().forEach(function(keyBindings) {
            for (var eventString in keyBindings) {
              this._addKeyBinding(eventString, keyBindings[eventString]);
            }
          }, this);
  
          for (var eventString in this._imperativeKeyBindings) {
            this._addKeyBinding(eventString, this._imperativeKeyBindings[eventString]);
          }
a1a3bc73   Luigi Serra   graphs updates
350
351
352
353
354
355
356
357
358
  
          // Give precedence to combos with modifiers to be checked first.
          for (var eventName in this._keyBindings) {
            this._keyBindings[eventName].sort(function (kb1, kb2) {
              var b1 = kb1[0].hasModifiers;
              var b2 = kb2[0].hasModifiers;
              return (b1 === b2) ? 0 : b1 ? -1 : 1;
            })
          }
73bcce88   luigser   COMPONENTS
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
        },
  
        _addKeyBinding: function(eventString, handlerName) {
          parseEventString(eventString).forEach(function(keyCombo) {
            this._keyBindings[keyCombo.event] =
              this._keyBindings[keyCombo.event] || [];
  
            this._keyBindings[keyCombo.event].push([
              keyCombo,
              handlerName
            ]);
          }, this);
        },
  
        _resetKeyEventListeners: function() {
          this._unlistenKeyEventListeners();
  
          if (this.isAttached) {
            this._listenKeyEventListeners();
          }
        },
  
        _listenKeyEventListeners: function() {
          Object.keys(this._keyBindings).forEach(function(eventName) {
            var keyBindings = this._keyBindings[eventName];
            var boundKeyHandler = this._onKeyBindingEvent.bind(this, keyBindings);
  
            this._boundKeyHandlers.push([this.keyEventTarget, eventName, boundKeyHandler]);
  
            this.keyEventTarget.addEventListener(eventName, boundKeyHandler);
          }, this);
        },
  
        _unlistenKeyEventListeners: function() {
          var keyHandlerTuple;
          var keyEventTarget;
          var eventName;
          var boundKeyHandler;
  
          while (this._boundKeyHandlers.length) {
            // My kingdom for block-scope binding and destructuring assignment..
            keyHandlerTuple = this._boundKeyHandlers.pop();
            keyEventTarget = keyHandlerTuple[0];
            eventName = keyHandlerTuple[1];
            boundKeyHandler = keyHandlerTuple[2];
  
            keyEventTarget.removeEventListener(eventName, boundKeyHandler);
          }
        },
  
        _onKeyBindingEvent: function(keyBindings, event) {
eb240478   Luigi Serra   public room cards...
410
411
412
413
          if (this.stopKeyboardEventPropagation) {
            event.stopPropagation();
          }
  
a1a3bc73   Luigi Serra   graphs updates
414
415
416
417
          // if event has been already prevented, don't do anything
          if (event.defaultPrevented) {
            return;
          }
73bcce88   luigser   COMPONENTS
418
  
a1a3bc73   Luigi Serra   graphs updates
419
420
421
422
          for (var i = 0; i < keyBindings.length; i++) {
            var keyCombo = keyBindings[i][0];
            var handlerName = keyBindings[i][1];
            if (keyComboMatchesEvent(keyCombo, event)) {
73bcce88   luigser   COMPONENTS
423
              this._triggerKeyHandler(keyCombo, handlerName, event);
a1a3bc73   Luigi Serra   graphs updates
424
425
426
427
              // exit the loop if eventDefault was prevented
              if (event.defaultPrevented) {
                return;
              }
73bcce88   luigser   COMPONENTS
428
            }
a1a3bc73   Luigi Serra   graphs updates
429
          }
73bcce88   luigser   COMPONENTS
430
431
432
433
434
        },
  
        _triggerKeyHandler: function(keyCombo, handlerName, keyboardEvent) {
          var detail = Object.create(keyCombo);
          detail.keyboardEvent = keyboardEvent;
f748e9cf   Luigi Serra   new controllet an...
435
436
437
438
439
440
441
442
          var event = new CustomEvent(keyCombo.event, {
            detail: detail,
            cancelable: true
          });
          this[handlerName].call(this, event);
          if (event.defaultPrevented) {
            keyboardEvent.preventDefault();
          }
73bcce88   luigser   COMPONENTS
443
444
445
446
        }
      };
    })();
  </script>