UNPKG

react-hotkeys

Version:

A declarative library for handling hotkeys and focus within a React application

11 lines (10 loc) 74.6 kB
/** * ISC License * * Copyright (c) 2018, Aleck Greenham * * Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ "use strict";function _interopDefault(e){return e&&"object"==typeof e&&"default"in e?e.default:e}Object.defineProperty(exports,"__esModule",{value:!0});var PropTypes=_interopDefault(require("prop-types")),React=require("react"),React__default=_interopDefault(React);function _typeof(e){return(_typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function _classCallCheck(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function _defineProperties(e,t){for(var n=0;n<t.length;n++){var i=t[n];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}function _createClass(e,t,n){return t&&_defineProperties(e.prototype,t),n&&_defineProperties(e,n),e}function _defineProperty(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _extends(){return(_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e}).apply(this,arguments)}function _objectSpread(t){for(var e=1;e<arguments.length;e++){var n=null!=arguments[e]?arguments[e]:{},i=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(i=i.concat(Object.getOwnPropertySymbols(n).filter(function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable}))),i.forEach(function(e){_defineProperty(t,e,n[e])})}return t}function _inherits(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&_setPrototypeOf(e,t)}function _getPrototypeOf(e){return(_getPrototypeOf=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function _setPrototypeOf(e,t){return(_setPrototypeOf=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function isNativeReflectConstruct(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(Reflect.construct(Date,[],function(){})),!0}catch(e){return!1}}function _construct(e,t,n){return(_construct=isNativeReflectConstruct()?Reflect.construct:function(e,t,n){var i=[null];i.push.apply(i,t);var o=new(Function.bind.apply(e,i));return n&&_setPrototypeOf(o,n.prototype),o}).apply(null,arguments)}function _isNativeFunction(e){return-1!==Function.toString.call(e).indexOf("[native code]")}function _wrapNativeSuper(e){var n="function"==typeof Map?new Map:void 0;return(_wrapNativeSuper=function(e){if(null===e||!_isNativeFunction(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==n){if(n.has(e))return n.get(e);n.set(e,t)}function t(){return _construct(e,arguments,_getPrototypeOf(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),_setPrototypeOf(t,e)})(e)}function _objectWithoutPropertiesLoose(e,t){if(null==e)return{};var n,i,o={},r=Object.keys(e);for(i=0;i<r.length;i++)n=r[i],0<=t.indexOf(n)||(o[n]=e[n]);return o}function _objectWithoutProperties(e,t){if(null==e)return{};var n,i,o=_objectWithoutPropertiesLoose(e,t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);for(i=0;i<r.length;i++)n=r[i],0<=t.indexOf(n)||Object.prototype.propertyIsEnumerable.call(e,n)&&(o[n]=e[n])}return o}function _assertThisInitialized(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function _possibleConstructorReturn(e,t){return!t||"object"!=typeof t&&"function"!=typeof t?_assertThisInitialized(e):t}function _superPropBase(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=_getPrototypeOf(e)););return e}function _get(e,t,n){return(_get="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var i=_superPropBase(e,t);if(i){var o=Object.getOwnPropertyDescriptor(i,t);return o.get?o.get.call(n):o.value}})(e,t,n||e)}function _toConsumableArray(e){return _arrayWithoutHoles(e)||_iterableToArray(e)||_nonIterableSpread()}function _arrayWithoutHoles(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}function _iterableToArray(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}function _nonIterableSpread(){throw new TypeError("Invalid attempt to spread non-iterable instance")}function dictionaryFrom(e){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:null;return e.reduce(function(e,t){return e[t]=n||{value:t},e},{})}var _defaultConfiguration={logLevel:"warn",defaultKeyEvent:"keydown",defaultComponent:"div",defaultTabIndex:"-1",ignoreTags:["input","select","textarea"],enableHardSequences:!1,ignoreKeymapAndHandlerChangesByDefault:!0,ignoreEventsCondition:function(e){var t=e.target;if(t&&t.tagName){var n=t.tagName.toLowerCase();return Configuration.option("_ignoreTagsDict")[n]||t.isContentEditable}return!1},ignoreRepeatedEventsWhenKeyHeldDown:!0,simulateMissingKeyPressEvents:!0,stopEventPropagationAfterHandling:!0,stopEventPropagationAfterIgnoring:!0,allowCombinationSubmatches:!1,customKeyCodes:{}},_configuration=_objectSpread({},_defaultConfiguration);_configuration._ignoreTagsDict=dictionaryFrom(_configuration.ignoreTags,!0);var Configuration=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"init",value:function(t){var n=this,e=t.ignoreTags,i=t.customKeyCodes;e&&(t._ignoreTagsDict=dictionaryFrom(t.ignoreTags)),i&&(t._customKeyNamesDict=dictionaryFrom(Object.values(t.customKeyCodes))),-1!==["verbose","debug","info"].indexOf(t.logLevel)&&console.warn("React HotKeys: You have requested log level '".concat(t.logLevel,"' but for performance reasons, logging below severity level 'warning' is disabled in production. Please use the development build for complete logs.")),Object.keys(t).forEach(function(e){n.set(e,t[e])})}},{key:"set",value:function(e,t){_configuration[e]=t}},{key:"reset",value:function(e){_configuration[e]=_defaultConfiguration[e]}},{key:"option",value:function(e){return _configuration[e]}}]),e}(),Logger=function(){function n(){var t=this,e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"warn";_classCallCheck(this,n),_defineProperty(this,"verbose",this.noop),_defineProperty(this,"debug",this.noop),_defineProperty(this,"info",this.noop),_defineProperty(this,"warn",this.noop),_defineProperty(this,"error",this.noop),this.logLevel=this.constructor.levels[e],this.logLevel>=this.constructor.levels.error&&(this.error=console.error,this.logLevel>=this.constructor.levels.warn&&(this.warn=console.warn,["info","debug","verbose"].some(function(e){return!(t.logLevel>=t.constructor.levels[e])||(t[e]=console.log,!1)})))}return _createClass(n,[{key:"noop",value:function(){}}]),n}();_defineProperty(Logger,"logIcons",["📕","📗","📘","📙"]),_defineProperty(Logger,"componentIcons",["🔺","⭐️","🔷","🔶","⬛️"]),_defineProperty(Logger,"eventIcons",["❤️","💚","💙","💛","💜","🧡"]),_defineProperty(Logger,"levels",{none:0,error:1,warn:2,info:3,debug:4,verbose:5});var KeyEventType={keydown:0,keypress:1,keyup:2},ModifierFlagsDictionary={Shift:["shiftKey"],Meta:["metaKey"],Control:["ctrlKey"],Alt:["altKey"]},ShiftedKeysDictionary={"`":["~"],1:["!"],2:["@",'"'],3:["#","£"],4:["$"],5:["%"],6:["^"],7:["&"],8:["*"],9:["("],0:[")"],"-":["_"],"=":["plus"],";":[":"],"'":['"',"@"],",":["<"],".":[">"],"/":["?"],"\\":["|"],"[":["{"],"]":["}"],"#":["~"]};function resolveShiftedAlias(e){return ShiftedKeysDictionary[e]||[1===e.length?e.toUpperCase():e]}function hasKey(e,t){return e.hasOwnProperty(t)}function invertArrayDictionary(i){var o=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};return Object.keys(i).reduce(function(t,n){var e=i[n];return e.forEach(function(e){hasKey(t,e)||(t[e]=[]),t[e].push(n)}),o.includeOriginal&&(hasKey(t,n)||(t[n]=[]),t[n]=[].concat(_toConsumableArray(t[n]),_toConsumableArray(e))),t},{})}var UnshiftedKeysDictionary=invertArrayDictionary(ShiftedKeysDictionary);function resolveUnshiftedAlias(e){return UnshiftedKeysDictionary[e]||[1===e.length?e.toLowerCase():e]}var KeyOSAndLayoutAliasesDictionary={},KeyOSAndLayoutAliasesDictionary$1=invertArrayDictionary(KeyOSAndLayoutAliasesDictionary,{includeOriginal:!0});function isString(e){return"string"==typeof e}function stripSuperfluousWhitespace(e){return isString(e)?e.trim().replace(/\s+/g," "):e}var MousetrapToReactKeyNamesDictionary={tab:"Tab",capslock:"CapsLock",shift:"Shift",meta:"Meta",alt:"Alt",ctrl:"Control",space:" ",spacebar:" ",escape:"Escape",esc:"Escape",left:"ArrowLeft",right:"ArrowRight",up:"ArrowUp",down:"ArrowDown",return:"Enter",del:"Delete",command:"Meta",option:"Alt",enter:"Enter",backspace:"Backspace",ins:"Insert",pageup:"PageUp",pagedown:"PageDown",end:"End",home:"Home",contextmenu:"ContextMenu",numlock:"Clear"},KeyShorthandDictionary={cmd:"Meta"};function standardizeKeyName(e){var t=e.toLowerCase();return MousetrapToReactKeyNamesDictionary[t]||KeyShorthandDictionary[t]||(e.match(/^f\d+$/)?e.toUpperCase():e)}var translateToKey={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},NonPrintableKeysDictionary=dictionaryFrom(Object.values(translateToKey),!0);function isNonPrintableKeyName(e){return!!NonPrintableKeysDictionary[e]}function isCustomKeyName(e){return Configuration.option("_customKeyNamesDict")[e]}function isValidKey(e){return isNonPrintableKeyName(e)||String.fromCharCode(e.charCodeAt(0))===e||isCustomKeyName(e)}var InvalidKeyNameError=function(e){function r(){var e,t;_classCallCheck(this,r);for(var n=arguments.length,i=new Array(n),o=0;o<n;o++)i[o]=arguments[o];return _defineProperty(_assertThisInitialized(_assertThisInitialized(t=_possibleConstructorReturn(this,(e=_getPrototypeOf(r)).call.apply(e,[this].concat(i))))),"name","InvalidKeyNameError"),t}return _inherits(r,_wrapNativeSuper(Error)),r}();function normalizedCombinationId(e){return e.sort().join("+")}var KeySequenceParser=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"parse",value:function(e){var n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},t=stripSuperfluousWhitespace(e).split(" ");try{var i=t.slice(0,t.length-1),o=t[t.length-1],r=i.map(function(e){var t=parseCombination(e,n);return normalizedCombinationId(Object.keys(t))}).join(" "),s=parseCombination(o,n),a={id:normalizedCombinationId(Object.keys(s)),keyDictionary:s,keyEventType:n.keyEventType,size:Object.keys(s).length};return{sequence:{prefix:r,size:i.length+1},combination:a}}catch(e){return{sequence:null,combination:null}}}}]),e}();function parseCombination(e){var i=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};return e.replace(/^\+|(\s|[^+]\+)\+/,"$1plus").split("+").reduce(function(e,t){var n=standardizeKeyName(t);if(i.ensureValidKeys&&!isValidKey(n))throw new InvalidKeyNameError;return e[n]=!0,e},{})}var AltedKeysDictionary={"`":["`"],1:["¡"],2:["™"],3:["£"],4:["¢"],5:["∞"],6:["§"],7:["¶"],8:["•"],9:["ª"],0:["º"],"-":["–"],"=":["≠"],a:["å"],b:["∫"],c:["ç"],d:["∂"],e:["´"],f:["ƒ"],g:["©"],h:["˙"],i:["ˆ"],j:["∆"],k:["˚"],l:["¬"],m:["µ"],n:["˜"],o:["ø"],p:["π"],q:["œ"],r:["®"],s:["ß"],t:["†"],u:["¨"],v:["√"],w:["∑"],x:["≈"],y:["¥"],z:["Ω"],"[":["“"],"]":["‘"],"\\":["«"],"'":["æ"],";":["…"],",":["≤"],".":["≥"],"/":["÷"]},UnaltedKeysDictionary=invertArrayDictionary(AltedKeysDictionary);function resolveUnaltedAlias(e){return UnaltedKeysDictionary[e]||[e]}function resolveAltedAlias(e){return AltedKeysDictionary[e]||[e]}var AltShiftedKeysDictionary={"`":["`"],1:["⁄"],2:["€"],3:["‹"],4:["›"],5:["fi"],6:["fl"],7:["‡"],8:["°"],9:["·"],0:["‚"],"-":["—"],"=":["±"],a:["Å"],b:["ı"],c:["Ç"],d:["Î"],e:["´"],f:["Ï"],g:["˝"],h:["Ó"],i:["ˆ"],j:["Ô"],k:[""],l:["Ò"],m:["Â"],n:["˜"],o:["Ø"],p:["π"],q:["Œ"],r:["‰"],s:["Í"],t:["Î"],u:["¨"],v:["◊"],w:["„"],x:["˛"],y:["Á"],z:["¸"],"[":["”"],"]":["’"],"\\":["»"],"'":["Æ"],";":["Ú"],",":["¯"],".":["˘"]},UnaltShiftedKeysDictionary=invertArrayDictionary(AltShiftedKeysDictionary);function resolveUnaltShiftedAlias(e){return UnaltShiftedKeysDictionary[e]||resolveUnshiftedAlias(e)}function resolveAltShiftedAlias(e){return AltShiftedKeysDictionary[e]||[e]}var KeyCombinationSerializer=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"serialize",value:function(e){var c=e.Shift,y=e.Alt,h={};return Object.keys(e).sort().forEach(function(e){var n=[];if(c)if(y){var t=resolveUnaltShiftedAlias(e),i=resolveAltShiftedAlias(e);n=[].concat(_toConsumableArray(n),[e],_toConsumableArray(t),_toConsumableArray(i))}else{var o=resolveUnshiftedAlias(e),r=resolveShiftedAlias(e);n=[].concat(_toConsumableArray(n),[e],_toConsumableArray(o),_toConsumableArray(r))}else if(y){var s=resolveUnaltedAlias(e),a=resolveAltedAlias(e);n=[].concat(_toConsumableArray(n),[e],_toConsumableArray(s),_toConsumableArray(a))}else{n.push(e);var u=KeyOSAndLayoutAliasesDictionary$1[e];u&&(n=[].concat(_toConsumableArray(n),_toConsumableArray(u)))}var l=Object.keys(h);0<l.length?l.forEach(function(t){n.forEach(function(e){h[t+"+".concat(e)]=_objectSpread({},h[t],_defineProperty({},e,!0))}),delete h[t]}):n.forEach(function(e){h[e]=_defineProperty({},e,!0)})}),Object.values(h).map(function(e){return Object.keys(e).sort().join("+")})}},{key:"isValidKeySerialization",value:function(e){return 0<e.length&&!!KeySequenceParser.parse(e,{ensureValidKeys:!0}).combination}}]),e}(),KeyEventSequenceIndex={previous:0,current:1};function resolveKeyAlias(e){return KeyOSAndLayoutAliasesDictionary$1[e]||[e]}function applicableAliasFunctions(e){if(e.Shift)return e.Alt?[resolveAltShiftedAlias,resolveUnaltShiftedAlias]:[resolveShiftedAlias,resolveUnshiftedAlias];if(e.Alt)return[resolveAltedAlias,resolveUnaltedAlias];var t=function(e){return[e]};return[t,t]}function isUndefined(e){return void 0===e}var KeyEventState={unseen:0,seen:1,simulated:2},KeyEventStateArrayManager=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"newRecord",value:function(e,t){var n=[KeyEventState.unseen,KeyEventState.unseen,KeyEventState.unseen];if(!isUndefined(e))for(var i=0;i<=e;i++)n[i]=t;return n}},{key:"setBit",value:function(e,t,n){return e[t]=n,e}},{key:"clone",value:function(e){for(var t=this.newRecord(),n=0;n<e.length;n++)t[n]=e[n];return t}}]),e}();function isObject(e){return!Array.isArray(e)&&"object"===_typeof(e)&&null!==e}function isEmpty(e){return isObject(e)?0===Object.keys(e).length:!e||0===e.length}function size(e){return isObject(e)?Object.keys(e).length:e.length}var KeyCombination=function(){function t(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,t),this._keys=e,this._includesKeyUp=!1,this._update()}return _createClass(t,[{key:"getIds",value:function(){return this._ids}},{key:"getKeyAliases",value:function(){return this._keyAliases}},{key:"getNormalizedKeyName",value:function(e){if(this._keys[e])return e;var t=this._keyAliases[e];return t||e}},{key:"getNumberOfKeys",value:function(){return size(this._keys)}},{key:"any",value:function(){return 0<Object.keys(this._getKeyStates()).length}},{key:"isEnding",value:function(){return this._includesKeyUp}},{key:"hasEnded",value:function(){return isEmpty(this.keysStillPressedDict())}},{key:"addKey",value:function(e,t){this._setKeyState(e,[KeyEventStateArrayManager.newRecord(),KeyEventStateArrayManager.newRecord(KeyEventType.keydown,t)])}},{key:"setKeyState",value:function(e,t,n){var i=this._getKeyState(e);if(this.isKeyIncluded(e)){var o=KeyEventStateArrayManager.clone(i[1]),r=KeyEventStateArrayManager.clone(o);KeyEventStateArrayManager.setBit(r,t,n),this._setKeyState(e,[o,r])}else this.addKey(e,n);t===KeyEventType.keyup&&(this._includesKeyUp=!0)}},{key:"forEachKey",value:function(e){return Object.keys(this._keys).forEach(e)}},{key:"some",value:function(e){return Object.keys(this._keys).some(e)}},{key:"getKeyDictionary",value:function(){return dictionaryFrom(Object.keys(this._getKeyStates()),!0)}},{key:"keysStillPressedDict",value:function(){var n=this;return Object.keys(this._keys).reduce(function(e,t){return n.isKeyStillPressed(t)&&(e[t]=n._getKeyState(t)),e},{})}},{key:"isKeyIncluded",value:function(e){return!!this._getKeyState(e)}},{key:"isKeyStillPressed",value:function(e){return this.isEventTriggered(e,KeyEventType.keypress)&&!this.isKeyReleased(e)}},{key:"isKeyReleased",value:function(e){return this.isEventTriggered(e,KeyEventType.keyup)}},{key:"isEventTriggered",value:function(e,t){return this._getKeyStateType(e,KeyEventSequenceIndex.current,t)}},{key:"wasEventPreviouslyTriggered",value:function(e,t){return this._getKeyStateType(e,KeyEventSequenceIndex.previous,t)}},{key:"isKeyPressSimulated",value:function(e){return this._isKeyEventSimulated(e,KeyEventType.keypress)}},{key:"isKeyUpSimulated",value:function(e){return this._isKeyEventSimulated(e,KeyEventType.keyup)}},{key:"describe",value:function(){return this.getIds()[0]}},{key:"toJSON",value:function(){return{keys:this._getKeyStates(),ids:this.getIds(),keyAliases:this.getKeyAliases()}}},{key:"_getKeyStateType",value:function(e,t,n){var i=this._getKeyState(e);return i&&i[t][n]}},{key:"_update",value:function(){this._ids=KeyCombinationSerializer.serialize(this._keys),this._keyAliases=buildKeyAliases(this._keys)}},{key:"_isKeyEventSimulated",value:function(e,t){return this.isEventTriggered(e,t)===KeyEventState.simulated}},{key:"_getKeyStates",value:function(){return this._keys}},{key:"_getKeyState",value:function(e){var t=this._keys[e];if(t)return t;var n=this._keyAliases[e];return n?this._keys[n]:void 0}},{key:"_setKeyState",value:function(e,t){var n=this.getNormalizedKeyName(e);this._keys[n]=t,this._update()}}]),t}();function buildKeyAliases(e){return Object.keys(e).reduce(function(n,i){return resolveKeyAlias(i).forEach(function(t){applicableAliasFunctions(e).forEach(function(e){e(t).forEach(function(e){e===i&&i===t||(n[e]=i)})})}),n},{})}var KeyHistory=function(){function i(e){var t=e.maxLength,n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:null;_classCallCheck(this,i),this._records=[],this._maxLength=t,n?this._push(n):this._push(new KeyCombination)}return _createClass(i,[{key:"getMostRecentCombinations",value:function(e){return this._records.slice(-e,-1)}},{key:"any",value:function(){return this._records.some(function(e){return e.any()})}},{key:"getLength",value:function(){return this._records.length}},{key:"getCurrentCombination",value:function(){return this._records[this.getLength()-1]}},{key:"addKeyToCurrentCombination",value:function(e,t,n){this._ensureInitialKeyCombination(),this.getCurrentCombination().setKeyState(e,t,n)}},{key:"setMaxLength",value:function(e){this._maxLength=e,this._trimHistory()}},{key:"startNewKeyCombination",value:function(e,t){this._ensureInitialKeyCombination();var n=new KeyCombination(this.getCurrentCombination().keysStillPressedDict());n.addKey(e,t),this._push(n)}},{key:"toJSON",value:function(){return this._records.map(function(e){return e.toJSON()})}},{key:"_ensureInitialKeyCombination",value:function(){0===this.getLength()&&this._push(new KeyCombination)}},{key:"_push",value:function(e){this._trimHistory(),this._records.push(e)}},{key:"_trimHistory",value:function(){for(;this.getLength()>this._maxLength;)this._shift()}},{key:"_shift",value:function(){this._records.shift()}}]),i}(),Registry=function(){function e(){_classCallCheck(this,e),this._registry={}}return _createClass(e,[{key:"get",value:function(e){return this._registry[e]}},{key:"set",value:function(e,t){this._registry[e]=t}},{key:"remove",value:function(e){delete this._registry[e]}},{key:"toJSON",value:function(){return this._registry}}]),e}();function arrayFrom(e){return Array.isArray(e)?e:e?[e]:[]}function without(n){var e=1<arguments.length&&void 0!==arguments[1]?arguments[1]:[],i=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},o=dictionaryFrom(arrayFrom(e));return Array.isArray(n)?n.reduce(function(e,t){return o[t]&&(i.stringifyFirst||o[t].value===t)||e.push(t),e},[]):isObject(n)?Object.keys(n).reduce(function(e,t){return o[t]||(e[t]=n[t]),e},{}):n}var ComponentTree=function(e){function i(){return _classCallCheck(this,i),_possibleConstructorReturn(this,_getPrototypeOf(i).apply(this,arguments))}return _inherits(i,Registry),_createClass(i,[{key:"add",value:function(e,t){_get(_getPrototypeOf(i.prototype),"set",this).call(this,e,{childIds:[],parentId:null,keyMap:t})}},{key:"update",value:function(e,t){var n=_get(_getPrototypeOf(i.prototype),"get",this).call(this,e);_get(_getPrototypeOf(i.prototype),"set",this).call(this,e,_objectSpread({},n,{keyMap:t}))}},{key:"setParent",value:function(e,t){this.get(e).parentId=t,this._addChildId(t,e)}},{key:"remove",value:function(e){var t=this._getParentId(e);this._removeChildId(t,e),_get(_getPrototypeOf(i.prototype),"remove",this).call(this,e)}},{key:"_getParentId",value:function(e){var t=this.get(e);return t&&t.parentId}},{key:"_addChildId",value:function(e,t){this.get(e).childIds.push(t)}},{key:"_removeChildId",value:function(e,t){var n=this.get(e);n&&(n.childIds=without(n.childIds,t))}}]),i}();function removeAtIndex(e,t){return[].concat(_toConsumableArray(e.slice(0,t)),_toConsumableArray(e.slice(t+1)))}var ComponentOptionsListIterator=function(){function t(e){_classCallCheck(this,t),this._list=e,this._position=-1}return _createClass(t,[{key:"getPosition",value:function(){return this._position}},{key:"getComponent",value:function(){return this._list.getAtPosition(this.getPosition())}},{key:"next",value:function(){return this.getPosition()+1<this._list.getLength()?(this._position++,this.getComponent()):null}}]),t}(),ComponentOptionsList=function(){function e(){_classCallCheck(this,e),this._list=[],this._idToIndex={},this._longestSequence=1,this._longestSequenceComponentId=null,this._keyMapEventRecord=KeyEventStateArrayManager.newRecord()}return _createClass(e,[{key:"getNewIterator",value:function(){return new ComponentOptionsListIterator(this)}},{key:"add",value:function(e,t,n,i){if(this.containsId(e))return this.update(e,t,n,i);var o=this._build(e,t,n,i);this._list.push(o);var r=this._getLastIndex();return this._idToIndex[e]=r}},{key:"containsId",value:function(e){return!!this.get(e)}},{key:"get",value:function(e){return this.getAtPosition(this.getIndexById(e))}},{key:"getIndexById",value:function(e){return this._idToIndex[e]}},{key:"update",value:function(e,t,n,i){var o=this._isUpdatingComponentWithLongestSequence(e),r=this.getLongestSequence(),s=this._build(e,t,n,i);o&&s.sequenceLength!==r&&(s.sequenceLength>r?this._longestSequence=s.sequenceLength:this._recalculateLongestSequence()),this._list[this.getIndexById(e)]=s}},{key:"remove",value:function(e){var t=this._isUpdatingComponentWithLongestSequence(e);this.removeAtPosition(this.getIndexById(e)),t&&this._recalculateLongestSequence()}},{key:"any",value:function(){return 0!==this.getLength()}},{key:"isRoot",value:function(e){return this.getIndexById(e)>=this.getLength()-1}},{key:"getLongestSequence",value:function(){return this._longestSequence}},{key:"anyActionsForEventType",value:function(e){return!!this._keyMapEventRecord[e]}},{key:"getLength",value:function(){return this._list.length}},{key:"getAtPosition",value:function(e){return this._list[e]}},{key:"removeAtPosition",value:function(e){this._list=removeAtIndex(this._list,e);for(var t=e;t<this.getLength();)this._idToIndex[this.getAtPosition(t).componentId]=t,t++}},{key:"toJSON",value:function(){return this._list}},{key:"_getLastIndex",value:function(){return this.getLength()-1}},{key:"_build",value:function(e,t,n,i){var o=this._applyHardSequences(t,n),r=o.keyMap,s=o.handlers;return{actions:this._buildActionDictionary(_objectSpread({},t,r),i,e),handlers:s,componentId:e,options:i}}},{key:"_isUpdatingComponentWithLongestSequence",value:function(e){return e===this._getLongestSequenceComponentId()}},{key:"_getLongestSequenceComponentId",value:function(){return this._longestSequenceComponentId}},{key:"_recalculateLongestSequence",value:function(){for(var e=this.getNewIterator();e.next();){var t=e.getComponent(),n=t.longestSequence,i=t.componentId;n>this.getLongestSequence()&&(this._longestSequenceComponentId=i,this._longestSequence=n)}}},{key:"_applyHardSequences",value:function(n,i){return Configuration.option("enableHardSequences")?Object.keys(i).reduce(function(e,t){return!!!n[t]&&KeyCombinationSerializer.isValidKeySerialization(t)&&(e.keyMap[t]=t),e.handlers[t]=i[t],e},{keyMap:{},handlers:{}}):{keyMap:n,handlers:i}}},{key:"_buildActionDictionary",value:function(t,s,a){var u=this;return Object.keys(t).reduce(function(o,r){var e=t[r];return(isObject(e)&&hasKey(e,"sequences")?arrayFrom(e.sequences):arrayFrom(e)).forEach(function(e){var t=normalizeActionOptions(e,s),n=t.keySequence,i=t.keyEventType;u._addActionOptions(o,a,r,n,i)}),o},{})}},{key:"_addActionOptions",value:function(e,t,n,i,o){var r=KeySequenceParser.parse(i,{keyEventType:o}),s=r.sequence,a=r.combination;s.size>this.getLongestSequence()&&(this._longestSequence=s.size,this._longestSequenceComponentId=t),this._keyMapEventRecord[o]=KeyEventState.seen,e[n]||(e[n]=[]),e[n].push(_objectSpread({prefix:s.prefix,actionName:n,sequenceLength:s.size},a))}}]),e}();function normalizeActionOptions(e,t){if(isObject(e)){var n=e.sequence,i=e.action;return{keySequence:n,keyEventType:isUndefined(i)?KeyEventType[t.defaultKeyEvent]:KeyEventType[i]}}return{keySequence:e,keyEventType:KeyEventType[t.defaultKeyEvent]}}function indexFromEnd(e,t){return e[e.length-(t+1)]}for(var KeysWithKeyUpHiddenByCmd={Enter:!0,Backspace:!0,ArrowRight:!0,ArrowLeft:!0,ArrowUp:!0,ArrowDown:!0,CapsLock:!0},i=1;i<13;i++)KeysWithKeyUpHiddenByCmd["F".concat(i)]=!0;function keyupIsHiddenByCmd(e){return 1===e.length||hasKey(KeysWithKeyUpHiddenByCmd,e)}var KeyCombinationMatcher=function(){function e(){_classCallCheck(this,e),this._actionConfigs={},this._order=null}return _createClass(e,[{key:"addMatch",value:function(e,t){if(this._includesMatcherForCombination(e.id)){var n=e.keyEventType,i=e.actionName,o=e.id;this._addHandlerToActionConfig(o,{keyEventType:n,actionName:i,handler:t})}else this._addNewActionConfig(e,t)}},{key:"findMatch",value:function(e,t,n){this._order||this._setOrder();var i=!0,o=!1,r=void 0;try{for(var s,a=this._order[Symbol.iterator]();!(i=(s=a.next()).done);i=!0){var u=s.value,l=this._actionConfigs[u];if(this._matchesActionConfig(e,t,n,l))return l}}catch(e){o=!0,r=e}finally{try{i||null==a.return||a.return()}finally{if(o)throw r}}return null}},{key:"toJSON",value:function(){return{actionConfigs:this._actionConfigs,order:this._order}}},{key:"_matchesActionConfig",value:function(t,n,i,e){if(!canBeMatched(t,e))return!1;if(!e.events[i])return!1;var o=!1;return Object.keys(e.keyDictionary).every(function(e){return!!t.isEventTriggered(e,i)&&(n&&n===t.getNormalizedKeyName(e)&&(o=!t.wasEventPreviouslyTriggered(e,i)),!0)})&&o}},{key:"_setOrder",value:function(){var n=Object.values(this._actionConfigs).reduce(function(e,t){var n=t.id,i=t.size;return e[i]||(e[i]=[]),e[i].push(n),e},{});this._order=Object.keys(n).sort(function(e,t){return t-e}).reduce(function(e,t){return e.concat(n[t])},[])}},{key:"_addNewActionConfig",value:function(e,t){var n=e.prefix,i=e.sequenceLength,o=e.id,r=e.keyDictionary,s=e.size,a=e.keyEventType,u=e.actionName;this._setCombinationMatcher(o,{prefix:n,sequenceLength:i,id:o,keyDictionary:r,size:s,events:{}}),this._addHandlerToActionConfig(o,{keyEventType:a,actionName:u,handler:t})}},{key:"_addHandlerToActionConfig",value:function(e,t){var n=t.keyEventType,i=t.actionName,o=t.handler,r=this._getCombinationMatcher(e);this._setCombinationMatcher(e,_objectSpread({},r,{events:_objectSpread({},r.events,_defineProperty({},n,{actionName:i,handler:o}))}))}},{key:"_setCombinationMatcher",value:function(e,t){this._actionConfigs[e]=t}},{key:"_getCombinationMatcher",value:function(e){return this._actionConfigs[e]}},{key:"_includesMatcherForCombination",value:function(e){return!!this._getCombinationMatcher(e)}}]),e}();function canBeMatched(e,t){var n=size(t.keyDictionary);return Configuration.option("allowCombinationSubmatches")||keyUpIsBeingHidden(e)?e.getNumberOfKeys()>=n:e.getNumberOfKeys()===n}function keyUpIsBeingHidden(e){return!!e.isKeyStillPressed("Meta")&&e.some(function(e){return keyupIsHiddenByCmd(e)})}var KeyHistoryMatcher=function(){function e(){_classCallCheck(this,e),this._combinationMatchers={},this._eventRecord=KeyEventStateArrayManager.newRecord()}return _createClass(e,[{key:"addMatch",value:function(e,t){this._getOrCreateCombinationMatcher(e.prefix).addMatch(e,t),KeyEventStateArrayManager.setBit(this._eventRecord,e.keyEventType,KeyEventState.seen),(!this._longestSequence||this._longestSequence<e.sequenceLength)&&(this._longestSequence=e.sequenceLength)}},{key:"findMatch",value:function(e,t,n){var i=this._findCombinationMatcher(e);return i?i.findMatch(e.getCurrentCombination(),e.getCurrentCombination().getNormalizedKeyName(t),n):null}},{key:"hasMatchesForEventType",value:function(e){return!!this._eventRecord[e]}},{key:"getLongestSequence",value:function(){return this._longestSequence}},{key:"toJSON",value:function(){var i=this;return Object.keys(this._combinationMatchers).reduce(function(e,t){var n=i._combinationMatchers[t];return e[t]=n.toJSON(),e},{})}},{key:"_getOrCreateCombinationMatcher",value:function(e){return this._combinationMatchers[e]||(this._combinationMatchers[e]=new KeyCombinationMatcher),this._combinationMatchers[e]}},{key:"_findCombinationMatcher",value:function(e){var t=e.getMostRecentCombinations(this.getLongestSequence());if(0===t.length)return this._combinationMatchers[""];for(var n=t.map(function(e){return e.getIds()}),i=n.map(function(e){return e.length}),o=new Array(n.length).fill(0),r=!1;!r;){var s=o.map(function(e,t){return n[t][e]}).join(" ");if(this._combinationMatchers[s])return this._combinationMatchers[s];for(var a=0,u=!0;u&&a<o.length;){var l=(indexFromEnd(o,a)+1)%(indexFromEnd(i,a)||1);(u=0===(o[o.length-(a+1)]=l))&&a++}r=a===o.length}}}]),e}(),ActionResolver=function(){function i(e){_classCallCheck(this,i),this._keyMapMatchers=[],this._unmatchedHandlerStatus=[],this._handlersDictionary={},this._keySequencesDictionary={};for(var t=e.getNewIterator();t.next();){var n=t.getComponent().handlers;this._unmatchedHandlerStatus.push([Object.keys(n).length,{}]),this._keyMapMatchers.push(new KeyHistoryMatcher)}this._componentList=e,this._componentListIterator=e.getNewIterator()}return _createClass(i,[{key:"getKeyHistoryMatcher",value:function(e){if(this._componentHasUnmatchedHandlers(e))for(;this._componentListIterator.next();)this._addHandlersFromComponent(),this._addActionsFromComponent();return this._getKeyHistoryMatcher(e)}},{key:"componentHasActionsBoundToEventType",value:function(e,t){return this.getKeyHistoryMatcher(e).hasMatchesForEventType(t)}},{key:"findMatchingKeySequenceInComponent",value:function(e,t,n,i){return this.componentHasActionsBoundToEventType(e,i)?this.getKeyHistoryMatcher(e).findMatch(t,n,i):null}},{key:"_getKeyHistoryMatcher",value:function(e){return this._keyMapMatchers[e]}},{key:"_addActionsFromComponent",value:function(){var s=this,t=this._componentListIterator.getComponent().actions;Object.keys(t).forEach(function(n){var e=s._getHandlers(n);if(e){var i=e[0],o=s._componentList.getAtPosition(i).handlers[n],r=s._getKeyHistoryMatcher(i);t[n].forEach(function(e){var t=[e.prefix,e.id].join(" ");s._isClosestHandlerFound(t,e)||(r.addMatch(e,o),s._addKeySequence(t,[i,e.keyEventType]))}),e.forEach(function(e){var t=s._getUnmatchedHandlerStatus(e);t[1][n]||(t[1][n]=!0,t[0]--)})}})}},{key:"_getHandlers",value:function(e){return this._handlersDictionary[e]}},{key:"_addHandlersFromComponent",value:function(){var t=this,e=this._componentListIterator.getComponent().handlers;Object.keys(e).forEach(function(e){t._addHandler(e)})}},{key:"_addHandler",value:function(e){this._handlersDictionary[e]||(this._handlersDictionary[e]=[]),this._handlersDictionary[e].push(this._componentListIterator.getPosition())}},{key:"_addKeySequence",value:function(e,t){this._keySequencesDictionary[e]||(this._keySequencesDictionary[e]=[]),this._keySequencesDictionary[e].push(t)}},{key:"_componentHasUnmatchedHandlers",value:function(e){return 0<this._getUnmatchedHandlerStatus(e)[0]}},{key:"_getUnmatchedHandlerStatus",value:function(e){return this._unmatchedHandlerStatus[e]}},{key:"_isClosestHandlerFound",value:function(e,t){return this._keySequencesDictionary[e]&&this._keySequencesDictionary[e].some(function(e){return e[1]===t.keyEventType})}}]),i}();function copyAttributes(t,n,e){return e.forEach(function(e){hasKey(t,e)&&(n[e]=t[e])}),n}function describeKeyEventType(e){switch(parseInt(e,10)){case 0:return"keydown";case 1:return"keypress";default:return"keyup"}}function hasKeyPressEvent(e){return!isNonPrintableKeyName(e)}function stateFromEvent(e){return e.simulated?KeyEventState.simulated:KeyEventState.seen}var SEQUENCE_ATTRIBUTES=["sequence","action"],KEYMAP_ATTRIBUTES=["name","description","group"],AbstractKeyEventStrategy=function(){function n(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},t=1<arguments.length?arguments[1]:void 0;_classCallCheck(this,n),this.logger=e.logger||new Logger("warn"),this.componentId=-1,this.keyEventManager=t,this._componentTree=new ComponentTree,this.rootComponentId=null,this._reset(),this.resetKeyHistory()}return _createClass(n,[{key:"_reset",value:function(){this.componentList=new ComponentOptionsList,this._initHandlerResolutionState()}},{key:"_newKeyHistory",value:function(){return new KeyHistory({maxLength:this.componentList.getLongestSequence()})}},{key:"getKeyHistory",value:function(){return this._keyHistory||(this._keyHistory=this._newKeyHistory()),this._keyHistory}},{key:"_initHandlerResolutionState",value:function(){this._actionResolver=null}},{key:"resetKeyHistory",value:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};this.keypressEventsToSimulate=[],this.keyupEventsToSimulate=[],this.getKeyHistory().any()&&!e.force?this._keyHistory=new KeyHistory({maxLength:this.componentList.getLongestSequence()},new KeyCombination(this.getCurrentCombination().keysStillPressedDict())):this._keyHistory=this._newKeyHistory()}},{key:"getApplicationKeyMap",value:function(){return null===this.rootComponentId?{}:this._buildApplicationKeyMap([this.rootComponentId],{})}},{key:"_buildApplicationKeyMap",value:function(e,o){var r=this;return e.forEach(function(e){var t=r._componentTree.get(e),n=t.childIds,i=t.keyMap;i&&Object.keys(i).forEach(function(e){var t=i[e];o[e]={},isObject(t)?hasKey(t,"sequences")?(copyAttributes(t,o[e],KEYMAP_ATTRIBUTES),o[e].sequences=r._createSequenceFromConfig(t.sequences)):(copyAttributes(t,o[e],KEYMAP_ATTRIBUTES),o[e].sequences=[copyAttributes(t,{},SEQUENCE_ATTRIBUTES)]):o[e].sequences=r._createSequenceFromConfig(t)}),r._buildApplicationKeyMap(n,o)}),o}},{key:"_createSequenceFromConfig",value:function(e){return arrayFrom(e).map(function(e){return isObject(e)?copyAttributes(e,{},SEQUENCE_ATTRIBUTES):{sequence:e}})}},{key:"registerKeyMap",value:function(e){return this.componentId+=1,this._componentTree.add(this.componentId,e),this.componentId}},{key:"reregisterKeyMap",value:function(e,t){this._componentTree.update(e,t)}},{key:"registerComponentMount",value:function(e,t){isUndefined(t)?this.rootComponentId=e:this._componentTree.setParent(e,t)}},{key:"deregisterKeyMap",value:function(e){this._componentTree.remove(e),e===this.rootComponentId&&(this.rootComponentId=null)}},{key:"_addComponent",value:function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},i=3<arguments.length?arguments[3]:void 0;this.componentList.add(e,t,n,i),this.getKeyHistory().setMaxLength(this.componentList.getLongestSequence())}},{key:"_allKeysAreReleased",value:function(){return this.getCurrentCombination().hasEnded()}},{key:"getCurrentCombination",value:function(){return this.getKeyHistory().getCurrentCombination()}},{key:"_shouldSimulate",value:function(e,t){var n=hasKeyPressEvent(t),i=this.getCurrentCombination();return e===KeyEventType.keypress?!n||n&&i.isKeyStillPressed("Meta"):e===KeyEventType.keyup&&(keyupIsHiddenByCmd(t)&&i.isKeyReleased("Meta"))}},{key:"_cloneAndMergeEvent",value:function(n,e){return _objectSpread({},Object.keys(ModifierFlagsDictionary).reduce(function(e,t){return e[t]=n[t],e},{}),e)}},{key:"_callClosestMatchingHandler",value:function(e,t,n,i,o){for(this._actionResolver||(this._actionResolver=new ActionResolver(this.componentList));o<=i;){this._actionResolver.getKeyHistoryMatcher(o);var r=this._actionResolver.findMatchingKeySequenceInComponent(o,this.getKeyHistory(),t,n);this.getCurrentCombination();if(r){var s=r.events[n];if(Configuration.option("allowCombinationSubmatches"))KeyCombinationSerializer.serialize(r.keyDictionary);return s.handler(e),this._stopEventPropagationAfterHandlingIfEnabled(e,o),!0}this._actionResolver.componentHasActionsBoundToEventType(o,n),o++}}},{key:"_stopEventPropagationAfterHandlingIfEnabled",value:function(e,t){return!!Configuration.option("stopEventPropagationAfterHandling")&&(this._stopEventPropagation(e,t),!0)}},{key:"_stopEventPropagation",value:function(e,t){throw new Error("_stopEventPropagation must be overridden by a subclass")}},{key:"_checkForModifierFlagDiscrepancies",value:function(o,e,r){var s=this;Object.keys(ModifierFlagsDictionary).forEach(function(t){if(e!==t||r!==KeyEventType.keyup){var n=s.getCurrentCombination(),i=n.isKeyStillPressed(t);ModifierFlagsDictionary[t].forEach(function(e){!1===o[e]&&i&&n.setKeyState(t,KeyEventType.keyup,stateFromEvent(o))})}})}},{key:"_logPrefix",value:function(){}}]),n}(),KeyEventCounter=function(){function e(){_classCallCheck(this,e)}return _createClass(e,null,[{key:"getId",value:function(){return isUndefined(this._id)&&(this._id=0),this._id}},{key:"incrementId",value:function(){this._id=this.getId()+1}}]),e}();function getEventCharCode(e){var t,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,10===t&&(t=13),32<=t||13===t?t:0}var normalizeKey={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"};function reactsGetEventKey(e){if(e.key){var t=normalizeKey[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"!==e.type)return"keydown"===e.type||"keyup"===e.type?translateToKey[e.keyCode]||"Unidentified":"";var n=getEventCharCode(e);return 13===n?"Enter":String.fromCharCode(n)}function getKeyName(e){var t,n,i=(t=Configuration.option("customKeyCodes"),n=e.keyCode||e.charCode,hasKey(t,n)?t[n]:e.nativeEvent?e.key:reactsGetEventKey(e));return"+"===i?"plus":i}function isCmdKey(e){return"Meta"===e}var EventResponse={unseen:0,ignored:1,seen:2,recorded:3,handled:4},EventPropagator=function(){function o(e,t){var n=t.logger,i=t.logPrefix;_classCallCheck(this,o),this._componentList=e,this._previousPropagation=null,this.logger=n,this._logPrefix=i,this._reset()}return _createClass(o,[{key:"_reset",value:function(){this._previousPosition=-1,this._position=-1,this._actionHandled=!1,this._ignoreEvent=!1,this._observeIgnoredEvents=!1,this._stopping=!1,this._componentId=null,this._key=null,this._type=null}},{key:"isFirstPropagationStep",value:function(){var e=this.getPreviousPosition();return-1===e||e>=this._position}},{key:"isForKey",value:function(e){return this._key===e}},{key:"isForEventType",value:function(e){return this._type===e}},{key:"startNewPropagationStep",value:function(e,t,n,i){return this._position=this._componentList.getIndexById(e),this._componentId=e,this.isFirstPropagationStep()&&(KeyEventCounter.incrementId(),this._key=t.key,this._type=i),!t.repeat||!Configuration.option("ignoreRepeatedEventsWhenKeyHeldDown")||(this.ignoreEvent(t),!1)}},{key:"finishPropagationStep",value:function(){this.isStopped()||this._componentList.isRoot(this._componentId)?(this._previousPropagation=this._clone(),this._reset()):this._previousPosition=this._position}},{key:"getPreviousPropagation",value:function(){return this._previousPropagation||(this._previousPropagation=this._clone({copyState:!1})),this._previousPropagation}},{key:"getPreviousPosition",value:function(){return this._previousPosition}},{key:"observeIgnoredEvents",value:function(){this._observeIgnoredEvents=!0}},{key:"ignoreEvent",value:function(e){return this.setIgnoreEvent(!0),!(!this.isIgnoringEvent()||!Configuration.option("stopEventPropagationAfterIgnoring"))&&(this.stop(e),this.finishPropagationStep(),!0)}},{key:"setIgnoreEvent",value:function(e){this._ignoreEvent=e}},{key:"isIgnoringEvent",value:function(){return!this._observeIgnoredEvents&&this._ignoreEvent}},{key:"isStopped",value:function(){return this._stopping}},{key:"stop",value:function(e){return!this.isStopped()&&(this._stopping=!0,e.simulated||e.stopPropagation(),!0)}},{key:"isPendingPropagation",value:function(){var e=this.getPreviousPosition();return-1!==e&&e+1<this._position}},{key:"isHandled",value:function(){return this._actionHandled}},{key:"setHandled",value:function(){this._actionHandled=!0}},{key:"_clone",value:function(){var e=(0<arguments.length&&void 0!==arguments[0]?arguments[0]:{}).copyState,t=void 0===e||e,n=new o(this._componentList,{logger:this.logger,logPrefix:this._logPrefix});return t&&Object.assign(n,this),n}}]),o}(),FocusOnlyKeyEventStrategy=function(e){function i(){var e,t=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{},n=1<arguments.length?arguments[1]:void 0;return _classCallCheck(this,i),(e=_possibleConstructorReturn(this,_getPrototypeOf(i).call(this,t,n))).focusTreeId=0,e}return _inherits(i,AbstractKeyEventStrategy),_createClass(i,[{key:"_reset",value:function(){_get(_getPrototypeOf(i.prototype),"_reset",this).call(this),this.keypressEventsToSimulate=[],this.focusTreeId+=1,this.eventPropagator=new EventPropagator(this.componentList,{logger:this.logger,logPrefix:this._logPrefix.bind(this)})}},{key:"enableHotKeys",value:function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},i=3<arguments.length?arguments[3]:void 0;if(this.resetOnNextFocus&&(this._reset(),this.resetOnNextFocus=!1),!this.componentList.containsId(e))return this._addComponent(e,t,n,i),this.focusTreeId}},{key:"updateEnabledHotKeys",value:function(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{},i=3<arguments.length&&void 0!==arguments[3]?arguments[3]:{},o=4<arguments.length?arguments[4]:void 0;e===this.focusTreeId&&this.componentList.containsId(t)&&(this.componentList.update(t,n,i,o),this.getKeyHistory().setMaxLength(this.componentList.getLongestSequence()),this._initHandlerResolutionState())}},{key:"disableHotKeys",value:function(e,t){return this.resetOnNextFocus||(this.resetOnNextFocus=!0),this.eventPropagator.isPendingPropagation()}},{key:"handleKeydown",value:function(e,t,n){var i=3<arguments.length&&void 0!==arguments[3]?arguments[3]:{},o=getKeyName(e);if(t!==this.focusTreeId)return this.eventPropagator.ignoreEvent(e),!0;if(this.eventPropagator.startNewPropagationStep(n,e,o,KeyEventType.keydown)){if(this._howToHandleKeyEvent(e,t,n,o,i,KeyEventType.keydown)===EventResponse.handled){var r=stateFromEvent(e),s=this.getCurrentCombination();s.isKeyIncluded(o)||s.isEnding()?this._startAndLogNewKeyCombination(o,t,n,r):this._addToAndLogCurrentKeyCombination(o,KeyEventType.keydown,t,n,r),this._callHandlerIfActionNotHandled(e,o,KeyEventType.keydown,n,t)}return this._simulateKeyPressForNonPrintableKeys(e,o,t,n,i),this.eventPropagator.finishPropagationStep(),!1}}},{key:"_howToHandleKeyEvent",value:function(e,t,n,i,o,r){if(this.eventPropagator.isFirstPropagationStep()){if(o.ignoreEventsCondition(e)&&this.eventPropagator.ignoreEvent(e))return this._eventIsToBeIgnored(e,n,i,r);this._checkForModifierFlagDiscrepancies(e,i,r)}else if(this.eventPropagator.isIgnoringEvent())return this._eventIsToBeIgnored(e,n,i,r);return EventResponse.handled}},{key:"_eventIsToBeIgnored",value:function(e,t,n,i){return EventResponse.ignored}},{key:"handleKeyPress",value:function(e,t,n,i){var o=getKeyName(e),r=this.getCurrentCombination();if(r.isKeyPressSimulated(o))return this.eventPropagator.ignoreEvent(e),!0;if(this.eventPropagator.startNewPropagationStep(n,e,o,KeyEventType.keypress)){var s=t!==this.focusTreeId,a=this._howToHandleKeyEvent(e,t,n,o,i,KeyEventType.keypress);return this.eventPropagator.isFirstPropagationStep(n)&&r.isKeyIncluded(o)&&this._addToAndLogCurrentKeyCombination(o,KeyEventType.keypress,t,n,stateFromEvent(e)),a===EventResponse.handled&&this._callHandlerIfActionNotHandled(e,o,KeyEventType.keypress,n,t),this.eventPropagator.finishPropagationStep(),s}}},{key:"handleKeyUp",value:function(e,t,n,i){var o=getKeyName(e),r=this.getCurrentCombination();if(r.isKeyUpSimulated(o))return this.eventPropagator.ignoreEvent(e),!0;if(this.eventPropagator.startNewPropagationStep(n,e,o,KeyEventType.keyup)){var s=t!==this.focusTreeId,a=this._howToHandleKeyEvent(e,t,n,o,i,KeyEventType.keyup);return this.eventPropagator.isFirstPropagationStep(n)&&r.isKeyIncluded(o)&&this._addToAndLogCurrentKeyCombination(o,KeyEventType.keyup,t,n,stateFromEvent(e)),a===EventResponse.handled&&this._callHandlerIfActionNotHandled(e,o,KeyEventType.keyup,n,t),this._simulateKeyUpEventsHiddenByCmd(e,o,t,n,i),this.eventPropagator.finishPropagationStep(),s}}},{key:"closeHangingKeyCombination",value:function(e,t){var n=this.getCurrentCombination();n.isKeyIncluded(e)&&!n.isEventTriggered(e,t)&&n.setKeyState(e,t,KeyEventState.simulated)}},{key:"_simulateKeyPressForNonPrintableKeys",value:function(e,t,n,i,o){this._handleEventSimulation("keypressEventsToSimulate","simulatePendingKeyPressEvents",this._shouldSimulate(KeyEventType.keypress,t),{event:e,key:t,focusTreeId:n,componentId:i,options:o})}},{key:"_simulateKeyUpEventsHiddenByCmd",value:function(t,e,n,i,o){var r=this;isCmdKey(e)&&this.getCurrentCombination().forEachKey(function(e){isCmdKey(e)||r._handleEventSimulation("keyupEventsToSimulate","simulatePendingKeyUpEvents",r._shouldSimulate(KeyEventType.keyup,e),{event:t,key:e,focusTreeId:n,componentId:i,options:o})})}},{key:"_stopEventPropagation",value:function(e,t){this.eventPropagator.stop(e)}},{key:"getEventPropagator",value:function(){return this.eventPropagator}},{key:"_startAndLogNewKeyCombination",value:function(e,t,n,i){this.getKeyHistory().startNewKeyCombination(e,i)}},{key:"_addToAndLogCurrentKeyCombination",value:function(e,t,n,i,o){this.getKeyHistory().addKeyToCurrentCombination(e,t,o)}},{key:"_handleEventSimulation",value:function(e,t,n,i){var o=i.event,r=i.key,s=i.focusTreeId,a=i.componentId,u=i.options;if(n&&Configuration.option("simulateMissingKeyPressEvents")){var l=this._cloneAndMergeEvent(o,{key:r,simulated:!0});this[e].push({event:l,focusTreeId:s,componentId:a,options:u})}(this.componentList.isRoot(a)||this.eventPropagator.isStopped())&&(this.keyEventManager.isGlobalListenersBound()||this[t]())}},{key:"simulatePendingKeyPressEvents",value:function(){this._simulatePendingKeyEvents("keypressEventsToSimulate","handleKeyPress")}},{key:"simulatePendingKeyUpEvents",value:function(){this._simulatePendingKeyEvents("keyupEventsToSimulate","handleKeyUp")}},{key:"_simulatePendingKeyEvents",value:function(e,r){var s=this;0<this[e].length&&KeyEventCounter.incrementId(),this[e].forEach(function(e){var t=e.event,n=e.focusTreeId,i=e.componentId,o=e.options;s[r](t,n,i,o)}),this[e]=[]}},{key:"_callHandlerIfActionNotHandled",value:function(e,t,n,i,o){this.getCurrentCombination().describe();if(this.componentList.anyActionsForEventType(n))if(this.eventPropagator.isHandled());else{var r=this.eventPropagator.getPreviousPosition(),s=this.componentList.getIndexById(i);this._callClosestMatchingHandler(e,t,n,s,-1===r?0:r)&&this.eventPropagator.setHandled()}}},{key:"_logPrefix",value:function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},n=Logger.logIcons,i=Logger.eventIcons,o=Logger.componentIcons,r="HotKeys (";if(!1!==t.focusTreeId){var s=isUndefined(t.focusTreeId)?this.focusTreeId:t.focusTreeId;r+="F".concat(s).concat(n[s%n.length],"-")}if(!1!==t.eventId){var a=isUndefined(t.eventId)?KeyEventCounter.getId():t.eventId;r+="E".concat(a).concat(i[a%i.length],"-")}r+="C".concat(e).concat(o[e%o.length]);var u=this.componentList.getIndexById(e);return isUndefined(u)||(r+="-P".concat(u).concat(o[u%o.length],":")),"".concat(r,")")}}]),i}();function contains(e,t){var n=2<arguments.length&&void 0!==arguments[2