-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathhumaninput-1.1.15-full.js
3979 lines (3558 loc) · 175 KB
/
humaninput-1.1.15-full.js
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["humaninput-full"] = factory();
else
root["HumanInput"] = root["HumanInput"] || {}, root["HumanInput"]["humaninput-full"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 28);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {module.exports = global["HumanInput"] = __webpack_require__(10);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {module.exports = global["HumanInput"] = __webpack_require__(4);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {module.exports = global["HumanInput"] = __webpack_require__(5);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(0)))
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.__esModule = true;
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _polyfills = __webpack_require__(14);
var _constants = __webpack_require__(3);
var _utils = __webpack_require__(1);
var _logger = __webpack_require__(13);
var _events = __webpack_require__(11);
var _keymaps = __webpack_require__(12);
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } /**
* humaninput.js - HumanInput is a Human-generated event library for humans (keyboard, mouse, gesture, touch, gamepad, speech recognition and more)
* Copyright (c) 2016, Dan McDougall
* @link https://github.com/liftoff/HumanInput
* @license Apache-2.0
*/
(0, _polyfills.polyfill)(); // Won't do anything unless we execute it
// Remove this line if you don't care about Safari keyboard support:
// Removing this saves ~1.3k in minified output!
// Sandbox-side variables and shortcuts
// const window = this;
var _HI = window.HumanInput; // For noConflict
var screen = window.screen;
var document = window.document;
// NOTE: "blur", "reset", and "submit" are all just handled via _genericEvent()
var defaultEvents = ["blur", "click", "compositionend", "compositionstart", "compositionupdate", "contextmenu", "focus", "hold", "input", "keydown", "keypress", "keyup", "reset", "submit"];
var instances = [];
var plugins = [];
// Lesser state tracking variables
var lastDownLength = 0;
var finishedKeyCombo = false; // Used with combos like ctrl-c
// Check if the browser supports KeyboardEvent.key:
var KEYSUPPORT = false;
if (Object.keys(window.KeyboardEvent.prototype).includes('key')) {
KEYSUPPORT = true;
}
var HumanInput = function (_EventHandler) {
_inherits(HumanInput, _EventHandler);
// Core API functions
function HumanInput(elem, settings) {
var _settings$listenEvent;
_classCallCheck(this, HumanInput);
// These are the defaults:
var defaultSettings = {
listenEvents: HumanInput.defaultListenEvents,
addEvents: [],
removeEvents: [],
eventOptions: {},
noKeyRepeat: true,
sequenceTimeout: 3500,
holdInterval: 250,
maxSequenceBuf: 12,
uniqueNumpad: false,
swipeThreshold: 50,
moveThreshold: 5,
disableSequences: false,
disableSelectors: false,
eventMap: {},
translate: _utils.noop,
logLevel: 'INFO',
logPrefix: (0, _utils.getLoggingName)(elem)
};
// Apply settings over the defaults:
for (var item in settings) {
defaultSettings[item] = settings[item];
}
settings = defaultSettings;
var log = new _logger.Logger(settings.logLevel, settings.logPrefix);
// Interestingly, you can't just return an existing instance if you haven't called super() yet
// (may be a WebPack thing) which is why this is down here and not at the top of the constructor:
var _this = _possibleConstructorReturn(this, _EventHandler.call(this, log));
if (instances.length) {
// Existing instance(s); check them for duplicates on the same element
for (var inst in instances) {
if (instances[inst].elem === elem) {
var _ret;
return _ret = instances[inst], _possibleConstructorReturn(_this, _ret); // Enforce singleton per element (efficiency!)
}
}
}
instances.push(_this); // Used when enforcing singletons
// For localization of our few strings:
_this.l = settings.translate;
(_settings$listenEvent = settings.listenEvents).push.apply(_settings$listenEvent, settings.addEvents);
if (settings.removeEvents.length) {
settings.listenEvents = settings.listenEvents.filter(function (item) {
return !settings.removeEvents.includes(item);
});
}
_this.settings = settings;
_this.elem = (0, _utils.getNode)(elem || window);
_this.Logger = _logger.Logger; // In case someone wants to use it separately
_this.log = log;
_this.VERSION = "1.1.15";
_this.plugin_instances = []; // Each instance of HumanInput gets its own set of plugin instances
// NOTE: Most state-tracking variables are set inside HumanInput.init()
// This needs to be set early on so we don't get errors in the early trigger() calls:
_this.eventMap = { forward: {}, reverse: {} };
// NOTE: keyMaps are only necessary for Safari
_this.keyMaps = { 0: {}, 1: {}, 2: {} };
if (_keymaps.keyMaps) {
_this.keyMaps = _keymaps.keyMaps;
}
// Apply some post-instantiation settings
if (settings.disableSequences) {
_this._handleSeqEvents = _utils.noop;
}
if (settings.disableSelectors) {
_this._handleSelectors = _utils.noop;
}
// These functions need to be bound to work properly ('this' will be window or this.elem which isn't what we want)
['_composition', '_contextmenu', '_holdCounter', '_resetSeqTimeout', '_resetStates', '_keydown', '_keypress', '_keyup', 'trigger'].forEach(function (event) {
_this[event] = _this[event].bind(_this);
});
// Take care of our multi-function functions :)
_this._compositionstart = _this._composition;
_this._compositionupdate = _this._composition;
_this._compositionend = _this._composition;
// Add some generic window/document events so plugins don't need to handle
// them on their own; it's better to have *one* listener.
if (typeof document.hidden !== "undefined") {
document.addEventListener('visibilitychange', function (e) {
if (document.hidden) {
_this.trigger('document:hidden', e);
} else {
_this.trigger('document:visible', e);
}
}, false);
}
var genericHandler = _this._genericEvent.bind(_this, 'window');
// Window focus and blur are also almost always user-initiated:
if (window.onblur !== undefined) {
(0, _utils.addListeners)(window, ['blur', 'focus'], genericHandler, true);
}
if (_this.elem === window) {
// Only attach window events if HumanInput was instantiated on the 'window'
// These events are usually user-initiated so they count:
(0, _utils.addListeners)(window, ['beforeunload', 'hashchange', 'languagechange'], genericHandler, true);
// Window resizing needs some de-bouncing or you end up with far too many events being fired while the user drags:
window.addEventListener('resize', (0, _utils.debounce)(genericHandler, 250), true);
// Orientation change is almost always human-initiated:
if (window.orientation !== undefined) {
window.addEventListener('orientationchange', function (e) {
var event = 'window:orientation';
_this.trigger(event, e);
// NOTE: There's built-in aliases for 'landscape' and 'portrait'
if (Math.abs(window.orientation) === 90) {
_this.trigger(event + ':landscape', e);
} else {
_this.trigger(event + ':portrait', e);
}
}, false);
}
}
// Start er up!
_this.init();
return _this;
}
HumanInput.prototype.map = function map(eventMap) {
/**:HumanInput.map(eventMap)
This function will update ``this.eventMap`` with the given *obj*'s keys and values and then with it's values and keys (so lookups can be performed in reverse).
*/
for (var item in eventMap) {
// Create both forward and reverse mappings
this.eventMap.forward[item] = eventMap[item];
this.eventMap.reverse[eventMap[item]] = item;
}
};
HumanInput.prototype.init = function init() {
var _this2 = this;
var settings = this.settings;
var listenEvents = settings.listenEvents;
var debug = this.log.debug;
if (this.eventCount) {
// It already exists/reset scenario
// This is so a reset can be detected and handled properly by external stuff
this.trigger('hi:reset');
}
this.scope = ''; // The current event scope (empty string means global scope)
this.state = { // Stores temporary/fleeting state information
down: [], // Tracks which keys/buttons are currently held down (pressed)
downAlt: [], // Used to keep keydown and keyup events in sync when the 'key' gets replaced inside the keypress event
holdStart: null, // Tracks the start time of hold events
holdArgs: [], // Keeps track of arguments that will be passed to hold events
seqBuffer: [] // For tracking sequences like 'a b c'
};
this.events = {}; // Tracks functions attached to events
// The eventMap can be used to change the name of triggered events (e.g. 'w': 'forward')
this.eventMap = { forward: {}, reverse: {} };
this.map(settings.eventMap); // Apply any provided eventMap
// NOTE: Possible new feature: Transform events using registerable functions:
// this.transforms = []; // Used for transforming event names
finishedKeyCombo = false; // Internal state tracking of keyboard combos like ctrl-c
// Setup our basic window listen events
// This tries to emulate fullscreen detection since the Fullscreen API doesn't friggin' work when the user presses F11 or selects fullscreen from the menu...
if (this.elem === window) {
this.on('window:resize', function () {
// NOTE: This may not work with multiple monitors
if (window.outerWidth === screen.width && window.outerHeight === screen.height) {
_this2.state.fullscreen = true;
_this2.trigger('fullscreen', true);
} else if (_this2.state.fullscreen) {
_this2.state.fullscreen = false;
_this2.trigger('fullscreen', false);
}
});
}
// Reset states if the user alt-tabs away (or similar)
this.on('window:blur', this._resetStates);
// Enable plugins
for (var i = 0; i < plugins.length; i++) {
// Instantiate the plugin (if not already)
if (!(this.plugin_instances[i] instanceof plugins[i])) {
this.plugin_instances[i] = new plugins[i](this);
}
var plugin = this.plugin_instances[i];
debug(this.l('Initializing Plugin:'), plugin.constructor.name);
if ((0, _utils.isFunction)(plugin.init)) {
var initResult = plugin.init(this);
for (var attr in initResult.exports) {
this[attr] = initResult.exports[attr];
}
}
}
// Set or reset our event listeners (enables changing built-in events at a later time)
this.off('hi:pause');
this.on('hi:pause', function () {
debug(_this2.l('Pause: Removing event listeners ', listenEvents));
listenEvents.forEach(function (event) {
var opts = settings.eventOptions[event] || true;
if ((0, _utils.isFunction)(_this2['_' + event])) {
_this2.elem.removeEventListener(event, _this2['_' + event], opts);
}
});
});
this.off(['hi:initialized', 'hi:resume']); // In case of re-init
this.on(['hi:initialized', 'hi:resume'], function () {
debug('HumanInput Version: ' + _this2.VERSION);
debug(_this2.l('Start/Resume: Addding event listeners'), listenEvents);
listenEvents.forEach(function (event) {
var opts = settings.eventOptions[event] || true;
if ((0, _utils.isFunction)(_this2['_' + event])) {
// TODO: Figure out why removeEventListener isn't working
_this2.elem.removeEventListener(event, _this2['_' + event], opts);
_this2.elem.addEventListener(event, _this2['_' + event], opts);
} else {
// No function for this event; use the generic event handler and hope for the best
_this2['_' + event] = _this2._genericEvent.bind(_this2, '');
_this2.elem.addEventListener(event, _this2['_' + event], opts);
}
});
});
this.trigger('hi:initialized', this);
};
HumanInput.prototype.noConflict = function noConflict() {
window.HumanInput = _HI;
return HumanInput;
};
// Core *internal* API functions
HumanInput.prototype._resetStates = function _resetStates() {
// This gets called after the sequenceTimeout to reset the state of all keys and modifiers (and a few other things)
// Besides the obvious usefulness of this with sequences, it also serves as a fallback mechanism if something goes
// wrong with state tracking.
// NOTE: As long as something is 'down' this won't (normally) be called because the sequenceTimeout gets cleared on 'down' events and set on 'up' events.
var state = this.state;
state.seqBuffer = [];
state.down = [];
state.downAlt = [];
state.holdArgs = [];
lastDownLength = 0;
finishedKeyCombo = false;
clearTimeout(state.holdTimeout);
this.trigger('hi:resetstates');
};
HumanInput.prototype._resetSeqTimeout = function _resetSeqTimeout() {
var _this3 = this;
// Ensure that the seqBuffer doesn't get emptied (yet):
clearTimeout(this.state.seqTimer);
this.state.seqTimer = setTimeout(function () {
_this3.log.debug(_this3.l('Resetting event sequence states due to timeout'));
_this3._resetStates();
}, this.settings.sequenceTimeout);
};
HumanInput.prototype._genericEvent = function _genericEvent(prefix, e) {
// Can be used with any event handled via addEventListener() to trigger a corresponding event in HumanInput
var notFiltered = this.filter(e),
results;
if (notFiltered) {
if (prefix.type) {
e = prefix;prefix = null;
}
if (prefix) {
prefix = prefix + ':';
} else {
prefix = '';
}
results = this.trigger(this.scope + prefix + e.type, e);
if (e.target) {
// Also triger events like '<event>:#id' or '<event>:.class':
results = results.concat(this._handleSelectors(prefix + e.type, e));
}
(0, _utils.handlePreventDefault)(e, results);
}
};
HumanInput.prototype._handleSelectors = function _handleSelectors(eventName) {
// Triggers the given *eventName* using various combinations of information taken from the given *e.target*.
var results = [];
var args = Array.from(arguments).slice(1);
var toBind = this; // A fallback
var constructedEvent;
if (args[0] && args[0].target) {
toBind = args[0].target;
if (toBind.id) {
constructedEvent = eventName + ':#' + toBind.id;
results = this.trigger.apply(toBind, [constructedEvent].concat(args));
}
if (toBind.classList && toBind.classList.length) {
for (var i = 0; i < toBind.classList.length; i++) {
constructedEvent = eventName + ':.' + toBind.classList.item(i);
results = results.concat(this.trigger.apply(toBind, [constructedEvent].concat(args)));
}
}
}
return results;
};
HumanInput.prototype._addDown = function _addDown(event, alt) {
// Adds the given *event* to this.state.down and this.state.downAlt to ensure the two stay in sync in terms of how many items they hold.
// If an *alt* event is given it will be stored in this.state.downAlt explicitly
var state = this.state;
var index = state.down.indexOf(event);
if (index == -1) {
index = state.downAlt.indexOf(event);
}
if (index == -1 && alt) {
index = state.downAlt.indexOf(alt);
}
if (index == -1) {
state.down.push(event);
if (alt) {
state.downAlt.push(alt);
} else {
state.downAlt.push(event);
}
}
this.trigger('hi:adddown', event, alt); // So plugins and modules can do stuff when this happens
};
HumanInput.prototype._removeDown = function _removeDown(event) {
// Removes the given *event* from this.state.down and this.state.downAlt (if found); keeping the two in sync in terms of indexes
var state = this.state;
var settings = this.settings;
var down = state.down;
var downAlt = state.downAlt;
var index = state.down.indexOf(event);
clearTimeout(state.holdTimeout);
if (index === -1) {
// Event changed between 'down' and 'up' events
index = downAlt.indexOf(event);
}
if (index === -1) {
// Still no index? Try one more thing: Upper case
index = downAlt.indexOf(event.toUpperCase()); // Handles the situation where the user releases a key *after* a Shift key combo
}
if (index !== -1) {
down.splice(index, 1);
downAlt.splice(index, 1);
}
lastDownLength = down.length;
if (settings.listenEvents.includes('hold')) {
state.holdArgs.pop();
state.heldTime = settings.holdInterval;
state.holdStart = Date.now(); // This needs to be reset whenever this.state.down changes
if (down.length) {
// Continue 'hold' events for any remaining 'down' events
state.holdTimeout = setTimeout(this._holdCounter, settings.holdInterval);
}
}
this.trigger('hi:removedown', event); // So plugins and modules can do stuff when this happens
};
HumanInput.prototype._doDownEvent = function _doDownEvent(event) {
/*
Adds the given *event* to this.state.down, calls this._handleDownEvents(), removes the event from this.state.down, then returns the triggered results.
Any additional arguments after the given *event* will be passed to this._handleDownEvents().
*/
var args = Array.from(arguments).slice(1);
this._addDown(event);
var results = this._handleDownEvents.apply(this, args);
this._handleSeqEvents(args[0]); // args[0] will be the browser event
this._removeDown(event);
return results;
};
HumanInput.prototype._keyEvent = function _keyEvent(key) {
// Given a *key* like 'ShiftLeft' returns the "official" key event or just the given *key* in lower case
if (_constants.CONTROLKEYS.includes(key)) {
return _constants.ControlKeyEvent;
} else if (_constants.ALTKEYS.includes(key)) {
return _constants.AltKeyEvent;
} else if (_constants.SHIFTKEYS.includes(key)) {
return _constants.ShiftKeyEvent;
} else if (_constants.OSKEYS.includes(key)) {
return _constants.OSKeyEvent;
} else {
return key.toLowerCase();
}
};
// NOTE: Context menu support can't be modularized (see note below for details)
HumanInput.prototype._contextmenu = function _contextmenu(e) {
if (this.filter(e)) {
var results = this._triggerWithSelectors(e.type, [e]);
/* NOTE: Unless the contextmenu is cancelled (i.e. preventDefault) we need to ensure that we reset all 'down' events.
The reason for this is because when the context menu comes up in the browser it immediately loses track of all
keys/buttons just like if the user were to alt-tab to a different application; the 'up' events will never fire.
*/
if (!(0, _utils.handlePreventDefault)(e, results)) {
this._resetStates();
}
}
};
// NOTE: Possible new feature:
// _transform(event) {
// /**:HumanInput._transform()
//
// Iterates over all the functions registered in ``this.transforms`` passing the given *event* and returns the result.
// */
// for (let renamer in this.transforms) {
// event = renamer(event);
// }
// return event;
// }
HumanInput.prototype._handleShifted = function _handleShifted(down) {
/* A DRY function to remove the shift key from *down* if warranted (e.g. just ['!'] instead of ['ShiftLeft', '!']). Returns true if *down* was modified.
Note that *down* should be a copy of ``this.state.down`` and not the actual ``this.state.down`` array.
*/
var lastItemIndex = down.length - 1;
var shiftKeyIndex = -1;
for (var i = 0; i < down.length; i++) {
shiftKeyIndex = down[i].indexOf('Shift');
if (shiftKeyIndex != -1) {
break;
}
}
if (shiftKeyIndex != -1) {
// The last key in the 'down' array is all we care about...
// Use the difference between the 'key' and 'code' (aka the 'alt' name) to detect chars that require shift but aren't uppercase:
if (down[lastItemIndex] != this.state.downAlt[lastItemIndex]) {
down.splice(shiftKeyIndex, 1); // Remove the shift key
return true; // We're done here
}
}
};
HumanInput.prototype._handleDownEvents = function _handleDownEvents() {
var settings = this.settings;
var state = this.state;
var events = this._downEvents();
var results = [];
var args = Array.from(arguments);
for (var i = 0; i < events.length; i++) {
results = results.concat(this._triggerWithSelectors(events[i], args));
}
if (settings.listenEvents.includes('hold')) {
state.holdArgs.push(args);
state.heldTime = settings.holdInterval; // Restart it
state.holdStart = Date.now();
// Start the 'hold:' counter! If no changes to this.state.down, fire a hold:<n>:<event> event for every second the down events are held
clearTimeout(state.holdTimeout); // Just in case
state.holdTimeout = setTimeout(this._holdCounter, settings.holdInterval);
}
return results;
};
HumanInput.prototype._handleSeqEvents = function _handleSeqEvents(e) {
// NOTE: This function should only be called when a button or key is released (i.e. when state changes to UP)
var state = this.state;
var seqBuffer = state.seqBuffer;
var results = [];
var down = state.down.slice(0);
if (lastDownLength < down.length) {
// User just finished a combo (e.g. ctrl-a)
if (this.sequenceFilter(e)) {
this._handleShifted(down);
(0, _utils.sortEvents)(down);
seqBuffer.push(down);
if (seqBuffer.length > this.settings.maxSequenceBuf) {
// Make sure it stays within the specified max
seqBuffer.shift();
}
if (seqBuffer.length > 1) {
// Trigger all combinations of sequence buffer events
var combos = this._seqCombinations(seqBuffer);
for (var i = 0; i < combos.length; i++) {
var sliced = (0, _utils.seqSlicer)(combos[i]);
for (var j = 0; j < sliced.length; j++) {
results = results.concat(this.trigger(this.scope + sliced[j], this));
}
}
if (results.length) {
// Reset the sequence buffer on matched event so we don't end up triggering more than once per sequence
seqBuffer = [];
}
}
}
}
this._resetSeqTimeout();
};
HumanInput.prototype._normSpecial = function _normSpecial(location, key, code) {
// Just a DRY function for keys that need some extra love
if (key == ' ') {
// Spacebar
return code; // The code for spacebar is 'Space'
}
if (code.hasOwnProperty('includes')) {
// This check was put here to resolve the edge case in issue #14 (https://github.com/liftoff/HumanInput/issues/14)
if (code.includes('Left') || code.includes('Right')) {
// Use the left and right variants of the name as the 'key'
key = code; // So modifiers can be more specific
}
}
if (this.settings.uniqueNumpad && location === 3) {
return 'numpad' + key; // Will be something like 'numpad5' or 'numpadenter'
}
if (key.startsWith('Arrow')) {
key = key.substr(5); // Remove the 'arrow' part
}
return key;
};
HumanInput.prototype._holdCounter = function _holdCounter() {
// This function triggers 'hold' events every <holdInterval ms> when events are 'down'.
var state = this.state;
var settings = this.settings;
var events = this._downEvents();
if (!events.length) {
return;
}
clearTimeout(state.holdTimeout);
var lastArg = state.holdArgs[state.holdArgs.length - 1] || [];
var realHeldTime = Date.now() - state.holdStart;
this._resetSeqTimeout(); // Make sure the sequence buffer reset function doesn't clear out our hold times
for (var i = 0; i < events.length; i++) {
// This is mostly so plugins and whatnot can do stuff when hold events are triggered
this.trigger('hold', events[i], realHeldTime);
// This is the meat of hold events:
this._triggerWithSelectors('hold:' + state.heldTime + ':' + events[i], lastArg.concat([realHeldTime]));
}
state.heldTime += settings.holdInterval;
if (state.heldTime < 5001) {
// Any longer than this and it probably means something went wrong (e.g. browser bug with touchend not firing)
state.holdTimeout = setTimeout(this._holdCounter, settings.holdInterval);
}
};
HumanInput.prototype._triggerWithSelectors = function _triggerWithSelectors(event, args) {
// A DRY function that triggers the given *event* normally and then via this._handleSelectors()
var results = [];
var scopedEvent = this.scope + event;
results = results.concat(this.trigger.apply(this, [scopedEvent].concat(args)));
results = results.concat(this._handleSelectors.apply(this, [scopedEvent].concat(args)));
return results;
};
HumanInput.prototype._seqCombinations = function _seqCombinations(buffer, joinChar) {
/**:HumanInput._seqCombinations(buffer[, joinChar])
Returns all possible alternate name combinations of events (as an Array) for a given buffer (*buffer*) which must be an Array of Arrays in the form of::
[['ControlLeft', 'c'], ['a']]
The example above would be returned as an Array of strings that can be passed to :js:func:`utils.seqSlicer` like so::
['controlleft-c a', 'ctrl-c a']
The given *joinChar* will be used to join the characters for key combinations.
.. note:: Events will always be emitted in lower case. To use events with upper case letters use the 'shift' modifier (e.g. 'shift-a'). Shifted letters that are not upper case do not require the 'shift' modifier (e.g. '?'). This goes for combinations that include other modifiers (e.g. 'ctrl-#' would not be 'ctrl-shift-3').
*/
var i, j;
var joinChar_ = joinChar || '-';
var replacement = (0, _utils.cloneArray)(buffer);
var out = [];
var temp = [];
for (i = 0; i < buffer.length; i++) {
out.push(replacement[i].join(joinChar_).toLowerCase());
// Normalize names (shiftleft becomes shift)
for (j = 0; j < buffer[i].length; j++) {
replacement[i][j] = [this._keyEvent(buffer[i][j])];
}
}
out = [out.join(' ')]; // Make a version that has the original key/modifier names (e.g. shiftleft)
for (i = 0; i < replacement.length; i++) {
if (replacement[i].length) {
temp.push((0, _utils.arrayCombinations)(replacement[i], joinChar_));
}
}
for (i = 0; i < temp.length; i++) {
temp[i] = this.eventMap.forward[temp[i]] || temp[i];
}
temp = temp.join(' ');
if (temp != out[0]) {
// Only if they're actually different
out.push(temp);
}
return out;
};
HumanInput.prototype._downEvents = function _downEvents() {
/* Returns all events that could represent the current state of ``this.state.down``. e.g. ['shiftleft-a', 'shift-a'] but not ['shift', 'a']
*/
var events = [];
var shiftedKey;
var down = this.state.down.slice(0); // Make a copy because we're going to mess with it
var downLength = down.length; // Need the original length for reference
var unshiftedDown = this.state.downAlt.slice(0); // The 'alt' chars (from the code) represent the un-shifted form of the key
if (downLength) {
if (downLength === 1) {
return this._seqCombinations([down]);
}
if (downLength > 1) {
// Combo; may need shift key removed to generate the correct event (e.g. '!' instead of 'shift-!')
shiftedKey = this._handleShifted(down);
// Before sorting, fire the precise combo event
events = events.concat(this._seqCombinations([down], '->'));
if (shiftedKey) {
// Generate events for the un-shifted chars (e.g. shift->1, shift->2, etc)
events = events.concat(this._seqCombinations([unshiftedDown], '->'));
}
}
if (down.length > 1) {
// Is there more than one item *after* we may have removed shift?
(0, _utils.sortEvents)(down);
// Make events for all alternate names (e.g. 'controlleft-a' and 'ctrl-a'):
events = events.concat(this._seqCombinations([down]));
}
if (shiftedKey) {
(0, _utils.sortEvents)(unshiftedDown);
events = events.concat(this._seqCombinations([unshiftedDown]));
}
}
return events;
};
HumanInput.prototype._keydown = function _keydown(e) {
// NOTE: e.which and e.keyCode will be incorrect for a *lot* of keys
// and basically always incorrect with alternate keyboard layouts
// which is why we replace this.state.down[<the key>] inside _keypress()
// when we can (for browsers that don't support KeyboardEvent.key).
var state = this.state;
var results;
var keyCode = e.which || e.keyCode;
var location = e.location || 0;
// NOTE: Should I put e.code first below? Hmmm. Should we allow keyMaps to override the browser's native key name if it's available?
var code = this.keyMaps[location][keyCode] || this.keyMaps[0][keyCode] || e.code;
var key = e.key || code;
var event = e.type;
var notFiltered = this.filter(e);
var fpEvent = this.scope + 'faceplant';
if (e.repeat && notFiltered && this.settings.noKeyRepeat) {
e.preventDefault(); // Make sure keypress doesn't fire after this
return false; // Don't do anything if key repeat is disabled
}
key = this._normSpecial(location, key, code);
if (key == 'Compose') {
// This indicates that the user is entering a composition
state.composing = true;
return;
}
if (!state.down.includes(key)) {
this._addDown(key, code);
}
// Don't let the sequence buffer reset if the user is active:
this._resetSeqTimeout();
if (notFiltered) {
// This is in case someone wants just on('keydown'):
results = this._triggerWithSelectors(event, [e, key, code]);
// Now trigger the more specific keydown:<key> event:
results = results.concat(this._triggerWithSelectors(event += ':' + key.toLowerCase(), [e, key, code]));
if (state.down.length > 5) {
// 6 or more keys down at once? FACEPLANT!
results = results.concat(this.trigger(fpEvent, e)); // ...or just key mashing :)
}
/* NOTE: For browsers that support KeyboardEvent.key we can trigger the usual
events inside _keydown() (which is faster) but other browsers require
_keypress() be called first to fix localized/shifted keys. So for those
browser we call _handleDownEvents() inside _keyup(). */
if (KEYSUPPORT) {
results = results.concat(this._handleDownEvents(e, key, code));
}
(0, _utils.handlePreventDefault)(e, results);
}
};
// NOTE: Use of _keypress is only necessary until Safari supports KeyboardEvent.key!
HumanInput.prototype._keypress = function _keypress(e) {
// NOTE: keypress events don't always fire when modifiers are used!
// This means that such browsers may never get sequences like 'ctrl-?'
var charCode = e.charCode || e.which,
key = e.key || String.fromCharCode(charCode);
if (!KEYSUPPORT && charCode > 47 && key.length) {
// Replace the possibly-incorrect key with the correct one
this.state.down.pop();
this.state.down.push(key);
}
};
HumanInput.prototype._keyup = function _keyup(e) {
var state = this.state;
var results;
var keyCode = e.which || e.keyCode;
var location = e.location || 0;
// NOTE: Should I put e.code first below? Hmmm. Should we allow keyMaps to override the browser's native key name if it's available?
var code = this.keyMaps[location][keyCode] || this.keyMaps[0][keyCode] || e.code;
var key = e.key || code;
var event = e.type;
key = this._normSpecial(location, key, code);
if (_constants.MACOS) {
/* Macs have a bug where the keyup event doesn't fire for non-modifier keys if the command key
was held during a combo.
To prevent this from mis-firing hold events and ensure that state stays sane we have to
*assume* that any non-modifier keys are no longer being held after the command key is released.
Note to Apple: Fix your OS! */
if (_constants.OSKEYS.includes(key)) {
// It's the command key
var toRemove = [];
// Reset any non-modifier keys in this.state.down
for (var i = 0; i < state.down.length; i++) {
if (!_constants.AllModifiers.includes(state.down[i])) {
toRemove.push(state.down[i]);
}
}
for (var _i = 0; _i < toRemove.length; _i++) {
this._removeDown(toRemove[_i]);
}
}
}
if (!state.downAlt.length) {
// Implies key states were reset or out-of-order somehow
return; // Don't do anything since our state is invalid
}
if (state.composing) {
state.composing = false;
return;
}
if (this.filter(e)) {
if (!KEYSUPPORT) {
this._handleDownEvents(e);
}
// This is in case someone wants just on('keyup'):
results = this._triggerWithSelectors(event, [e, key, code]);
// Now trigger the more specific keyup:<key> event:
results = results.concat(this._triggerWithSelectors(event + ':' + key.toLowerCase(), [e, key, code]));
this._handleSeqEvents(e);
(0, _utils.handlePreventDefault)(e, results);
}
// Remove the key from this.state.down even if we're filtered (state must stay accurate)
this._removeDown(key);
};
HumanInput.prototype._composition = function _composition(e) {
var data = e.data;
var event = 'compos';
if (this.filter(e)) {
var results = this._triggerWithSelectors(e.type, [e, data]);
if (data) {
if (e.type == 'compositionupdate') {
event += 'ing:"' + data + '"';
} else if (e.type == 'compositionend') {
event += 'ed:"' + data + '"';
}
results = results.concat(this._triggerWithSelectors(event, [e]));
(0, _utils.handlePreventDefault)(e, results);
}
}
};
// Public API functions
HumanInput.prototype.filter = function filter(event) {
/**:HumanInput.filter(event)
This function gets called before HumanInput events are triggered. If it returns ``False`` then ``trigger()`` will not be called.
Override this function to implement your own filter.
.. note:: The given *event* won't always be a browser-generated event but it should always have a 'type' and 'target'.
*/
var tagName = (event.target || event.srcElement).tagName,
// The events we're concerned with:
keyboardEvents = ['keydown', 'keyup', 'keypress'];
if (event.type && keyboardEvents.includes(event.type)) {
// Don't trigger keyboard events if the user is typing into a form
return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
}
return true;
};
HumanInput.prototype.sequenceFilter = function sequenceFilter(event) {
/**:HumanInput.sequenceFilter(event)
This function gets called before HumanInput events are added to the sequence buffer. If it returns ``False`` then the event will not be added to the sequence buffer.
Override this function to implement your own filter.
.. note:: The given *event* won't always be a browser-generated event but it should always have a 'type' and 'target'.
*/
return true; // Don't filter out anything
};
HumanInput.prototype.pushScope = function pushScope(scope) {
/**:HumanInput.pushScope(scope)
Pushes the given *scope* into HumanInput.scope. Examples::
> HI = HumanInput(window);
> HI.pushScope('foo');
> HI.scope;
'foo:'
> HI.pushScope('bar');
> HI.scope;
'foo.bar:'
*/
if (this.scope.length) {
this.scope = this.scope.slice(0, -1) + '.' + scope + ':';
} else {