Socket
Socket
Sign inDemoInstall

react-hotkeys

Package Overview
Dependencies
44
Maintainers
2
Versions
38
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

Comparing version 1.1.4 to 2.0.0-pre1

cjs/configure.js

471

cjs/HotKeys.js

@@ -11,6 +11,2 @@ 'use strict';

var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _react = require('react');

@@ -20,30 +16,10 @@

var _reactDom = require('react-dom');
var _Configuration = require('./lib/Configuration');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _Configuration2 = _interopRequireDefault(_Configuration);
var _FocusTrap = require('./FocusTrap');
var _withHotKeys = require('./withHotKeys');
var _FocusTrap2 = _interopRequireDefault(_FocusTrap);
var _withHotKeys2 = _interopRequireDefault(_withHotKeys);
var _lodash = require('lodash.isboolean');
var _lodash2 = _interopRequireDefault(_lodash);
var _lodash3 = require('lodash.isobject');
var _lodash4 = _interopRequireDefault(_lodash3);
var _lodash5 = require('lodash.isequal');
var _lodash6 = _interopRequireDefault(_lodash5);
var _sequencesFromKeyMap = require('./utils/sequencesFromKeyMap');
var _sequencesFromKeyMap2 = _interopRequireDefault(_sequencesFromKeyMap);
var _hasChanged = require('./utils/hasChanged');
var _hasChanged2 = _interopRequireDefault(_hasChanged);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -60,442 +36,29 @@

/**
* A string or list of strings, that represent a sequence of one or more keys
* @typedef {String | Array.<String>} MouseTrapKeySequence
* @see {@link https://craig.is/killing/mice} for support key sequences
* @see HotKeysEnabled
*/
var HotKeysWrapper = function (_Component) {
_inherits(HotKeysWrapper, _Component);
/**
* Name of a key event
* @typedef {'keyup'|'keydown'|'keypress'} KeyEventName
*/
function HotKeysWrapper() {
_classCallCheck(this, HotKeysWrapper);
/**
* Options for the mapping of a key sequence and event
* @typedef {Object} KeyEventOptions
* @property {MouseTrapKeySequence} The key sequence required to satisfy a KeyEventMatcher
* @property {KeyEventName} action The keyboard state required to satisfy a KeyEventMatcher
*/
/**
* A matcher used on keyboard sequences and events to trigger handler functions
* when matching sequences occur
* @typedef {MouseTrapKeySequence | KeyMapOptions | Array<MouseTrapKeySequence>} KeyEventMatcher
*/
/**
* A unique key to associate with KeyEventMatchers that allows associating handler
* functions at a later stage
* @typedef {String} ActionName
*/
/**
* A mapping from ActionNames to KeyEventMatchers
* @typedef {Object.<String, KeyEventMatcher>} KeySequence
*/
/**
* Component that wraps it children in a "focus trap" and allows key events to
* trigger function handlers when its children are in focus
*/
var HotKeys = function (_Component) {
_inherits(HotKeys, _Component);
function HotKeys(props, context) {
_classCallCheck(this, HotKeys);
/**
* The focus and blur handlers need access to the current component as 'this'
* so they need to be bound to it when the component is instantiated
*/
var _this = _possibleConstructorReturn(this, (HotKeys.__proto__ || Object.getPrototypeOf(HotKeys)).call(this, props, context));
_this.onFocus = _this.onFocus.bind(_this);
_this.onBlur = _this.onBlur.bind(_this);
return _this;
return _possibleConstructorReturn(this, (HotKeysWrapper.__proto__ || Object.getPrototypeOf(HotKeysWrapper)).apply(this, arguments));
}
/**
* Constructs the context object that contains references to this component
* and its KeyMap so that they may be accessed by any descendant HotKeys
* components
* @returns {{hotKeyParent: HotKeys, hotKeyMap: KeySequence}} Child context object
*/
_createClass(HotKeys, [{
key: 'getChildContext',
value: function getChildContext() {
return {
hotKeyParent: this,
hotKeyMap: this.__hotKeyMap__
};
}
/**
* Sets this components KeyMap from its keyMap prop and the KeyMap of its
* ancestor KeyMap component (if one exists)
*/
}, {
key: 'componentWillMount',
value: function componentWillMount() {
this.updateMap();
}
/**
* Updates this component's KeyMap if either its own keyMap prop has changed
* or its ancestor's KeyMap has been update
*
* @returns {boolean} Whether the KeyMap was updated
*/
}, {
key: 'updateMap',
value: function updateMap() {
var newMap = this.buildMap();
if (!(0, _lodash6.default)(newMap, this.__hotKeyMap__)) {
this.__hotKeyMap__ = newMap;
return true;
}
return false;
}
/**
* This component's KeyMap merged with that of its most direct ancestor that is a
* HotKeys component. This component's mappings take precedence over those defined
* in its ancestor.
* @returns {KeySequence} This component's KeyMap merged with its HotKeys ancestor's
*/
}, {
key: 'buildMap',
value: function buildMap() {
var parentMap = this.context.hotKeyMap || {};
var thisMap = this.props.keyMap || {};
/**
* TODO: This appears to only merge in the key maps of its most direct
* ancestor - what about grandparent components' KeyMap's?
*/
return _extends({}, parentMap, thisMap);
}
/**
* This component's KeyMap
* @returns {KeySequence} This component's KeyMap
*/
}, {
key: 'getMap',
value: function getMap() {
return this.__hotKeyMap__;
}
/**
* Imports mousetrap and stores a reference to it on the this component
*/
}, {
key: 'componentDidMount',
value: function componentDidMount() {
// import is here to support React's server rendering as Mousetrap immediately
// calls itself with window and it fails in Node environment
var Mousetrap = require('mousetrap');
/**
* TODO: Not optimal - imagine hundreds of this component. We need a top level
* delegation point for mousetrap
*/
this.__mousetrap__ = new Mousetrap(this.props.attach || _reactDom2.default.findDOMNode(this));
this.updateHotKeys(true);
}
/**
* Updates this component's KeyMap and synchronises the handlers across to
* Mousetrap after the component has been updated (passed new prop values)
* @param {Object} prevProps The props used on the component's last render
*/
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
this.updateHotKeys(false, prevProps);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(null);
}
if (this.__mousetrap__) {
this.__mousetrap__.reset();
}
}
/**
* Updates this component's KeyMap and synchronises the changes across
* to Mouestrap
* @param {Boolean} force Whether to force an update of the KeyMap and sync
* to Mousetrap, even if no relevant values appear to have changed
* since the last time
* @param {Object} prevProps The props used on the component's last render
*/
}, {
key: 'updateHotKeys',
value: function updateHotKeys() {
var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var prevProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _props$handlers = this.props.handlers,
handlers = _props$handlers === undefined ? {} : _props$handlers;
var _prevProps$handlers = prevProps.handlers,
prevHandlers = _prevProps$handlers === undefined ? handlers : _prevProps$handlers;
var keyMapHasChanged = this.updateMap();
if (force || keyMapHasChanged || (0, _hasChanged2.default)(handlers, prevHandlers)) {
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(null);
}
this.syncHandlersToMousetrap();
}
}
/**
* Synchronises the KeyMap and handlers applied to this component over to
* Mousetrap
*/
}, {
key: 'syncHandlersToMousetrap',
value: function syncHandlersToMousetrap() {
var _this2 = this;
var _props$handlers2 = this.props.handlers,
handlers = _props$handlers2 === undefined ? {} : _props$handlers2;
var hotKeyMap = this.getMap();
var sequenceHandlers = [];
var mousetrap = this.__mousetrap__;
// Group all our handlers by sequence
Object.keys(handlers).forEach(function (hotKey) {
var handler = handlers[hotKey];
var sequencesAsArray = (0, _sequencesFromKeyMap2.default)(hotKeyMap, hotKey);
/**
* TODO: Could be optimized as every handler will get called across every bound
* component - imagine making a node a focus point and then having hundreds!
*/
sequencesAsArray.forEach(function (sequence) {
var action = void 0;
var callback = function callback(event, sequence) {
/**
* Check we are actually in focus and that a child hasn't already
* handled this sequence
*/
var isFocused = (0, _lodash2.default)(_this2.props.focused) ? _this2.props.focused : _this2.__isFocused__;
if (isFocused && sequence !== _this2.__lastChildSequence__) {
if (_this2.context.hotKeyParent) {
_this2.context.hotKeyParent.childHandledSequence(sequence);
}
return handler(event, sequence);
}
};
if ((0, _lodash4.default)(sequence)) {
action = sequence.action;
sequence = sequence.sequence;
}
sequenceHandlers.push({ callback: callback, action: action, sequence: sequence });
});
});
/**
* TODO: Hard reset our handlers (probably could be more efficient)
*/
mousetrap.reset();
sequenceHandlers.forEach(function (_ref) {
var sequence = _ref.sequence,
callback = _ref.callback,
action = _ref.action;
return mousetrap.bind(sequence, callback, action);
});
}
/**
* Stores a reference to the last key sequence handled by the most direct
* descendant HotKeys component, and passes that sequence to its own most
* direct HotKeys ancestor for it to do the same.
*
* This reference is stored so that parent HotKeys components do not try
* to handle a sequence that has already been handled by one of its
* descendants.
*
* @param {KeyEventMatcher} sequence The sequence handled most recently by
* a child HotKeys component
*/
}, {
key: 'childHandledSequence',
value: function childHandledSequence() {
var sequence = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
this.__lastChildSequence__ = sequence;
/**
* Traverse up any hot key parents so everyone is aware a child has
* handled a certain sequence
*/
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(sequence);
}
}
/**
* Renders the component's children wrapped in a FocusTrap with the necessary
* props to capture keyboard events
*
* @returns {FocusTrap} FocusTrap with necessary props to capture keyboard events
*/
}, {
_createClass(HotKeysWrapper, [{
key: 'render',
value: function render() {
var _props = this.props,
keyMap = _props.keyMap,
handlers = _props.handlers,
focused = _props.focused,
attach = _props.attach,
children = _props.children,
props = _objectWithoutProperties(_props, ['keyMap', 'handlers', 'focused', 'attach', 'children']);
hotKeys = _props.hotKeys,
remainingProps = _objectWithoutProperties(_props, ['hotKeys']);
return _react2.default.createElement(
_FocusTrap2.default,
_extends({}, props, { onFocus: this.onFocus, onBlur: this.onBlur }),
children
);
}
var DefaultComponent = remainingProps.component || _Configuration2.default.option('defaultComponent');
/**
* Updates the internal focused state and calls the onFocus prop if it is
* defined
*/
}, {
key: 'onFocus',
value: function onFocus() {
this.__isFocused__ = true;
if (this.props.onFocus) {
var _props2;
(_props2 = this.props).onFocus.apply(_props2, arguments);
}
return _react2.default.createElement(DefaultComponent, _extends({}, hotKeys, remainingProps));
}
/**
* Updates the internal focused state and calls the onBlur prop if it is
* defined.
*
* Also registers a null sequence as being handled by this component with
* its ancestor HotKeys.
*/
}, {
key: 'onBlur',
value: function onBlur() {
this.__isFocused__ = false;
if (this.props.onBlur) {
var _props3;
(_props3 = this.props).onBlur.apply(_props3, arguments);
}
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(null);
}
}
}]);
return HotKeys;
return HotKeysWrapper;
}(_react.Component);
HotKeys.propTypes = {
/**
* A map from action names to Mousetrap key sequences
*/
keyMap: _propTypes2.default.object,
/**
* A map from action names to event handler functions
*/
handlers: _propTypes2.default.object,
/**
* Whether HotKeys should behave as if it has focus in the browser,
* whether it does or not - a way to force focus behaviour
*/
focused: _propTypes2.default.bool,
/**
* The DOM element the keyboard listeners should be attached to
*/
attach: _propTypes2.default.any,
/**
* Children to wrap within a focus trap
*/
children: _propTypes2.default.node,
/**
* Function to call when this component gains focus in the browser
*/
onFocus: _propTypes2.default.func,
/**
* Function to call when this component loses focus in the browser
*/
onBlur: _propTypes2.default.func
};
HotKeys.childContextTypes = {
/**
* Reference to this instance of HotKeys so that any descendents are aware
* that they are being rendered within another HotKeys component
*/
hotKeyParent: _propTypes2.default.any,
/**
* Reference to this instance's KeyMap so that any descendents may merge it
* into its own
*/
hotKeyMap: _propTypes2.default.object
};
HotKeys.contextTypes = {
/**
* Reference to the most direct ancestor that is a HotKeys component (if one
* exists) so that messages may be passed to it when necessary
*/
hotKeyParent: _propTypes2.default.any,
/**
* Reference to the KeyMap of its most direct HotKeys ancestor, so that it may
* be merged into this components
*/
hotKeyMap: _propTypes2.default.object
};
exports.default = HotKeys;
exports.default = (0, _withHotKeys2.default)(HotKeysWrapper);

@@ -16,29 +16,47 @@ 'use strict';

var _withHotKeys = require('./withHotKeys');
var _HotKeysIgnore = require('./HotKeysIgnore');
Object.defineProperty(exports, 'withHotKeys', {
Object.defineProperty(exports, 'HotKeysIgnore', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_withHotKeys).default;
return _interopRequireDefault(_HotKeysIgnore).default;
}
});
var _FocusTrap = require('./FocusTrap');
var _withHotKeysIgnore = require('./withHotKeysIgnore');
Object.defineProperty(exports, 'FocusTrap', {
Object.defineProperty(exports, 'withHotKeysIgnore', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_FocusTrap).default;
return _interopRequireDefault(_withHotKeysIgnore).default;
}
});
var _HotKeyMapMixin = require('./HotKeyMapMixin');
var _GlobalHotKeys = require('./GlobalHotKeys');
Object.defineProperty(exports, 'HotKeyMapMixin', {
Object.defineProperty(exports, 'GlobalHotKeys', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_HotKeyMapMixin).default;
return _interopRequireDefault(_GlobalHotKeys).default;
}
});
var _withHotKeys = require('./withHotKeys');
Object.defineProperty(exports, 'withHotKeys', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_withHotKeys).default;
}
});
var _configure = require('./configure');
Object.defineProperty(exports, 'configure', {
enumerable: true,
get: function get() {
return _interopRequireDefault(_configure).default;
}
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -9,4 +9,6 @@ /**

* 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.
*
* PLEASE NOTE: SOURCE CODE FOUND IN THE lib/vendor DIRECTORY IS UNDER THE MIT LICENSE - PLEASE SEE THE LICENSE FILE FOR EACH DIRECTORY FOR MORE INFORMATION
*/
"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),isEqual=_interopDefault(require("lodash.isequal")),ReactDOM=_interopDefault(require("react-dom")),isBool=_interopDefault(require("lodash.isboolean")),isObject=_interopDefault(require("lodash.isobject")),classCallCheck=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},createClass=function(){function e(e,t){for(var o=0;o<t.length;o++){var n=t[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},inherits=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},objectWithoutProperties=function(e,t){var o={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(o[n]=e[n]);return o},possibleConstructorReturn=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},FocusTrap=function(e){function t(){return classCallCheck(this,t),possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return inherits(t,e),createClass(t,[{key:"render",value:function(){var e=this.props,t=e.component,o=e.children,n=objectWithoutProperties(e,["component","children"]);return React__default.createElement(t,_extends({tabIndex:"-1"},n),o)}}]),t}(React.Component);function sequencesFromKeyMap(e,t){var o=e[t];return o?Array.isArray(o)?o:[o]:[t]}function hasChanged(e,t){return!isEqual(e,t)}FocusTrap.propTypes={onFocus:PropTypes.func,onBlur:PropTypes.func,component:PropTypes.oneOfType([PropTypes.func,PropTypes.string]),children:PropTypes.node},FocusTrap.defaultProps={component:"div"};var HotKeys=function(e){function t(e,o){classCallCheck(this,t);var n=possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,o));return n.onFocus=n.onFocus.bind(n),n.onBlur=n.onBlur.bind(n),n}return inherits(t,e),createClass(t,[{key:"getChildContext",value:function(){return{hotKeyParent:this,hotKeyMap:this.__hotKeyMap__}}},{key:"componentWillMount",value:function(){this.updateMap()}},{key:"updateMap",value:function(){var e=this.buildMap();return!isEqual(e,this.__hotKeyMap__)&&(this.__hotKeyMap__=e,!0)}},{key:"buildMap",value:function(){var e=this.context.hotKeyMap||{},t=this.props.keyMap||{};return _extends({},e,t)}},{key:"getMap",value:function(){return this.__hotKeyMap__}},{key:"componentDidMount",value:function(){var e=require("mousetrap");this.__mousetrap__=new e(this.props.attach||ReactDOM.findDOMNode(this)),this.updateHotKeys(!0)}},{key:"componentDidUpdate",value:function(e){this.updateHotKeys(!1,e)}},{key:"componentWillUnmount",value:function(){this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(null),this.__mousetrap__&&this.__mousetrap__.reset()}},{key:"updateHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=this.props.handlers,n=void 0===o?{}:o,r=t.handlers,s=void 0===r?n:r,a=this.updateMap();(e||a||hasChanged(n,s))&&(this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(null),this.syncHandlersToMousetrap())}},{key:"syncHandlersToMousetrap",value:function(){var e=this,t=this.props.handlers,o=void 0===t?{}:t,n=this.getMap(),r=[],s=this.__mousetrap__;Object.keys(o).forEach(function(t){var s=o[t];sequencesFromKeyMap(n,t).forEach(function(t){var o=void 0;isObject(t)&&(o=t.action,t=t.sequence),r.push({callback:function(t,o){if((isBool(e.props.focused)?e.props.focused:e.__isFocused__)&&o!==e.__lastChildSequence__)return e.context.hotKeyParent&&e.context.hotKeyParent.childHandledSequence(o),s(t,o)},action:o,sequence:t})})}),s.reset(),r.forEach(function(e){var t=e.sequence,o=e.callback,n=e.action;return s.bind(t,o,n)})}},{key:"childHandledSequence",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;this.__lastChildSequence__=e,this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(e)}},{key:"render",value:function(){var e=this.props,t=(e.keyMap,e.handlers,e.focused,e.attach,e.children),o=objectWithoutProperties(e,["keyMap","handlers","focused","attach","children"]);return React__default.createElement(FocusTrap,_extends({},o,{onFocus:this.onFocus,onBlur:this.onBlur}),t)}},{key:"onFocus",value:function(){var e;(this.__isFocused__=!0,this.props.onFocus)&&(e=this.props).onFocus.apply(e,arguments)}},{key:"onBlur",value:function(){var e;(this.__isFocused__=!1,this.props.onBlur)&&(e=this.props).onBlur.apply(e,arguments);this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(null)}}]),t}(React.Component);HotKeys.propTypes={keyMap:PropTypes.object,handlers:PropTypes.object,focused:PropTypes.bool,attach:PropTypes.any,children:PropTypes.node,onFocus:PropTypes.func,onBlur:PropTypes.func},HotKeys.childContextTypes={hotKeyParent:PropTypes.any,hotKeyMap:PropTypes.object},HotKeys.contextTypes={hotKeyParent:PropTypes.any,hotKeyMap:PropTypes.object};var withHotKeys=function(e){return function(t){return function(o){function n(e){classCallCheck(this,n);var t=possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t._setRef=t._setRef.bind(t),t.state={handlers:{}},t}return inherits(n,o),createClass(n,[{key:"componentDidMount",value:function(){this.setState({handlers:this._ref.hotKeyHandlers})}},{key:"_setRef",value:function(e){this._ref=e}},{key:"render",value:function(){var o=this.state.handlers;return React__default.createElement(HotKeys,{component:"document-fragment",keyMap:e,handlers:o},React__default.createElement(t,_extends({ref:this._setRef},this.props)))}}]),n}(React.PureComponent)}};function HotKeyMapMixin(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{contextTypes:{hotKeyMap:PropTypes.object},childContextTypes:{hotKeyMap:PropTypes.object},getChildContext:function(){return{hotKeyMap:this.__hotKeyMap__}},componentWillMount:function(){this.updateMap()},updateMap:function(){var e=this.buildMap();return!isEqual(e,this.__hotKeyMap__)&&(this.__hotKeyMap__=e,!0)},buildMap:function(){var t=this.context.hotKeyMap||{},o=this.props.keyMap||{};return _extends({},t,e,o)},getMap:function(){return this.__hotKeyMap__}}}exports.HotKeys=HotKeys,exports.withHotKeys=withHotKeys,exports.FocusTrap=FocusTrap,exports.HotKeyMapMixin=HotKeyMapMixin;
"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 dictionaryFrom(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return e.reduce(function(e,n){return e[n]=t||{value:n},e},{})}var _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},classCallCheck=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},createClass=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),defineProperty=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},get=function e(t,n,o){null===t&&(t=Function.prototype);var i=Object.getOwnPropertyDescriptor(t,n);if(void 0===i){var r=Object.getPrototypeOf(t);return null===r?void 0:e(r,n,o)}if("value"in i)return i.value;var a=i.get;return void 0!==a?a.call(o):void 0},inherits=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},objectWithoutProperties=function(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n},possibleConstructorReturn=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},slicedToArray=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var n=[],o=!0,i=!1,r=void 0;try{for(var a,s=e[Symbol.iterator]();!(o=(a=s.next()).done)&&(n.push(a.value),!t||n.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{!o&&s.return&&s.return()}finally{if(i)throw r}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),toConsumableArray=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)},_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},simulateMissingKeyPressEvents:!0,stopEventPropagationAfterHandling:!0,stopEventPropagationAfterIgnoring:!0},_configuration=_extends({},_defaultConfiguration);_configuration._ignoreTagsDict=dictionaryFrom(_configuration.ignoreTags,!0);var Configuration=function(){function e(){classCallCheck(this,e)}return createClass(e,null,[{key:"init",value:function(e){var t=this;e.ignoreTags&&(e._ignoreTagsDict=dictionaryFrom(e.ignoreTags)),-1!==["verbose","debug","info"].indexOf(e.logLevel)&&console.warn("React HotKeys: You have requested log level '"+e.logLevel+"' but for performance reasons, logging below severity level 'warning' is disabled in production. Please use the development build for complete logs."),Object.keys(e).forEach(function(n){t.set(n,e[n])})}},{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 e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"warn";classCallCheck(this,e),this.verbose=this.noop,this.debug=this.noop,this.info=this.noop,this.warn=this.noop,this.error=this.noop,this.logLevel=this.constructor.levels[n],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(e,[{key:"noop",value:function(){}}]),e}();function isUndefined(e){return void 0===e}Logger.logIcons=["📕","📗","📘","📙"],Logger.componentIcons=["🔺","⭐️","🔷","🔶","⬛️"],Logger.eventIcons=["❤️","💚","💙","💛","💜","🧡"],Logger.levels={none:0,error:1,warn:2,info:3,debug:4,verbose:5};var KeyEventBitmapManager=function(){function e(){classCallCheck(this,e)}return createClass(e,null,[{key:"newBitmap",value:function(e){var t=[!1,!1,!1];if(!isUndefined(e))for(var n=0;n<=e;n++)t[n]=!0;return t}},{key:"setBit",value:function(e,t){return e[t]=!0,e}},{key:"clone",value:function(e){for(var t=this.newBitmap(),n=0;n<e.length;n++)t[n]=e[n];return t}},{key:"and",value:function(e,t){for(var n=[],o=0;o<e.length;o++)n[o]=e[o]&t[o];return n}}]),e}(),KeyEventBitmapIndex={keydown:0,keypress:1,keyup:2},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(e){return Object.keys(e).reduce(function(t,n){return e[n].forEach(function(e){hasKey(t,e)||(t[e]=[]),t[e].push(n)}),t},{})}var UnshiftedKeysDictionary=invertArrayDictionary(ShiftedKeysDictionary);function resolveUnshiftedAlias(e){return UnshiftedKeysDictionary[e]||[1===e.length?e.toLowerCase():e]}var KeyAliasesDictionary={Backspace:["Delete"]};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:"Backspace",command:"Meta",option:"Alt",enter:"Enter",backspace:"Backspace",ins:"Insert",pageup:"PageUp",pagedown:"PageDown",end:"End",home:"Home",contextmenu:"ContextMenu",numlock:"Clear"};function standardizeKeyName(e){return MousetrapToReactKeyNamesDictionary[e.toLowerCase()]||(e.match(/^f\d+$/)?e.toUpperCase():e)}var SpecialKeysDictionary={Shift:!0,Control:!0,Alt:!0,Meta:!0,Enter:!0,Tab:!0,CapsLock:!0,BackSpace:!0};function isSpecialKey(e){return!!SpecialKeysDictionary[e]}function isValidKey(e){return isSpecialKey(e)||String.fromCharCode(e.charCodeAt(0))===e}var InvalidKeyNameError=function(e){function t(){return classCallCheck(this,t),possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return inherits(t,e),t}(Error);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 t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=stripSuperfluousWhitespace(e).split(" ");try{var o=n.slice(0,n.length-1),i=n[n.length-1],r=o.map(function(e){var n=parseCombination(e,t);return normalizedCombinationId(Object.keys(n))}).join(" "),a=parseCombination(i,t),s={id:normalizedCombinationId(Object.keys(a)),keyDictionary:a,eventBitmapIndex:t.eventBitmapIndex,size:Object.keys(a).length};return{sequence:{prefix:r,size:o.length+1},combination:s}}catch(e){return{sequence:null,combination:null}}}}]),e}();function parseCombination(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e.replace(/^\+|(\s|[^+]\+)\+/,"$1plus").split("+").reduce(function(e,n){var o=standardizeKeyName(n);if(t.ensureValidKeys&&!isValidKey(o))throw new InvalidKeyNameError;return e[o]=!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 t=e.Shift,n=e.Alt,o={};return Object.keys(e).sort().forEach(function(e){var i=[];if(t)if(n){var r=resolveUnaltShiftedAlias(e),a=resolveAltShiftedAlias(e);i=[].concat(toConsumableArray(i),[e],toConsumableArray(r),toConsumableArray(a))}else{var s=resolveUnshiftedAlias(e),u=resolveShiftedAlias(e);i=[].concat(toConsumableArray(i),[e],toConsumableArray(s),toConsumableArray(u))}else if(n){var l=resolveUnaltedAlias(e),c=resolveAltedAlias(e);i=[].concat(toConsumableArray(i),[e],toConsumableArray(l),toConsumableArray(c))}else{i.push(e);var y=KeyAliasesDictionary[e];y&&(i=[].concat(toConsumableArray(i),toConsumableArray(y)))}var h=Object.keys(o);h.length>0?h.forEach(function(e){i.forEach(function(t){o[e+"+"+t]=_extends({},o[e],defineProperty({},t,!0))}),delete o[e]}):i.forEach(function(e){o[e]=defineProperty({},e,!0)})}),Object.values(o).map(function(e){return Object.keys(e).sort().join("+")})}},{key:"isValidKeySerialization",value:function(e){return e.length>0&&!!KeySequenceParser.parse(e,{ensureValidKeys:!0}).combination}}]),e}();function arrayFrom(e){return Array.isArray(e)?e:e?[e]:[]}function indexFromEnd(e,t){return e[e.length-(t+1)]}function isObject(e){return!Array.isArray(e)&&"object"===(void 0===e?"undefined":_typeof(e))&&null!==e}function isEmpty(e){return isObject(e)?0===Object.keys(e).length:!e||0===e.length}function describeKeyEvent(e){switch(parseInt(e,10)){case 0:return"keydown";case 1:return"keypress";default:return"keyup"}}var KeyEventSequenceIndex={previous:0,current:1};function resolveKeyAlias(e){return KeyAliasesDictionary[e]||[e]}for(var ModifierFlagsDictionary={Shift:["shiftKey"],Meta:["metaKey"],Control:["ctrlKey"],Alt:["altKey"]},AbstractKeyEventStrategy=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];classCallCheck(this,e),this.logger=t.logger||new Logger("warn"),this.componentId=0,this.keyEventManager=n,this._reset(),this._resetKeyCombinationHistory()}return createClass(e,[{key:"_reset",value:function(){this._resetRegisteredKeyMapsState(),this._resetHandlerResolutionState()}},{key:"_resetRegisteredKeyMapsState",value:function(){this.componentList=[],this.longestSequence=1,this.longestSequenceComponentIndex=null,this.keyMapEventBitmap=KeyEventBitmapManager.newBitmap()}},{key:"_resetHandlerResolutionState",value:function(){this.keyMaps=null,this.handlerResolutionSearchIndex=0,this.unmatchedHandlerStatus=null,this.handlersDictionary={},this.keySequencesDictionary={}}},{key:"_resetKeyCombinationHistory",value:function(){if(this.keyCombinationIncludesKeyUp=!1,this.keypressEventsToSimulate=[],!this.keyCombinationHistory||this.keyCombinationHistory.length<1)this.keyCombinationHistory=[];else{var e=this._getCurrentKeyCombination(),t=Object.keys(e.keys).reduce(function(t,n){var o=e.keys[n],i=o[KeyEventSequenceIndex.current];return i[KeyEventBitmapIndex.keydown]&&!i[KeyEventBitmapIndex.keyup]&&(t[n]=o),t},{});this.keyCombinationHistory=[{keys:t,ids:KeyCombinationSerializer.serialize(t)}]}}},{key:"_addComponentToList",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=this._buildComponentOptions(e,t,n,o);return this.componentList.push(i),i}},{key:"_buildComponentOptions",value:function(e,t,n,o){var i=this._applyHardSequences(t,n),r=i.keyMap,a=i.handlers;return{actions:this._buildActionDictionary(_extends({},t,r),o,e),handlers:a,componentId:e,options:o}}},{key:"_applyHardSequences",value:function(e,t){return Configuration.option("enableHardSequences")?Object.keys(t).reduce(function(n,o){return!!!e[o]&&KeyCombinationSerializer.isValidKeySerialization(o)&&(n.keyMap[o]=o),n.handlers[o]=t[o],n},{keyMap:{},handlers:{}}):{keyMap:e,handlers:t}}},{key:"_buildActionDictionary",value:function(e,t,n){var o=this;return Object.keys(e).reduce(function(i,r){return arrayFrom(e[r]).forEach(function(e){var a=function(){if(isObject(e)){var n=e.sequence,o=e.action;return{keySequence:n,eventBitmapIndex:isUndefined(o)?KeyEventBitmapIndex[t.defaultKeyEvent]:KeyEventBitmapIndex[o]}}return{keySequence:e,eventBitmapIndex:KeyEventBitmapIndex[t.defaultKeyEvent]}}(),s=a.keySequence,u=a.eventBitmapIndex,l=KeySequenceParser.parse(s,{eventBitmapIndex:u}),c=l.sequence,y=l.combination;c.size>o.longestSequence&&(o.longestSequence=c.size,o.longestSequenceComponentIndex=n),KeyEventBitmapManager.setBit(o.keyMapEventBitmap,u),i[r]||(i[r]=[]),i[r].push(_extends({prefix:c.prefix,actionName:r,sequenceLength:c.size},y))}),i},{})}},{key:"_getCurrentKeyCombination",value:function(){return this.keyCombinationHistory.length>0?this.keyCombinationHistory[this.keyCombinationHistory.length-1]:{keys:{},ids:[""],keyAliases:{}}}},{key:"_addToCurrentKeyCombination",value:function(e,t){0===this.keyCombinationHistory.length&&this.keyCombinationHistory.push({keys:{},ids:[""],keyAliases:{}});var n=this._getCurrentKeyCombination(),o=this._getKeyAlias(n,e),i=this._getKeyState(n,e);n.keys[o]=i?[KeyEventBitmapManager.clone(i[1]),KeyEventBitmapManager.newBitmap(t)]:[KeyEventBitmapManager.newBitmap(),KeyEventBitmapManager.newBitmap(t)],n.ids=KeyCombinationSerializer.serialize(n.keys),n.keyAliases=this._buildCombinationKeyAliases(n.keys),t===KeyEventBitmapIndex.keyup&&(this.keyCombinationIncludesKeyUp=!0)}},{key:"_startNewKeyCombination",value:function(e,t){this.keyCombinationHistory.length>this.longestSequence&&this.keyCombinationHistory.shift();var n=this._getCurrentKeyCombination(),o=_extends({},this._withoutKeyUps(n),defineProperty({},e,[KeyEventBitmapManager.newBitmap(),KeyEventBitmapManager.newBitmap(t)]));this.keyCombinationHistory.push({keys:o,ids:KeyCombinationSerializer.serialize(o),keyAliases:this._buildCombinationKeyAliases(o)}),this.keyCombinationIncludesKeyUp=!1}},{key:"_withoutKeyUps",value:function(e){return Object.keys(e.keys).reduce(function(t,n){var o=e.keys[n];return o[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keyup]||(t[n]=o),t},{})}},{key:"_callMatchingHandlerClosestToEventTarget",value:function(e,t,n,o,i){var r=this;for(this.keyMaps&&this.unmatchedHandlerStatus||(this.keyMaps=[],this.unmatchedHandlerStatus=[],this.componentList.forEach(function(e){var t=e.handlers;r.unmatchedHandlerStatus.push([Object.keys(t).length,{}]),r.keyMaps.push({})}));i<=o;){var a=this.unmatchedHandlerStatus[i][0];if(a>0)for(var s=function(){var e=r.componentList[r.handlerResolutionSearchIndex],t=e.handlers,n=e.actions;Object.keys(t).forEach(function(e){r.handlersDictionary[e]||(r.handlersDictionary[e]=[]),r.handlersDictionary[e].push(r.handlerResolutionSearchIndex)}),Object.keys(n).forEach(function(e){var t=r.handlersDictionary[e];if(t){var o=t[0],i=r.componentList[o].handlers[e],a=r.keyMaps[o];a.sequences||(a.sequences={}),n[e].forEach(function(e){var t=[e.prefix,e.id].join(" ");if(!(r.keySequencesDictionary[t]&&r.keySequencesDictionary[t].some(function(t){return t[1]===e.eventBitmapIndex}))){a.sequences[e.prefix]||(a.sequences[e.prefix]={combinations:{}});var n=e.prefix,s=e.sequenceLength,u=e.id,l=e.keyDictionary,c=e.size,y=e.eventBitmapIndex,h=e.actionName,p=a.sequences[e.prefix].combinations[e.id];a.sequences[e.prefix].combinations[e.id]=p?_extends({},p,{events:_extends({},p.events,defineProperty({},y,{actionName:h,eventBitmapIndex:y,handler:i}))}):{prefix:n,sequenceLength:s,id:u,keyDictionary:l,size:c,events:defineProperty({},y,{actionName:h,eventBitmapIndex:y,handler:i})},a.eventBitmap||(a.eventBitmap=KeyEventBitmapManager.newBitmap()),KeyEventBitmapManager.setBit(a.eventBitmap,e.eventBitmapIndex),(!a.longestSequence||a.longestSequence<e.sequenceLength)&&(a.longestSequence=e.sequenceLength),r.keySequencesDictionary[t]||(r.keySequencesDictionary[t]=[]),r.keySequencesDictionary[t].push([o,e.eventBitmapIndex])}}),t.forEach(function(t){var n=r.unmatchedHandlerStatus[t];n[1][e]||(n[1][e]=!0,n[0]--)})}}),r.handlerResolutionSearchIndex++};this.handlerResolutionSearchIndex<this.componentList.length&&a>0;)s();var u=this.keyMaps[i];if(u&&!isEmpty(u.sequences)&&u.eventBitmap[n])for(var l=u.sequences,c=u.longestSequence,y=this._getCurrentKeyCombination(),h=this._getKeyAlias(y,t),p=c;p>=0;){var d=this.keyCombinationHistory.slice(-p,-1).map(function(e){return e.ids}),v=this._tryMatchSequenceWithKeyAliases(l,d);if(v){v.order||function(){var e=Object.values(v.combinations).reduce(function(e,t){var n=t.id,o=t.size;return e[o]||(e[o]=[]),e[o].push(n),e},{});v.order=Object.keys(e).sort(function(e,t){return t-e}).reduce(function(t,n){return t.concat(e[n])},[])}();for(var f=v.order,g=0;g<f.length;){var m=f[g],_=v.combinations[m];if(this._combinationMatchesKeys(h,y,_,n)){KeyCombinationSerializer.serialize(_.keyDictionary);return _.events[n].handler(e),this._stopEventPropagationAfterHandlingIfEnabled(e,i),!0}g++}}p--}else;i++}}},{key:"_stopEventPropagationAfterHandlingIfEnabled",value:function(e,t){return!!Configuration.option("stopEventPropagationAfterHandling")&&(this._stopEventPropagation(e,t),!0)}},{key:"_stopEventPropagationAfterIgnoringIfEnabled",value:function(e,t){return!!Configuration.option("stopEventPropagationAfterIgnoring")&&(this._stopEventPropagation(e,t),!0)}},{key:"_stopEventPropagation",value:function(e,t){e.stopPropagation()}},{key:"_describeCurrentKeyCombination",value:function(){return this._getCurrentKeyCombination().ids[0]}},{key:"_tryMatchSequenceWithKeyAliases",value:function(e,t){if(0===t.length)return e[""];for(var n=t.map(function(e){return e.length}),o=t.map(function(){return 0}),i=!1;!i;){var r=o.map(function(e,n){return t[n][e]}).join(" ");if(e[r])return e[r];for(var a=0,s=!0;s&&a<o.length;){var u=(indexFromEnd(o,a)+1)%(indexFromEnd(n,a)||1);o[o.length-(a+1)]=u,(s=0===u)&&a++}i=a===o.length}}},{key:"_combinationMatchesKeys",value:function(e,t,n,o){var i=this;if(!n.events[o])return!1;var r=!1;return!Object.keys(n.keyDictionary).some(function(n){var a=i._getKeyState(t,n);return!a||(!i._keyIsCurrentlyTriggeringEvent(a,o)||(e&&e===i._getKeyAlias(t,n)&&(r=!i._keyAlreadyTriggeredEvent(a,o)),!1))})&&r}},{key:"_checkForModifierFlagDiscrepancies",value:function(e){var t=this;Object.keys(ModifierFlagsDictionary).forEach(function(n){var o=t._getCurrentKeyState(n),i=o&&!t._keyIsCurrentlyTriggeringEvent(o,KeyEventBitmapIndex.keyup);ModifierFlagsDictionary[n].forEach(function(o){!1===e[o]&&i&&t._addToCurrentKeyCombination(n,KeyEventBitmapIndex.keyup)})})}},{key:"_keyIsCurrentlyTriggeringEvent",value:function(e,t){return e&&e[KeyEventSequenceIndex.current][t]}},{key:"_keyAlreadyTriggeredEvent",value:function(e,t){return e&&e[KeyEventSequenceIndex.previous][t]}},{key:"_getCurrentKeyState",value:function(e){var t=this._getCurrentKeyCombination();return this._getKeyState(t,e)}},{key:"_getKeyState",value:function(e,t){var n=e.keys[t];if(n)return n;var o=e.keyAliases[t];return o?e.keys[o]:void 0}},{key:"_getKeyAlias",value:function(e,t){if(e.keys[t])return t;var n=e.keyAliases[t];return n||t}},{key:"_buildCombinationKeyAliases",value:function(e){var t=function(){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]}();return Object.keys(e).reduce(function(e,n){return resolveKeyAlias(n).forEach(function(o){t.forEach(function(t){t(o).forEach(function(t){t===n&&n===o||(e[t]=n)})})}),e},{})}}]),e}(),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}(),KeysWithoutPressEventDictionary={Shift:!0,Control:!0,Alt:!0,Meta:!0,Enter:!0,Tab:!0,BackSpace:!0,ArrowRight:!0,ArrowLeft:!0,ArrowUp:!0,ArrowDown:!0,CapsLock:!0},i=1;i<13;i++)KeysWithoutPressEventDictionary["F"+i]=!0;function hasKeyPressEvent(e){return!KeysWithoutPressEventDictionary[e]}function normalizeKeyName(e){return"+"===e?"plus":e}var FocusOnlyKeyEventStrategy=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];classCallCheck(this,t);var o=possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o.focusTreeId=0,o.currentEvent={key:null,type:null,handled:!1},o}return inherits(t,AbstractKeyEventStrategy),createClass(t,[{key:"_reset",value:function(){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_reset",this).call(this),this.componentId=0,this.focusTreeId+=1,this._clearEventPropagationState()}},{key:"_clearEventPropagationState",value:function(){this.eventPropagationState={previousComponentIndex:-1,actionHandled:!1,ignoreEvent:!1}}},{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];return(this.resetOnNextFocus||this.keyMaps)&&(this._reset(),this.resetOnNextFocus=!1),this.componentId=this.componentList.length,this._addComponentToList(this.componentId,e,t,n),[this.focusTreeId,this.componentId]}},{key:"updateHotKeys",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments[4];e===this.focusTreeId&&this.componentList[t]&&(this.componentList[t]=this._buildComponentOptions(t,n,o,i))}},{key:"removeHotKeys",value:function(e,t){return this.resetOnNextFocus||(this.resetOnNextFocus=!0),this.eventPropagationState.previousComponentIndex+1<t}},{key:"handleKeydown",value:function(e,t,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=normalizeKeyName(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())return this._ignoreEvent(e,n),!1;if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,KeyEventBitmapIndex.keydown),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return this._ignoreEvent(e,n),!1;this._checkForModifierFlagDiscrepancies(e),!!this._getCurrentKeyState(i)||this.keyCombinationIncludesKeyUp?this._startNewKeyCombination(i,KeyEventBitmapIndex.keydown,t,n):this._addToCurrentKeyCombination(i,KeyEventBitmapIndex.keydown,t,n)}return this._callHandlerIfActionNotHandled(e,i,KeyEventBitmapIndex.keydown,n,t),!hasKeyPressEvent(i)&&Configuration.option("simulateMissingKeyPressEvents")&&(e.persist(),this.keypressEventsToSimulate.push({event:e,focusTreeId:t,componentId:n,options:o,key:i})),this._isFocusTreeRoot(n)&&(this.keyEventManager.isGlobalListenersBound()||this.simulatePendingKeyPressEvents(i)),this._updateEventPropagationHistory(n),!1}},{key:"simulatePendingKeyPressEvents",value:function(){var e=this;this.keypressEventsToSimulate.length>0&&KeyEventCounter.incrementId(),this.keypressEventsToSimulate.forEach(function(t){var n=t.event,o=t.focusTreeId,i=t.componentId,r=t.options;e.handleKeypress(n,o,i,r)}),this.keypressEventsToSimulate=[],this._clearEventPropagationState()}},{key:"handleKeypress",value:function(e,t,n,o){var i=normalizeKeyName(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())this._ignoreEvent(e,n);else{if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,KeyEventBitmapIndex.keypress),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return void this._ignoreEvent(e,n);var r=this._getCurrentKeyState(i);r&&(r[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keypress]||r[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keyup])?this._startNewKeyCombination(i,KeyEventBitmapIndex.keypres,t,n):this._addToCurrentKeyCombination(i,KeyEventBitmapIndex.keypress,t,n)}this._callHandlerIfActionNotHandled(e,i,KeyEventBitmapIndex.keypress,n,t),this._updateEventPropagationHistory(n)}}},{key:"handleKeyup",value:function(e,t,n,o){var i=normalizeKeyName(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())this._ignoreEvent(e,n);else{if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,KeyEventBitmapIndex.keyup),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return void this._ignoreEvent(e,n);var r=this._getCurrentKeyState(i);r&&r[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keyup]?this._startNewKeyCombination(i,KeyEventBitmapIndex.keyup,t,n):this._addToCurrentKeyCombination(i,KeyEventBitmapIndex.keyup,t,n)}this._callHandlerIfActionNotHandled(e,i,KeyEventBitmapIndex.keyup,n,t),this._updateEventPropagationHistory(n)}}},{key:"_ignoreEvent",value:function(e,t){this._stopEventPropagationAfterIgnoringIfEnabled(e,t)?this._updateEventPropagationHistory(t,{forceReset:!0}):this._updateEventPropagationHistory(t)}},{key:"_alreadyEstablishedShouldIgnoreEvent",value:function(){return this.eventPropagationState.ignoreEvent}},{key:"_isNewKeyEvent",value:function(e){var t=this.eventPropagationState.previousComponentIndex;return-1===t||t>=e}},{key:"_updateEventPropagationHistory",value:function(e){(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{forceReset:!1}).forceReset||this._isFocusTreeRoot(e)?this._clearEventPropagationState():this.eventPropagationState.previousComponentIndex=e}},{key:"_setIgnoreEventFlag",value:function(e,t){this.eventPropagationState.ignoreEvent=t.ignoreEventsCondition(e)}},{key:"ignoreEvent",value:function(e){this.eventPropagationState.ignoreEvent=!0}},{key:"_isFocusTreeRoot",value:function(e){return e>=this.componentList.length-1}},{key:"_setNewEventParameters",value:function(e,t){KeyEventCounter.incrementId(),this.currentEvent={key:e.key,type:t,handled:!1}}},{key:"_startNewKeyCombination",value:function(e,n,o,i){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_startNewKeyCombination",this).call(this,e,n)}},{key:"_addToCurrentKeyCombination",value:function(e,n,o,i){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addToCurrentKeyCombination",this).call(this,e,n)}},{key:"_callHandlerIfActionNotHandled",value:function(e,t,n,o,i){this._describeCurrentKeyCombination();if(this.keyMapEventBitmap[n])if(this.eventPropagationState.actionHandled);else{var r=this.eventPropagationState.previousComponentIndex;this._callMatchingHandlerClosestToEventTarget(e,t,n,o,-1===r?0:r)&&(this.eventPropagationState.actionHandled=!0,this.currentEvent.handled=!0)}}},{key:"_logPrefix",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Logger.logIcons,o=Logger.eventIcons,i=Logger.componentIcons,r="HotKeys (";if(!1!==t.focusTreeId){var a=isUndefined(t.focusTreeId)?this.focusTreeId:t.focusTreeId;r+="FT"+a+n[a%n.length]+"-"}if(!1!==t.eventId){var s=isUndefined(t.eventId)?KeyEventCounter.getId():t.eventId;r+="E"+s+o[s%o.length]+"-"}return r+"C"+e+i[e%i.length]+"):"}}]),t}();function capitalize(e){return e.replace(/\b\w/g,function(e){return e.toUpperCase()})}function removeAtIndex(e,t){return[].concat(toConsumableArray(e.slice(0,t)),toConsumableArray(e.slice(t+1)))}function getEventCharCode(e){var t=void 0,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,10===t&&(t=13),t>=32||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"},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"};function getEventKey(e){if(e.key){var t=normalizeKey[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=getEventCharCode(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?translateToKey[e.keyCode]||"Unidentified":""}var GlobalKeyEventStrategy=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];classCallCheck(this,t);var o=possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o.componentId=-1,o.listenersBound=!1,o.eventOptions={ignoreEventsCondition:Configuration.option("ignoreEventsCondition")},o}return inherits(t,AbstractKeyEventStrategy),createClass(t,[{key:"_reset",value:function(){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_reset",this).call(this),this.componentIdDict={}}},{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2],o=arguments[3];return this.eventOptions=o,this.componentId+=1,this._addComponentToList(this.componentId,e,t,n),this._updateDocumentHandlers(),this.componentId}},{key:"updateHotKeys",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=arguments[4];this.eventOptions=i;var r=this._getComponentPosition(e);this.componentList[r]=this._buildComponentOptions(e,t,n,o),this._updateLongestKeySequenceIfNecessary(e),this._updateDocumentHandlers(),this._resetHandlerResolutionState()}},{key:"removeHotKeys",value:function(e){var t=this._getComponentAndPosition(e),n=slicedToArray(t,2),o=n[0].keyMapEventBitmap,i=n[1];this.componentList=removeAtIndex(this.componentList,i),this._updateLongestKeySequenceIfNecessary(e),this._updateComponentIndexDictFromList({startingAt:i}),this._updateDocumentHandlers(o,KeyEventBitmapManager.newBitmap()),this._resetHandlerResolutionState()}},{key:"_addComponentToList",value:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments[3];get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addComponentToList",this).call(this,e,n,o,i),this._setComponentPosition(e,this.componentList.length-1)}},{key:"_setComponentPosition",value:function(e,t){this.componentIdDict[e]=t}},{key:"_updateLongestKeySequenceIfNecessary",value:function(e){var t=this;e===this.longestSequenceComponentIndex&&(this.longestSequence=1,this.componentList.forEach(function(e){var n=e.longestSequence;n>t.longestSequence&&(t.longestSequence=n)}))}},{key:"_updateComponentIndexDictFromList",value:function(){for(var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{startingAt:0}).startAt;e<this.componentList.length;)this._setComponentPosition(this.componentList[e].componentId,e)}},{key:"_updateDocumentHandlers",value:function(){var e=this,t=this.keyMapEventBitmap.some(function(e){return e});if(!this.listenersBound&&t){for(var n=function(t){var n=describeKeyEvent(t);document["on"+n]=function(t){e.keyEventManager["handleGlobal"+capitalize(n)](t)}},o=0;o<this.keyMapEventBitmap.length;o++)n(o);this.listenersBound=!0}else if(this.listenersBound&&!t){for(o=0;o<this.keyMapEventBitmap.length;o++){var i=describeKeyEvent(o);delete document["on"+i]}this.listenersBound=!1}}},{key:"handleKeydown",value:function(e){this._checkForModifierFlagDiscrepancies(e);var t=normalizeKeyName(getEventKey(e));!!this._getCurrentKeyState(t)||this.keyCombinationIncludesKeyUp?this._startNewKeyCombination(t,KeyEventBitmapIndex.keydown):this._addToCurrentKeyCombination(t,KeyEventBitmapIndex.keydown);var n=this.keyEventManager.reactAppHistoryWithEvent(t,KeyEventBitmapIndex.keydown);if("handled"===n);else{if("seen"===n||KeyEventCounter.incrementId(),this.eventOptions.ignoreEventsCondition(e))return;this._callHandlerIfExists(e,t,KeyEventBitmapIndex.keydown),hasKeyPressEvent(t)||(this.keyEventManager.simulatePendingKeyPressEvents(),this.handleKeypress(e))}}},{key:"handleKeypress",value:function(e){var t=normalizeKeyName(getEventKey(e)),n=this._getCurrentKeyState(t);n&&(n[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keypress]||n[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keyup])?this._startNewKeyCombination(t,KeyEventBitmapIndex.keypress):this._addToCurrentKeyCombination(t,KeyEventBitmapIndex.keypress);var o=this.keyEventManager.reactAppHistoryWithEvent(t,KeyEventBitmapIndex.keypress);return"handled"!==o&&("seen"===o||KeyEventCounter.incrementId(),!this.eventOptions.ignoreEventsCondition(e)&&void this._callHandlerIfExists(e,t,KeyEventBitmapIndex.keypress))}},{key:"handleKeyup",value:function(e){var t=normalizeKeyName(getEventKey(e)),n=this._getCurrentKeyState(t);n&&n[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keyup]?this._startNewKeyCombination(t,KeyEventBitmapIndex.keyup):this._addToCurrentKeyCombination(t,KeyEventBitmapIndex.keyup);var o=this.keyEventManager.reactAppHistoryWithEvent(t,KeyEventBitmapIndex.keyup);return"handled"!==o&&("seen"===o||KeyEventCounter.incrementId(),!this.eventOptions.ignoreEventsCondition(e)&&void this._callHandlerIfExists(e,t,KeyEventBitmapIndex.keyup))}},{key:"_startNewKeyCombination",value:function(e,n){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_startNewKeyCombination",this).call(this,e,n)}},{key:"_addToCurrentKeyCombination",value:function(e,n){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addToCurrentKeyCombination",this).call(this,e,n)}},{key:"_getComponentPosition",value:function(e){return this.componentIdDict[e]}},{key:"_getComponent",value:function(e){var t=this._getComponentPosition(e);return this.componentList[t]}},{key:"_getComponentAndPosition",value:function(e){var t=this._getComponentPosition(e);return[this.componentList[t],t]}},{key:"_callHandlerIfExists",value:function(e,t,n){this._describeCurrentKeyCombination();this.keyMapEventBitmap[n]&&this._callMatchingHandlerClosestToEventTarget(e,t,n)}},{key:"_callMatchingHandlerClosestToEventTarget",value:function(e,n,o){for(var i=0;i<this.componentList.length;i++){if(get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_callMatchingHandlerClosestToEventTarget",this).call(this,e,n,o,i,0))return}}},{key:"_logPrefix",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Logger.eventIcons,o=Logger.componentIcons,i="HotKeys (GLOBAL";if(!1!==t.eventId){var r=isUndefined(t.eventId)?KeyEventCounter.getId():t.eventId;i=i+"-E"+r+n[r%n.length]}return isUndefined(e)?i+"):":i+"-C"+e+o[e%o.length]+"):"}}]),t}();function isFromFocusOnlyComponent(e){return!isUndefined(e)}var KeyEventManager=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};classCallCheck(this,e),this.logger=t.logger||new Logger(Configuration.option("logLevel")),this._focusOnlyEventStrategy=new FocusOnlyKeyEventStrategy({configuration:t,logger:this.logger},this),this._globalEventStrategy=new GlobalKeyEventStrategy({configuration:t,logger:this.logger},this),this.lastEventSeen=null}return createClass(e,null,[{key:"getInstance",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.instance||(this.instance=new e(t)),this.instance}},{key:"clear",value:function(){delete this.instance}}]),createClass(e,[{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];return this._focusOnlyEventStrategy.addHotKeys(e,t,n)}},{key:"updateHotKeys",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments[4];return this._focusOnlyEventStrategy.updateHotKeys(e,t,n,o,i)}},{key:"removeHotKeys",value:function(e,t){return this._focusOnlyEventStrategy.removeHotKeys(e,t)}},{key:"handleKeydown",value:function(e,t,n,o){if(isFromFocusOnlyComponent(t))return this._focusOnlyEventStrategy.handleKeydown(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"handleKeypress",value:function(e,t,n,o){if(isFromFocusOnlyComponent(t))return this._focusOnlyEventStrategy.handleKeypress(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"handleKeyup",value:function(e,t,n,o){if(isFromFocusOnlyComponent(t))return this._focusOnlyEventStrategy.handleKeyup(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"_recordLastSeenEvent",value:function(e){var t=e.key,n=e.type,o=e.nativeEvent;this.lastEventSeen={key:t,type:n,nativeEvent:o}}},{key:"addGlobalHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2],o=arguments[3];return this._globalEventStrategy.addHotKeys(e,t,n,o)}},{key:"updateGlobalHotKeys",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=arguments[4];return this._globalEventStrategy.updateHotKeys(e,t,n,o,i)}},{key:"removeGlobalHotKeys",value:function(e){return this._globalEventStrategy.removeHotKeys(e)}},{key:"handleGlobalKeydown",value:function(e){return this._globalEventStrategy.handleKeydown(e)}},{key:"handleGlobalKeypress",value:function(e){return this._globalEventStrategy.handleKeypress(e)}},{key:"handleGlobalKeyup",value:function(e){return this._globalEventStrategy.handleKeyup(e)}},{key:"ignoreEvent",value:function(e){this._focusOnlyEventStrategy.ignoreEvent(e)}},{key:"reactAppHistoryWithEvent",value:function(e,t){var n=this._focusOnlyEventStrategy.currentEvent;return n.key===e&&n.type===t?n.handled?"handled":"seen":"unseen"}},{key:"simulatePendingKeyPressEvents",value:function(){this._focusOnlyEventStrategy.simulatePendingKeyPressEvents()}},{key:"isGlobalListenersBound",value:function(){return this._globalEventStrategy.listenersBound}}]),e}();function withHotKeys(e){var t,n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};function i(e,t){return _extends({},o[e]||{},t[e]||{})}function r(e){return i("handlers",e)}function a(e){return i("keyMap",e)}return n=t=function(t){function n(e){classCallCheck(this,n);var t=possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t._handleFocus=t._handleFocus.bind(t),t._handleBlur=t._handleBlur.bind(t),t._handleKeyDown=t._handleKeyDown.bind(t),t._handleKeyPress=t._handleKeyPress.bind(t),t._handleKeyUp=t._handleKeyUp.bind(t),t._componentIsFocused=t._componentIsFocused.bind(t),t}return inherits(n,t),createClass(n,[{key:"render",value:function(){var t=this.props,n=(t.keyMap,t.handlers,t.allowChanges,objectWithoutProperties(t,["keyMap","handlers","allowChanges"])),o={onFocus:this._wrapFunction("onFocus",this._handleFocus),onBlur:this._wrapFunction("onBlur",this._handleBlur),tabIndex:Configuration.option("defaultTabIndex")};return this._shouldBindKeyListeners()&&(o.onKeyDown=this._handleKeyDown,o.onKeyPress=this._handleKeyPress,o.onKeyUp=this._handleKeyUp),React__default.createElement(e,_extends({hotKeys:o},n))}},{key:"_shouldBindKeyListeners",value:function(){var e=a(this.props);return!isEmpty(e)||Configuration.option("enableHardSequences")&&this._handlersIncludeHardSequences(e,r(this.props))}},{key:"_handlersIncludeHardSequences",value:function(e,t){return Object.keys(t).some(function(t){return!e[t]&&KeyCombinationSerializer.isValidKeySerialization(t)})}},{key:"_wrapFunction",value:function(e,t){var n=this;return"function"==typeof this.props[e]?function(o){n.props[e](o),t(o)}:t}},{key:"_focusTreeIdsPush",value:function(e){this._focusTreeIds||(this._focusTreeIds=[]),this._focusTreeIds.push(e)}},{key:"_focusTreeIdsShift",value:function(){this._focusTreeIds&&this._focusTreeIds.shift()}},{key:"_getFocusTreeId",value:function(){if(this._focusTreeIds)return this._focusTreeIds[0]}},{key:"componentDidUpdate",value:function(e){if(this._componentIsFocused()&&(this.props.allowChanges||!Configuration.option("ignoreKeymapAndHandlerChangesByDefault"))){var t=this.props,n=t.keyMap,o=t.handlers;KeyEventManager.getInstance().updateHotKeys(this._getFocusTreeId(),this._componentId,n,o,this._getComponentOptions())}}},{key:"componentWillUnmount",value:function(){this._handleBlur()}},{key:"_componentIsFocused",value:function(){return!0===this._focused}},{key:"_handleFocus",value:function(){var e;this.props.onFocus&&(e=this.props).onFocus.apply(e,arguments);var t=KeyEventManager.getInstance().addHotKeys(a(this.props),r(this.props),this._getComponentOptions()),n=slicedToArray(t,2),o=n[0],i=n[1];this._componentId=i,this._focusTreeIdsPush(o),this._focused=!0}},{key:"_handleBlur",value:function(){var e;this.props.onBlur&&(e=this.props).onBlur.apply(e,arguments);KeyEventManager.getInstance().removeHotKeys(this._getFocusTreeId(),this._componentId)||this._focusTreeIdsShift(),this._focused=!1}},{key:"_handleKeyDown",value:function(e){KeyEventManager.getInstance().handleKeydown(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_handleKeyPress",value:function(e){KeyEventManager.getInstance().handleKeypress(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_handleKeyUp",value:function(e){KeyEventManager.getInstance().handleKeyup(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_getComponentOptions",value:function(){return{defaultKeyEvent:Configuration.option("defaultKeyEvent")}}},{key:"_getEventOptions",value:function(){return{ignoreEventsCondition:Configuration.option("ignoreEventsCondition")}}}]),n}(React.PureComponent),t.propTypes={keyMap:PropTypes.object,handlers:PropTypes.object,onFocus:PropTypes.func,onBlur:PropTypes.func,allowChanges:PropTypes.bool},n}var HotKeysWrapper=function(e){function t(){return classCallCheck(this,t),possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return inherits(t,e),createClass(t,[{key:"render",value:function(){var e=this.props,t=e.hotKeys,n=objectWithoutProperties(e,["hotKeys"]),o=n.component||Configuration.option("defaultComponent");return React__default.createElement(o,_extends({},t,n))}}]),t}(React.Component),HotKeys=withHotKeys(HotKeysWrapper);function withHotKeysIgnore(e){var t,n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{only:[],except:[]};return n=t=function(t){function n(e){classCallCheck(this,n);var t=possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t._handleKeyEvent=t._handleKeyEvent.bind(t),t._reloadDictionaries=t._reloadDictionaries.bind(t),t}return inherits(n,t),createClass(n,[{key:"getDefaultProps",value:function(){return o}}]),createClass(n,[{key:"render",value:function(){var t=this.props,n=(t.only,t.except,objectWithoutProperties(t,["only","except"])),o={onKeyDown:this._handleKeyEvent,onKeyPress:this._handleKeyEvent,onKeyUp:this._handleKeyEvent,onFocus:this._reloadDictionaries};return React__default.createElement(e,_extends({hotKeys:o},n))}},{key:"_reloadDictionaries",value:function(){var e=this.props,t=e.only,n=e.except;this._onlyDict=keyDictionary(t),this._exceptDict=keyDictionary(n)}},{key:"_shouldIgnoreEvent",value:function(e){var t=e.key;return isEmpty(this._onlyDict)?!!isEmpty(this._exceptDict)||!this._exceptDict[t]:isEmpty(this._exceptDict)?this._onlyDict[t]:this._onlyDict[t]&&!this._exceptDict[t]}},{key:"_handleKeyEvent",value:function(e){this._shouldIgnoreEvent(e)&&KeyEventManager.getInstance().ignoreEvent(e)}}]),n}(React.PureComponent),t.propTypes={only:PropTypes.oneOfType([PropTypes.string,PropTypes.arrayOf(PropTypes.string)]),except:PropTypes.oneOfType([PropTypes.string,PropTypes.arrayOf(PropTypes.string)])},n}function keyDictionary(e){return arrayFrom(e).reduce(function(e,t){var n=standardizeKeyName(t);if(!isValidKey(n))throw new InvalidKeyNameError(t);return[resolveAltShiftedAlias,resolveUnaltShiftedAlias,resolveShiftedAlias,resolveUnshiftedAlias,resolveAltedAlias,resolveUnaltedAlias].forEach(function(t){e[t(n)]=!0}),e},{})}var HotKeysIgnore=function(e){function t(){return classCallCheck(this,t),possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return inherits(t,e),createClass(t,[{key:"render",value:function(){var e=this.props,t=e.hotKeys,n=objectWithoutProperties(e,["hotKeys"]),o=n.component||Configuration.option("defaultComponent");return React__default.createElement(o,_extends({},t,n))}}]),t}(React.Component),HotKeysIgnore$1=withHotKeysIgnore(HotKeysIgnore),GlobalHotKeys=function(e){function t(){return classCallCheck(this,t),possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return inherits(t,e),createClass(t,[{key:"render",value:function(){return this.props.children||null}},{key:"componentDidUpdate",value:function(){if(this.props.allowChanges||!Configuration.option("ignoreKeymapAndHandlerChangesByDefault")){var e=this.props,t=e.keyMap,n=e.handlers;KeyEventManager.getInstance().updateGlobalHotKeys(this._id,t,n,this._getComponentOptions(),this._getEventOptions())}}},{key:"componentDidMount",value:function(){var e=this.props,t=e.keyMap,n=e.handlers;this._id=KeyEventManager.getInstance().addGlobalHotKeys(t,n,this._getComponentOptions(),this._getEventOptions())}},{key:"componentWillUnmount",value:function(){KeyEventManager.getInstance().removeGlobalHotKeys(this._id)}},{key:"_getComponentOptions",value:function(){return{defaultKeyEvent:Configuration.option("defaultKeyEvent")}}},{key:"_getEventOptions",value:function(){return{ignoreEventsCondition:Configuration.option("ignoreEventsCondition")}}}]),t}(React.Component);function configure(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Configuration.init(e)}GlobalHotKeys.propTypes={keyMap:PropTypes.object,handlers:PropTypes.object,onFocus:PropTypes.func,onBlur:PropTypes.func,allowChanges:PropTypes.bool},exports.HotKeys=HotKeys,exports.HotKeysIgnore=HotKeysIgnore$1,exports.withHotKeysIgnore=withHotKeysIgnore,exports.GlobalHotKeys=GlobalHotKeys,exports.withHotKeys=withHotKeys,exports.configure=configure;

@@ -7,6 +7,12 @@ 'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
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 _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _react = require('react');

@@ -16,8 +22,22 @@

var _HotKeys = require('./HotKeys');
var _Configuration = require('./lib/Configuration');
var _HotKeys2 = _interopRequireDefault(_HotKeys);
var _Configuration2 = _interopRequireDefault(_Configuration);
var _KeyEventManager = require('./lib/KeyEventManager');
var _KeyEventManager2 = _interopRequireDefault(_KeyEventManager);
var _isEmpty = require('./utils/collection/isEmpty');
var _isEmpty2 = _interopRequireDefault(_isEmpty);
var _KeyCombinationSerializer = require('./lib/KeyCombinationSerializer');
var _KeyCombinationSerializer2 = _interopRequireDefault(_KeyCombinationSerializer);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

@@ -30,91 +50,347 @@

/**
* withHotKeys is an HOC that provides the wrappedComponent with the ability to implement keyboard actions
* without the user wrapping every component with a <HotKeys> component individually
* Wraps a React component in a HotKeysEnabled component, which passes down the
* callbacks and options necessary for React Hotkeys to work as a single prop value,
* hotkeys. These must be unwrapped and applied to a DOM-mountable element within
* the wrapped component (e.g. div, span, input, etc) in order for the key events
* to be recorded.
*
* See examples/master/HOCWrappedNode.js for an example implementation
* Follow the steps below to use the HOC:
*
* @example <caption>Example usage of withHotKeys.</caption>
* // Returns the HOC-wrapped component.
* // 1. Declared a key map that with the actionName as key and keyboardKeys as values
* const ACTION_KEY_MAP = {
* 'logConsole' : 'down',
* };
*
* class BasicBox extends React.Component {
*
* // 2. declare 'hotKeyHandlers' within the Component's class definition
* hotKeyHandlers: {
* 'logConsole': this.logConsole.bind(this),
* }
*
* logConsole() {
* console.log('a hotkey is pressed');
* }
*
* render() {
* return (
* <div tabIndex="0">
* Press the down arrow
* </div>
* );
* }
* }
*
* // 3. Wrap the Component with withHotKeys
* export default withHotKeys(ACTION_KEY_MAP)(BasicBox);
* @returns {function} Returns the HOC-wrapped component.
*
* @param {Object} keyMap an action-to-keyboard-key mapping
* @summary An HOC that provides the wrappedComponent with the ability to implement keyboard actions
* @param {React.ComponentClass} Component - Component class to wrap
* @param {Object} hotKeysOptions - Options that become the wrapping component's
* default prop values
* @returns {React.ComponentClass} Wrapped component that is passed all of the React hotkeys
* props in a single value, hotkeys.
*/
var withHotKeys = function withHotKeys(keyMap) {
return function (Component) {
return function (_PureComponent) {
_inherits(HotKeysWrapper, _PureComponent);
function withHotKeys(Component) {
var _class, _temp;
function HotKeysWrapper(props) {
_classCallCheck(this, HotKeysWrapper);
var hotKeysOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _this = _possibleConstructorReturn(this, (HotKeysWrapper.__proto__ || Object.getPrototypeOf(HotKeysWrapper)).call(this, props));
function mergeWithOptions(key, props) {
return _extends({}, hotKeysOptions[key] || {}, props[key] || {});
}
_this._setRef = _this._setRef.bind(_this);
_this.state = {
handlers: {}
function getHandlers(props) {
return mergeWithOptions('handlers', props);
}
function getKeyMap(props) {
return mergeWithOptions('keyMap', props);
}
/**
* Component that listens to key events when one of its children are in focus and
* selectively triggers actions (that may be handled by handler functions) when a
* sequence of events matches a list of pre-defined sequences or combinations
*/
return _temp = _class = function (_PureComponent) {
_inherits(HotKeysEnabled, _PureComponent);
function HotKeysEnabled(props) {
_classCallCheck(this, HotKeysEnabled);
/**
* The focus and blur handlers need access to the current component as 'this'
* so they need to be bound to it when the component is instantiated
*/
var _this = _possibleConstructorReturn(this, (HotKeysEnabled.__proto__ || Object.getPrototypeOf(HotKeysEnabled)).call(this, props));
_this._handleFocus = _this._handleFocus.bind(_this);
_this._handleBlur = _this._handleBlur.bind(_this);
_this._handleKeyDown = _this._handleKeyDown.bind(_this);
_this._handleKeyPress = _this._handleKeyPress.bind(_this);
_this._handleKeyUp = _this._handleKeyUp.bind(_this);
_this._componentIsFocused = _this._componentIsFocused.bind(_this);
return _this;
}
_createClass(HotKeysEnabled, [{
key: 'render',
value: function render() {
var _props = this.props,
keyMap = _props.keyMap,
handlers = _props.handlers,
allowChanges = _props.allowChanges,
props = _objectWithoutProperties(_props, ['keyMap', 'handlers', 'allowChanges']);
var hotKeys = {
onFocus: this._wrapFunction('onFocus', this._handleFocus),
onBlur: this._wrapFunction('onBlur', this._handleBlur),
tabIndex: _Configuration2.default.option('defaultTabIndex')
};
return _this;
if (this._shouldBindKeyListeners()) {
hotKeys.onKeyDown = this._handleKeyDown;
hotKeys.onKeyPress = this._handleKeyPress;
hotKeys.onKeyUp = this._handleKeyUp;
}
return _react2.default.createElement(Component, _extends({
hotKeys: hotKeys
}, props));
}
}, {
key: '_shouldBindKeyListeners',
value: function _shouldBindKeyListeners() {
var keyMap = getKeyMap(this.props);
_createClass(HotKeysWrapper, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.setState({ handlers: this._ref.hotKeyHandlers });
return !(0, _isEmpty2.default)(keyMap) || _Configuration2.default.option('enableHardSequences') && this._handlersIncludeHardSequences(keyMap, getHandlers(this.props));
}
}, {
key: '_handlersIncludeHardSequences',
value: function _handlersIncludeHardSequences(keyMap, handlers) {
return Object.keys(handlers).some(function (action) {
return !keyMap[action] && _KeyCombinationSerializer2.default.isValidKeySerialization(action);
});
}
}, {
key: '_wrapFunction',
value: function _wrapFunction(propName, func) {
var _this2 = this;
if (typeof this.props[propName] === 'function') {
return function (event) {
_this2.props[propName](event);
func(event);
};
} else {
return func;
}
}, {
key: '_setRef',
value: function _setRef(node) {
this._ref = node;
}
}, {
key: '_focusTreeIdsPush',
value: function _focusTreeIdsPush(componentId) {
if (!this._focusTreeIds) {
this._focusTreeIds = [];
}
}, {
key: 'render',
value: function render() {
var handlers = this.state.handlers;
// Setting component as documentfragment to avoid unexpected stylistic changes to the wrapped component
this._focusTreeIds.push(componentId);
}
}, {
key: '_focusTreeIdsShift',
value: function _focusTreeIdsShift() {
if (this._focusTreeIds) {
this._focusTreeIds.shift();
}
}
}, {
key: '_getFocusTreeId',
value: function _getFocusTreeId() {
if (this._focusTreeIds) {
return this._focusTreeIds[0];
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(previousProps) {
if (this._componentIsFocused() && (this.props.allowChanges || !_Configuration2.default.option('ignoreKeymapAndHandlerChangesByDefault'))) {
var _props2 = this.props,
keyMap = _props2.keyMap,
handlers = _props2.handlers;
return _react2.default.createElement(
_HotKeys2.default,
{ component: 'document-fragment', keyMap: keyMap, handlers: handlers },
_react2.default.createElement(Component, _extends({
ref: this._setRef
}, this.props))
);
_KeyEventManager2.default.getInstance().updateHotKeys(this._getFocusTreeId(), this._componentId, keyMap, handlers, this._getComponentOptions());
}
}]);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._handleBlur();
}
}, {
key: '_componentIsFocused',
value: function _componentIsFocused() {
return this._focused === true;
}
return HotKeysWrapper;
}(_react.PureComponent);
};
};
/**
* Handles when the component gains focus by calling onFocus prop, if defined, and
* registering itself with the KeyEventManager
* @private
*/
}, {
key: '_handleFocus',
value: function _handleFocus() {
if (this.props.onFocus) {
var _props3;
(_props3 = this.props).onFocus.apply(_props3, arguments);
}
var _KeyEventManager$getI = _KeyEventManager2.default.getInstance().addHotKeys(getKeyMap(this.props), getHandlers(this.props), this._getComponentOptions()),
_KeyEventManager$getI2 = _slicedToArray(_KeyEventManager$getI, 2),
focusTreeId = _KeyEventManager$getI2[0],
componentId = _KeyEventManager$getI2[1];
this._componentId = componentId;
this._focusTreeIdsPush(focusTreeId);
this._focused = true;
}
/**
* Handles when the component loses focus by calling the onBlur prop, if defined
* and removing itself from the KeyEventManager
* @private
*/
}, {
key: '_handleBlur',
value: function _handleBlur() {
if (this.props.onBlur) {
var _props4;
(_props4 = this.props).onBlur.apply(_props4, arguments);
}
var retainCurrentFocusTreeId = _KeyEventManager2.default.getInstance().removeHotKeys(this._getFocusTreeId(), this._componentId);
if (!retainCurrentFocusTreeId) {
this._focusTreeIdsShift();
}
this._focused = false;
}
/**
* Delegates handing the keydown event to the KeyEventManager
* @param {KeyboardEvent} event Key board event containing key name and state
* @private
*/
}, {
key: '_handleKeyDown',
value: function _handleKeyDown(event) {
var discardFocusTreeId = _KeyEventManager2.default.getInstance().handleKeydown(event, this._getFocusTreeId(), this._componentId, this._getEventOptions());
if (discardFocusTreeId) {
this._focusTreeIdsShift();
}
}
/**
* Delegates handing the keypress event to the KeyEventManager
* @param {KeyboardEvent} event Key board event containing key name and state
* @private
*/
}, {
key: '_handleKeyPress',
value: function _handleKeyPress(event) {
var discardFocusTreeId = _KeyEventManager2.default.getInstance().handleKeypress(event, this._getFocusTreeId(), this._componentId, this._getEventOptions());
if (discardFocusTreeId) {
this._focusTreeIdsShift();
}
}
/**
* Delegates handing the keyup event to the KeyEventManager
* @param {KeyboardEvent} event Key board event containing key name and state
* @private
*/
}, {
key: '_handleKeyUp',
value: function _handleKeyUp(event) {
var discardFocusTreeId = _KeyEventManager2.default.getInstance().handleKeyup(event, this._getFocusTreeId(), this._componentId, this._getEventOptions());
if (discardFocusTreeId) {
this._focusTreeIdsShift();
}
}
}, {
key: '_getComponentOptions',
value: function _getComponentOptions() {
return {
defaultKeyEvent: _Configuration2.default.option('defaultKeyEvent')
};
}
}, {
key: '_getEventOptions',
value: function _getEventOptions() {
return {
ignoreEventsCondition: _Configuration2.default.option('ignoreEventsCondition')
};
}
}]);
return HotKeysEnabled;
}(_react.PureComponent), _class.propTypes = {
/**
* A unique key to associate with KeyEventMatchers that allows associating handler
* functions at a later stage
* @typedef {String} ActionName
*/
/**
* Name of a key event
* @typedef {'keyup'|'keydown'|'keypress'} KeyEventName
*/
/**
* A string or list of strings, that represent a sequence of one or more keys
* @typedef {String | Array.<String>} MouseTrapKeySequence
* @see {@link https://craig.is/killing/mice} for support key sequences
*/
/**
* Options for the mapping of a key sequence and event
* @typedef {Object} KeyEventOptions
* @property {MouseTrapKeySequence} sequence - The key sequence required to satisfy a
* KeyEventDescription
* @property {KeyEventName} action - The keyboard state required to satisfy a
* KeyEventDescription
*/
/**
* A description of key sequence of one or more key combinations
* @typedef {MouseTrapKeySequence|KeyMapOptions|Array<MouseTrapKeySequence>} KeyEventDescription
*/
/**
* A mapping from ActionName to KeyEventDescription
* @typedef {Object.<ActionName, KeyEventDescription>} KeyMap
*/
/**
* A map from action names to Mousetrap or Browser key sequences
* @type {KeyMap}
*/
keyMap: _propTypes2.default.object,
/**
* A map from action names to event handler functions
* @typedef {Object<ActionName, Function>} HandlersMap
*/
/**
* A map from action names to event handler functions
* @type {HandlersMap}
*/
handlers: _propTypes2.default.object,
/**
* Function to call when this component gains focus in the browser
* @type {Function}
*/
onFocus: _propTypes2.default.func,
/**
* Function to call when this component loses focus in the browser
* @type {Function}
*/
onBlur: _propTypes2.default.func,
/**
* Whether the keyMap or handlers are permitted to change after the
* component mounts. If false, changes to the keyMap and handlers
* props will be ignored
*/
allowChanges: _propTypes2.default.bool
}, _temp;
}
exports.default = withHotKeys;

@@ -13,457 +13,35 @@ var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

import PropTypes from 'prop-types';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import FocusTrap from './FocusTrap';
import Configuration from './lib/Configuration';
import withHotKeys from './withHotKeys';
import isBool from 'lodash.isboolean';
import isObject from 'lodash.isobject';
import isEqual from 'lodash.isequal';
import sequencesFromKeyMap from './utils/sequencesFromKeyMap';
import hasChanged from './utils/hasChanged';
/**
* A string or list of strings, that represent a sequence of one or more keys
* @typedef {String | Array.<String>} MouseTrapKeySequence
* @see {@link https://craig.is/killing/mice} for support key sequences
* @see HotKeysEnabled
*/
/**
* Name of a key event
* @typedef {'keyup'|'keydown'|'keypress'} KeyEventName
*/
var HotKeysWrapper = function (_Component) {
_inherits(HotKeysWrapper, _Component);
/**
* Options for the mapping of a key sequence and event
* @typedef {Object} KeyEventOptions
* @property {MouseTrapKeySequence} The key sequence required to satisfy a KeyEventMatcher
* @property {KeyEventName} action The keyboard state required to satisfy a KeyEventMatcher
*/
function HotKeysWrapper() {
_classCallCheck(this, HotKeysWrapper);
/**
* A matcher used on keyboard sequences and events to trigger handler functions
* when matching sequences occur
* @typedef {MouseTrapKeySequence | KeyMapOptions | Array<MouseTrapKeySequence>} KeyEventMatcher
*/
/**
* A unique key to associate with KeyEventMatchers that allows associating handler
* functions at a later stage
* @typedef {String} ActionName
*/
/**
* A mapping from ActionNames to KeyEventMatchers
* @typedef {Object.<String, KeyEventMatcher>} KeySequence
*/
/**
* Component that wraps it children in a "focus trap" and allows key events to
* trigger function handlers when its children are in focus
*/
var HotKeys = function (_Component) {
_inherits(HotKeys, _Component);
function HotKeys(props, context) {
_classCallCheck(this, HotKeys);
/**
* The focus and blur handlers need access to the current component as 'this'
* so they need to be bound to it when the component is instantiated
*/
var _this = _possibleConstructorReturn(this, (HotKeys.__proto__ || Object.getPrototypeOf(HotKeys)).call(this, props, context));
_this.onFocus = _this.onFocus.bind(_this);
_this.onBlur = _this.onBlur.bind(_this);
return _this;
return _possibleConstructorReturn(this, (HotKeysWrapper.__proto__ || Object.getPrototypeOf(HotKeysWrapper)).apply(this, arguments));
}
/**
* Constructs the context object that contains references to this component
* and its KeyMap so that they may be accessed by any descendant HotKeys
* components
* @returns {{hotKeyParent: HotKeys, hotKeyMap: KeySequence}} Child context object
*/
_createClass(HotKeys, [{
key: 'getChildContext',
value: function getChildContext() {
return {
hotKeyParent: this,
hotKeyMap: this.__hotKeyMap__
};
}
/**
* Sets this components KeyMap from its keyMap prop and the KeyMap of its
* ancestor KeyMap component (if one exists)
*/
}, {
key: 'componentWillMount',
value: function componentWillMount() {
this.updateMap();
}
/**
* Updates this component's KeyMap if either its own keyMap prop has changed
* or its ancestor's KeyMap has been update
*
* @returns {boolean} Whether the KeyMap was updated
*/
}, {
key: 'updateMap',
value: function updateMap() {
var newMap = this.buildMap();
if (!isEqual(newMap, this.__hotKeyMap__)) {
this.__hotKeyMap__ = newMap;
return true;
}
return false;
}
/**
* This component's KeyMap merged with that of its most direct ancestor that is a
* HotKeys component. This component's mappings take precedence over those defined
* in its ancestor.
* @returns {KeySequence} This component's KeyMap merged with its HotKeys ancestor's
*/
}, {
key: 'buildMap',
value: function buildMap() {
var parentMap = this.context.hotKeyMap || {};
var thisMap = this.props.keyMap || {};
/**
* TODO: This appears to only merge in the key maps of its most direct
* ancestor - what about grandparent components' KeyMap's?
*/
return _extends({}, parentMap, thisMap);
}
/**
* This component's KeyMap
* @returns {KeySequence} This component's KeyMap
*/
}, {
key: 'getMap',
value: function getMap() {
return this.__hotKeyMap__;
}
/**
* Imports mousetrap and stores a reference to it on the this component
*/
}, {
key: 'componentDidMount',
value: function componentDidMount() {
// import is here to support React's server rendering as Mousetrap immediately
// calls itself with window and it fails in Node environment
var Mousetrap = require('mousetrap');
/**
* TODO: Not optimal - imagine hundreds of this component. We need a top level
* delegation point for mousetrap
*/
this.__mousetrap__ = new Mousetrap(this.props.attach || ReactDOM.findDOMNode(this));
this.updateHotKeys(true);
}
/**
* Updates this component's KeyMap and synchronises the handlers across to
* Mousetrap after the component has been updated (passed new prop values)
* @param {Object} prevProps The props used on the component's last render
*/
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
this.updateHotKeys(false, prevProps);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(null);
}
if (this.__mousetrap__) {
this.__mousetrap__.reset();
}
}
/**
* Updates this component's KeyMap and synchronises the changes across
* to Mouestrap
* @param {Boolean} force Whether to force an update of the KeyMap and sync
* to Mousetrap, even if no relevant values appear to have changed
* since the last time
* @param {Object} prevProps The props used on the component's last render
*/
}, {
key: 'updateHotKeys',
value: function updateHotKeys() {
var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var prevProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _props$handlers = this.props.handlers,
handlers = _props$handlers === undefined ? {} : _props$handlers;
var _prevProps$handlers = prevProps.handlers,
prevHandlers = _prevProps$handlers === undefined ? handlers : _prevProps$handlers;
var keyMapHasChanged = this.updateMap();
if (force || keyMapHasChanged || hasChanged(handlers, prevHandlers)) {
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(null);
}
this.syncHandlersToMousetrap();
}
}
/**
* Synchronises the KeyMap and handlers applied to this component over to
* Mousetrap
*/
}, {
key: 'syncHandlersToMousetrap',
value: function syncHandlersToMousetrap() {
var _this2 = this;
var _props$handlers2 = this.props.handlers,
handlers = _props$handlers2 === undefined ? {} : _props$handlers2;
var hotKeyMap = this.getMap();
var sequenceHandlers = [];
var mousetrap = this.__mousetrap__;
// Group all our handlers by sequence
Object.keys(handlers).forEach(function (hotKey) {
var handler = handlers[hotKey];
var sequencesAsArray = sequencesFromKeyMap(hotKeyMap, hotKey);
/**
* TODO: Could be optimized as every handler will get called across every bound
* component - imagine making a node a focus point and then having hundreds!
*/
sequencesAsArray.forEach(function (sequence) {
var action = void 0;
var callback = function callback(event, sequence) {
/**
* Check we are actually in focus and that a child hasn't already
* handled this sequence
*/
var isFocused = isBool(_this2.props.focused) ? _this2.props.focused : _this2.__isFocused__;
if (isFocused && sequence !== _this2.__lastChildSequence__) {
if (_this2.context.hotKeyParent) {
_this2.context.hotKeyParent.childHandledSequence(sequence);
}
return handler(event, sequence);
}
};
if (isObject(sequence)) {
action = sequence.action;
sequence = sequence.sequence;
}
sequenceHandlers.push({ callback: callback, action: action, sequence: sequence });
});
});
/**
* TODO: Hard reset our handlers (probably could be more efficient)
*/
mousetrap.reset();
sequenceHandlers.forEach(function (_ref) {
var sequence = _ref.sequence,
callback = _ref.callback,
action = _ref.action;
return mousetrap.bind(sequence, callback, action);
});
}
/**
* Stores a reference to the last key sequence handled by the most direct
* descendant HotKeys component, and passes that sequence to its own most
* direct HotKeys ancestor for it to do the same.
*
* This reference is stored so that parent HotKeys components do not try
* to handle a sequence that has already been handled by one of its
* descendants.
*
* @param {KeyEventMatcher} sequence The sequence handled most recently by
* a child HotKeys component
*/
}, {
key: 'childHandledSequence',
value: function childHandledSequence() {
var sequence = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
this.__lastChildSequence__ = sequence;
/**
* Traverse up any hot key parents so everyone is aware a child has
* handled a certain sequence
*/
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(sequence);
}
}
/**
* Renders the component's children wrapped in a FocusTrap with the necessary
* props to capture keyboard events
*
* @returns {FocusTrap} FocusTrap with necessary props to capture keyboard events
*/
}, {
_createClass(HotKeysWrapper, [{
key: 'render',
value: function render() {
var _props = this.props,
keyMap = _props.keyMap,
handlers = _props.handlers,
focused = _props.focused,
attach = _props.attach,
children = _props.children,
props = _objectWithoutProperties(_props, ['keyMap', 'handlers', 'focused', 'attach', 'children']);
hotKeys = _props.hotKeys,
remainingProps = _objectWithoutProperties(_props, ['hotKeys']);
return React.createElement(
FocusTrap,
_extends({}, props, { onFocus: this.onFocus, onBlur: this.onBlur }),
children
);
}
var DefaultComponent = remainingProps.component || Configuration.option('defaultComponent');
/**
* Updates the internal focused state and calls the onFocus prop if it is
* defined
*/
}, {
key: 'onFocus',
value: function onFocus() {
this.__isFocused__ = true;
if (this.props.onFocus) {
var _props2;
(_props2 = this.props).onFocus.apply(_props2, arguments);
}
return React.createElement(DefaultComponent, _extends({}, hotKeys, remainingProps));
}
/**
* Updates the internal focused state and calls the onBlur prop if it is
* defined.
*
* Also registers a null sequence as being handled by this component with
* its ancestor HotKeys.
*/
}, {
key: 'onBlur',
value: function onBlur() {
this.__isFocused__ = false;
if (this.props.onBlur) {
var _props3;
(_props3 = this.props).onBlur.apply(_props3, arguments);
}
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(null);
}
}
}]);
return HotKeys;
return HotKeysWrapper;
}(Component);
HotKeys.propTypes = {
/**
* A map from action names to Mousetrap key sequences
*/
keyMap: PropTypes.object,
/**
* A map from action names to event handler functions
*/
handlers: PropTypes.object,
/**
* Whether HotKeys should behave as if it has focus in the browser,
* whether it does or not - a way to force focus behaviour
*/
focused: PropTypes.bool,
/**
* The DOM element the keyboard listeners should be attached to
*/
attach: PropTypes.any,
/**
* Children to wrap within a focus trap
*/
children: PropTypes.node,
/**
* Function to call when this component gains focus in the browser
*/
onFocus: PropTypes.func,
/**
* Function to call when this component loses focus in the browser
*/
onBlur: PropTypes.func
};
HotKeys.childContextTypes = {
/**
* Reference to this instance of HotKeys so that any descendents are aware
* that they are being rendered within another HotKeys component
*/
hotKeyParent: PropTypes.any,
/**
* Reference to this instance's KeyMap so that any descendents may merge it
* into its own
*/
hotKeyMap: PropTypes.object
};
HotKeys.contextTypes = {
/**
* Reference to the most direct ancestor that is a HotKeys component (if one
* exists) so that messages may be passed to it when necessary
*/
hotKeyParent: PropTypes.any,
/**
* Reference to the KeyMap of its most direct HotKeys ancestor, so that it may
* be merged into this components
*/
hotKeyMap: PropTypes.object
};
export default HotKeys;
export default withHotKeys(HotKeysWrapper);
export { default as HotKeys } from './HotKeys';
export { default as HotKeysIgnore } from './HotKeysIgnore';
export { default as withHotKeysIgnore } from './withHotKeysIgnore';
export { default as GlobalHotKeys } from './GlobalHotKeys';
export { default as withHotKeys } from './withHotKeys';
export { default as FocusTrap } from './FocusTrap';
export { default as HotKeyMapMixin } from './HotKeyMapMixin';
export { default as configure } from './configure';

@@ -9,4 +9,6 @@ /**

* 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.
*
* PLEASE NOTE: SOURCE CODE FOUND IN THE lib/vendor DIRECTORY IS UNDER THE MIT LICENSE - PLEASE SEE THE LICENSE FILE FOR EACH DIRECTORY FOR MORE INFORMATION
*/
import PropTypes from"prop-types";import React,{Component,PureComponent}from"react";import isEqual from"lodash.isequal";import ReactDOM from"react-dom";import isBool from"lodash.isboolean";import isObject from"lodash.isobject";var classCallCheck=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},createClass=function(){function e(e,t){for(var o=0;o<t.length;o++){var n=t[o];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,o,n){return o&&e(t.prototype,o),n&&e(t,n),t}}(),_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var o=arguments[t];for(var n in o)Object.prototype.hasOwnProperty.call(o,n)&&(e[n]=o[n])}return e},inherits=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},objectWithoutProperties=function(e,t){var o={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(o[n]=e[n]);return o},possibleConstructorReturn=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},FocusTrap=function(e){function t(){return classCallCheck(this,t),possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return inherits(t,Component),createClass(t,[{key:"render",value:function(){var e=this.props,t=e.component,o=e.children,n=objectWithoutProperties(e,["component","children"]);return React.createElement(t,_extends({tabIndex:"-1"},n),o)}}]),t}();function sequencesFromKeyMap(e,t){var o=e[t];return o?Array.isArray(o)?o:[o]:[t]}function hasChanged(e,t){return!isEqual(e,t)}FocusTrap.propTypes={onFocus:PropTypes.func,onBlur:PropTypes.func,component:PropTypes.oneOfType([PropTypes.func,PropTypes.string]),children:PropTypes.node},FocusTrap.defaultProps={component:"div"};var HotKeys=function(e){function t(e,o){classCallCheck(this,t);var n=possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,o));return n.onFocus=n.onFocus.bind(n),n.onBlur=n.onBlur.bind(n),n}return inherits(t,Component),createClass(t,[{key:"getChildContext",value:function(){return{hotKeyParent:this,hotKeyMap:this.__hotKeyMap__}}},{key:"componentWillMount",value:function(){this.updateMap()}},{key:"updateMap",value:function(){var e=this.buildMap();return!isEqual(e,this.__hotKeyMap__)&&(this.__hotKeyMap__=e,!0)}},{key:"buildMap",value:function(){var e=this.context.hotKeyMap||{},t=this.props.keyMap||{};return _extends({},e,t)}},{key:"getMap",value:function(){return this.__hotKeyMap__}},{key:"componentDidMount",value:function(){var e=require("mousetrap");this.__mousetrap__=new e(this.props.attach||ReactDOM.findDOMNode(this)),this.updateHotKeys(!0)}},{key:"componentDidUpdate",value:function(e){this.updateHotKeys(!1,e)}},{key:"componentWillUnmount",value:function(){this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(null),this.__mousetrap__&&this.__mousetrap__.reset()}},{key:"updateHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=this.props.handlers,n=void 0===o?{}:o,r=t.handlers,s=void 0===r?n:r,a=this.updateMap();(e||a||hasChanged(n,s))&&(this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(null),this.syncHandlersToMousetrap())}},{key:"syncHandlersToMousetrap",value:function(){var e=this,t=this.props.handlers,o=void 0===t?{}:t,n=this.getMap(),r=[],s=this.__mousetrap__;Object.keys(o).forEach(function(t){var s=o[t];sequencesFromKeyMap(n,t).forEach(function(t){var o=void 0;isObject(t)&&(o=t.action,t=t.sequence),r.push({callback:function(t,o){if((isBool(e.props.focused)?e.props.focused:e.__isFocused__)&&o!==e.__lastChildSequence__)return e.context.hotKeyParent&&e.context.hotKeyParent.childHandledSequence(o),s(t,o)},action:o,sequence:t})})}),s.reset(),r.forEach(function(e){var t=e.sequence,o=e.callback,n=e.action;return s.bind(t,o,n)})}},{key:"childHandledSequence",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;this.__lastChildSequence__=e,this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(e)}},{key:"render",value:function(){var e=this.props,t=(e.keyMap,e.handlers,e.focused,e.attach,e.children),o=objectWithoutProperties(e,["keyMap","handlers","focused","attach","children"]);return React.createElement(FocusTrap,_extends({},o,{onFocus:this.onFocus,onBlur:this.onBlur}),t)}},{key:"onFocus",value:function(){var e;(this.__isFocused__=!0,this.props.onFocus)&&(e=this.props).onFocus.apply(e,arguments)}},{key:"onBlur",value:function(){var e;(this.__isFocused__=!1,this.props.onBlur)&&(e=this.props).onBlur.apply(e,arguments);this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(null)}}]),t}();HotKeys.propTypes={keyMap:PropTypes.object,handlers:PropTypes.object,focused:PropTypes.bool,attach:PropTypes.any,children:PropTypes.node,onFocus:PropTypes.func,onBlur:PropTypes.func},HotKeys.childContextTypes={hotKeyParent:PropTypes.any,hotKeyMap:PropTypes.object},HotKeys.contextTypes={hotKeyParent:PropTypes.any,hotKeyMap:PropTypes.object};var withHotKeys=function(e){return function(t){return function(o){function n(e){classCallCheck(this,n);var t=possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t._setRef=t._setRef.bind(t),t.state={handlers:{}},t}return inherits(n,PureComponent),createClass(n,[{key:"componentDidMount",value:function(){this.setState({handlers:this._ref.hotKeyHandlers})}},{key:"_setRef",value:function(e){this._ref=e}},{key:"render",value:function(){var o=this.state.handlers;return React.createElement(HotKeys,{component:"document-fragment",keyMap:e,handlers:o},React.createElement(t,_extends({ref:this._setRef},this.props)))}}]),n}()}};function HotKeyMapMixin(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{contextTypes:{hotKeyMap:PropTypes.object},childContextTypes:{hotKeyMap:PropTypes.object},getChildContext:function(){return{hotKeyMap:this.__hotKeyMap__}},componentWillMount:function(){this.updateMap()},updateMap:function(){var e=this.buildMap();return!isEqual(e,this.__hotKeyMap__)&&(this.__hotKeyMap__=e,!0)},buildMap:function(){var t=this.context.hotKeyMap||{},o=this.props.keyMap||{};return _extends({},t,e,o)},getMap:function(){return this.__hotKeyMap__}}}export{HotKeys,withHotKeys,FocusTrap,HotKeyMapMixin};
import PropTypes from"prop-types";import React,{PureComponent,Component}from"react";function dictionaryFrom(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return e.reduce(function(e,n){return e[n]=t||{value:n},e},{})}var _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},classCallCheck=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},createClass=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),defineProperty=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},_extends=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},get=function e(t,n,o){null===t&&(t=Function.prototype);var i=Object.getOwnPropertyDescriptor(t,n);if(void 0===i){var r=Object.getPrototypeOf(t);return null===r?void 0:e(r,n,o)}if("value"in i)return i.value;var s=i.get;return void 0!==s?s.call(o):void 0},inherits=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},objectWithoutProperties=function(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n},possibleConstructorReturn=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},slicedToArray=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var n=[],o=!0,i=!1,r=void 0;try{for(var s,a=e[Symbol.iterator]();!(o=(s=a.next()).done)&&(n.push(s.value),!t||n.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{!o&&a.return&&a.return()}finally{if(i)throw r}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),toConsumableArray=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)},_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},simulateMissingKeyPressEvents:!0,stopEventPropagationAfterHandling:!0,stopEventPropagationAfterIgnoring:!0},_configuration=_extends({},_defaultConfiguration);_configuration._ignoreTagsDict=dictionaryFrom(_configuration.ignoreTags,!0);var Configuration=function(){function e(){classCallCheck(this,e)}return createClass(e,null,[{key:"init",value:function(e){var t=this;e.ignoreTags&&(e._ignoreTagsDict=dictionaryFrom(e.ignoreTags)),-1!==["verbose","debug","info"].indexOf(e.logLevel)&&console.warn("React HotKeys: You have requested log level '"+e.logLevel+"' but for performance reasons, logging below severity level 'warning' is disabled in production. Please use the development build for complete logs."),Object.keys(e).forEach(function(n){t.set(n,e[n])})}},{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 e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"warn";classCallCheck(this,e),this.verbose=this.noop,this.debug=this.noop,this.info=this.noop,this.warn=this.noop,this.error=this.noop,this.logLevel=this.constructor.levels[n],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(e,[{key:"noop",value:function(){}}]),e}();function isUndefined(e){return void 0===e}Logger.logIcons=["📕","📗","📘","📙"],Logger.componentIcons=["🔺","⭐️","🔷","🔶","⬛️"],Logger.eventIcons=["❤️","💚","💙","💛","💜","🧡"],Logger.levels={none:0,error:1,warn:2,info:3,debug:4,verbose:5};var KeyEventBitmapManager=function(){function e(){classCallCheck(this,e)}return createClass(e,null,[{key:"newBitmap",value:function(e){var t=[!1,!1,!1];if(!isUndefined(e))for(var n=0;n<=e;n++)t[n]=!0;return t}},{key:"setBit",value:function(e,t){return e[t]=!0,e}},{key:"clone",value:function(e){for(var t=this.newBitmap(),n=0;n<e.length;n++)t[n]=e[n];return t}},{key:"and",value:function(e,t){for(var n=[],o=0;o<e.length;o++)n[o]=e[o]&t[o];return n}}]),e}(),KeyEventBitmapIndex={keydown:0,keypress:1,keyup:2},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(e){return Object.keys(e).reduce(function(t,n){return e[n].forEach(function(e){hasKey(t,e)||(t[e]=[]),t[e].push(n)}),t},{})}var UnshiftedKeysDictionary=invertArrayDictionary(ShiftedKeysDictionary);function resolveUnshiftedAlias(e){return UnshiftedKeysDictionary[e]||[1===e.length?e.toLowerCase():e]}var KeyAliasesDictionary={Backspace:["Delete"]};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:"Backspace",command:"Meta",option:"Alt",enter:"Enter",backspace:"Backspace",ins:"Insert",pageup:"PageUp",pagedown:"PageDown",end:"End",home:"Home",contextmenu:"ContextMenu",numlock:"Clear"};function standardizeKeyName(e){return MousetrapToReactKeyNamesDictionary[e.toLowerCase()]||(e.match(/^f\d+$/)?e.toUpperCase():e)}var SpecialKeysDictionary={Shift:!0,Control:!0,Alt:!0,Meta:!0,Enter:!0,Tab:!0,CapsLock:!0,BackSpace:!0};function isSpecialKey(e){return!!SpecialKeysDictionary[e]}function isValidKey(e){return isSpecialKey(e)||String.fromCharCode(e.charCodeAt(0))===e}var InvalidKeyNameError=function(e){function t(){return classCallCheck(this,t),possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return inherits(t,e),t}(Error);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 t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=stripSuperfluousWhitespace(e).split(" ");try{var o=n.slice(0,n.length-1),i=n[n.length-1],r=o.map(function(e){var n=parseCombination(e,t);return normalizedCombinationId(Object.keys(n))}).join(" "),s=parseCombination(i,t),a={id:normalizedCombinationId(Object.keys(s)),keyDictionary:s,eventBitmapIndex:t.eventBitmapIndex,size:Object.keys(s).length};return{sequence:{prefix:r,size:o.length+1},combination:a}}catch(e){return{sequence:null,combination:null}}}}]),e}();function parseCombination(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e.replace(/^\+|(\s|[^+]\+)\+/,"$1plus").split("+").reduce(function(e,n){var o=standardizeKeyName(n);if(t.ensureValidKeys&&!isValidKey(o))throw new InvalidKeyNameError;return e[o]=!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 t=e.Shift,n=e.Alt,o={};return Object.keys(e).sort().forEach(function(e){var i=[];if(t)if(n){var r=resolveUnaltShiftedAlias(e),s=resolveAltShiftedAlias(e);i=[].concat(toConsumableArray(i),[e],toConsumableArray(r),toConsumableArray(s))}else{var a=resolveUnshiftedAlias(e),u=resolveShiftedAlias(e);i=[].concat(toConsumableArray(i),[e],toConsumableArray(a),toConsumableArray(u))}else if(n){var l=resolveUnaltedAlias(e),c=resolveAltedAlias(e);i=[].concat(toConsumableArray(i),[e],toConsumableArray(l),toConsumableArray(c))}else{i.push(e);var y=KeyAliasesDictionary[e];y&&(i=[].concat(toConsumableArray(i),toConsumableArray(y)))}var h=Object.keys(o);h.length>0?h.forEach(function(e){i.forEach(function(t){o[e+"+"+t]=_extends({},o[e],defineProperty({},t,!0))}),delete o[e]}):i.forEach(function(e){o[e]=defineProperty({},e,!0)})}),Object.values(o).map(function(e){return Object.keys(e).sort().join("+")})}},{key:"isValidKeySerialization",value:function(e){return e.length>0&&!!KeySequenceParser.parse(e,{ensureValidKeys:!0}).combination}}]),e}();function arrayFrom(e){return Array.isArray(e)?e:e?[e]:[]}function indexFromEnd(e,t){return e[e.length-(t+1)]}function isObject(e){return!Array.isArray(e)&&"object"===(void 0===e?"undefined":_typeof(e))&&null!==e}function isEmpty(e){return isObject(e)?0===Object.keys(e).length:!e||0===e.length}function describeKeyEvent(e){switch(parseInt(e,10)){case 0:return"keydown";case 1:return"keypress";default:return"keyup"}}var KeyEventSequenceIndex={previous:0,current:1};function resolveKeyAlias(e){return KeyAliasesDictionary[e]||[e]}for(var ModifierFlagsDictionary={Shift:["shiftKey"],Meta:["metaKey"],Control:["ctrlKey"],Alt:["altKey"]},AbstractKeyEventStrategy=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];classCallCheck(this,e),this.logger=t.logger||new Logger("warn"),this.componentId=0,this.keyEventManager=n,this._reset(),this._resetKeyCombinationHistory()}return createClass(e,[{key:"_reset",value:function(){this._resetRegisteredKeyMapsState(),this._resetHandlerResolutionState()}},{key:"_resetRegisteredKeyMapsState",value:function(){this.componentList=[],this.longestSequence=1,this.longestSequenceComponentIndex=null,this.keyMapEventBitmap=KeyEventBitmapManager.newBitmap()}},{key:"_resetHandlerResolutionState",value:function(){this.keyMaps=null,this.handlerResolutionSearchIndex=0,this.unmatchedHandlerStatus=null,this.handlersDictionary={},this.keySequencesDictionary={}}},{key:"_resetKeyCombinationHistory",value:function(){if(this.keyCombinationIncludesKeyUp=!1,this.keypressEventsToSimulate=[],!this.keyCombinationHistory||this.keyCombinationHistory.length<1)this.keyCombinationHistory=[];else{var e=this._getCurrentKeyCombination(),t=Object.keys(e.keys).reduce(function(t,n){var o=e.keys[n],i=o[KeyEventSequenceIndex.current];return i[KeyEventBitmapIndex.keydown]&&!i[KeyEventBitmapIndex.keyup]&&(t[n]=o),t},{});this.keyCombinationHistory=[{keys:t,ids:KeyCombinationSerializer.serialize(t)}]}}},{key:"_addComponentToList",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=this._buildComponentOptions(e,t,n,o);return this.componentList.push(i),i}},{key:"_buildComponentOptions",value:function(e,t,n,o){var i=this._applyHardSequences(t,n),r=i.keyMap,s=i.handlers;return{actions:this._buildActionDictionary(_extends({},t,r),o,e),handlers:s,componentId:e,options:o}}},{key:"_applyHardSequences",value:function(e,t){return Configuration.option("enableHardSequences")?Object.keys(t).reduce(function(n,o){return!!!e[o]&&KeyCombinationSerializer.isValidKeySerialization(o)&&(n.keyMap[o]=o),n.handlers[o]=t[o],n},{keyMap:{},handlers:{}}):{keyMap:e,handlers:t}}},{key:"_buildActionDictionary",value:function(e,t,n){var o=this;return Object.keys(e).reduce(function(i,r){return arrayFrom(e[r]).forEach(function(e){var s=function(){if(isObject(e)){var n=e.sequence,o=e.action;return{keySequence:n,eventBitmapIndex:isUndefined(o)?KeyEventBitmapIndex[t.defaultKeyEvent]:KeyEventBitmapIndex[o]}}return{keySequence:e,eventBitmapIndex:KeyEventBitmapIndex[t.defaultKeyEvent]}}(),a=s.keySequence,u=s.eventBitmapIndex,l=KeySequenceParser.parse(a,{eventBitmapIndex:u}),c=l.sequence,y=l.combination;c.size>o.longestSequence&&(o.longestSequence=c.size,o.longestSequenceComponentIndex=n),KeyEventBitmapManager.setBit(o.keyMapEventBitmap,u),i[r]||(i[r]=[]),i[r].push(_extends({prefix:c.prefix,actionName:r,sequenceLength:c.size},y))}),i},{})}},{key:"_getCurrentKeyCombination",value:function(){return this.keyCombinationHistory.length>0?this.keyCombinationHistory[this.keyCombinationHistory.length-1]:{keys:{},ids:[""],keyAliases:{}}}},{key:"_addToCurrentKeyCombination",value:function(e,t){0===this.keyCombinationHistory.length&&this.keyCombinationHistory.push({keys:{},ids:[""],keyAliases:{}});var n=this._getCurrentKeyCombination(),o=this._getKeyAlias(n,e),i=this._getKeyState(n,e);n.keys[o]=i?[KeyEventBitmapManager.clone(i[1]),KeyEventBitmapManager.newBitmap(t)]:[KeyEventBitmapManager.newBitmap(),KeyEventBitmapManager.newBitmap(t)],n.ids=KeyCombinationSerializer.serialize(n.keys),n.keyAliases=this._buildCombinationKeyAliases(n.keys),t===KeyEventBitmapIndex.keyup&&(this.keyCombinationIncludesKeyUp=!0)}},{key:"_startNewKeyCombination",value:function(e,t){this.keyCombinationHistory.length>this.longestSequence&&this.keyCombinationHistory.shift();var n=this._getCurrentKeyCombination(),o=_extends({},this._withoutKeyUps(n),defineProperty({},e,[KeyEventBitmapManager.newBitmap(),KeyEventBitmapManager.newBitmap(t)]));this.keyCombinationHistory.push({keys:o,ids:KeyCombinationSerializer.serialize(o),keyAliases:this._buildCombinationKeyAliases(o)}),this.keyCombinationIncludesKeyUp=!1}},{key:"_withoutKeyUps",value:function(e){return Object.keys(e.keys).reduce(function(t,n){var o=e.keys[n];return o[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keyup]||(t[n]=o),t},{})}},{key:"_callMatchingHandlerClosestToEventTarget",value:function(e,t,n,o,i){var r=this;for(this.keyMaps&&this.unmatchedHandlerStatus||(this.keyMaps=[],this.unmatchedHandlerStatus=[],this.componentList.forEach(function(e){var t=e.handlers;r.unmatchedHandlerStatus.push([Object.keys(t).length,{}]),r.keyMaps.push({})}));i<=o;){var s=this.unmatchedHandlerStatus[i][0];if(s>0)for(var a=function(){var e=r.componentList[r.handlerResolutionSearchIndex],t=e.handlers,n=e.actions;Object.keys(t).forEach(function(e){r.handlersDictionary[e]||(r.handlersDictionary[e]=[]),r.handlersDictionary[e].push(r.handlerResolutionSearchIndex)}),Object.keys(n).forEach(function(e){var t=r.handlersDictionary[e];if(t){var o=t[0],i=r.componentList[o].handlers[e],s=r.keyMaps[o];s.sequences||(s.sequences={}),n[e].forEach(function(e){var t=[e.prefix,e.id].join(" ");if(!(r.keySequencesDictionary[t]&&r.keySequencesDictionary[t].some(function(t){return t[1]===e.eventBitmapIndex}))){s.sequences[e.prefix]||(s.sequences[e.prefix]={combinations:{}});var n=e.prefix,a=e.sequenceLength,u=e.id,l=e.keyDictionary,c=e.size,y=e.eventBitmapIndex,h=e.actionName,p=s.sequences[e.prefix].combinations[e.id];s.sequences[e.prefix].combinations[e.id]=p?_extends({},p,{events:_extends({},p.events,defineProperty({},y,{actionName:h,eventBitmapIndex:y,handler:i}))}):{prefix:n,sequenceLength:a,id:u,keyDictionary:l,size:c,events:defineProperty({},y,{actionName:h,eventBitmapIndex:y,handler:i})},s.eventBitmap||(s.eventBitmap=KeyEventBitmapManager.newBitmap()),KeyEventBitmapManager.setBit(s.eventBitmap,e.eventBitmapIndex),(!s.longestSequence||s.longestSequence<e.sequenceLength)&&(s.longestSequence=e.sequenceLength),r.keySequencesDictionary[t]||(r.keySequencesDictionary[t]=[]),r.keySequencesDictionary[t].push([o,e.eventBitmapIndex])}}),t.forEach(function(t){var n=r.unmatchedHandlerStatus[t];n[1][e]||(n[1][e]=!0,n[0]--)})}}),r.handlerResolutionSearchIndex++};this.handlerResolutionSearchIndex<this.componentList.length&&s>0;)a();var u=this.keyMaps[i];if(u&&!isEmpty(u.sequences)&&u.eventBitmap[n])for(var l=u.sequences,c=u.longestSequence,y=this._getCurrentKeyCombination(),h=this._getKeyAlias(y,t),p=c;p>=0;){var d=this.keyCombinationHistory.slice(-p,-1).map(function(e){return e.ids}),v=this._tryMatchSequenceWithKeyAliases(l,d);if(v){v.order||function(){var e=Object.values(v.combinations).reduce(function(e,t){var n=t.id,o=t.size;return e[o]||(e[o]=[]),e[o].push(n),e},{});v.order=Object.keys(e).sort(function(e,t){return t-e}).reduce(function(t,n){return t.concat(e[n])},[])}();for(var f=v.order,g=0;g<f.length;){var m=f[g],_=v.combinations[m];if(this._combinationMatchesKeys(h,y,_,n)){KeyCombinationSerializer.serialize(_.keyDictionary);return _.events[n].handler(e),this._stopEventPropagationAfterHandlingIfEnabled(e,i),!0}g++}}p--}else;i++}}},{key:"_stopEventPropagationAfterHandlingIfEnabled",value:function(e,t){return!!Configuration.option("stopEventPropagationAfterHandling")&&(this._stopEventPropagation(e,t),!0)}},{key:"_stopEventPropagationAfterIgnoringIfEnabled",value:function(e,t){return!!Configuration.option("stopEventPropagationAfterIgnoring")&&(this._stopEventPropagation(e,t),!0)}},{key:"_stopEventPropagation",value:function(e,t){e.stopPropagation()}},{key:"_describeCurrentKeyCombination",value:function(){return this._getCurrentKeyCombination().ids[0]}},{key:"_tryMatchSequenceWithKeyAliases",value:function(e,t){if(0===t.length)return e[""];for(var n=t.map(function(e){return e.length}),o=t.map(function(){return 0}),i=!1;!i;){var r=o.map(function(e,n){return t[n][e]}).join(" ");if(e[r])return e[r];for(var s=0,a=!0;a&&s<o.length;){var u=(indexFromEnd(o,s)+1)%(indexFromEnd(n,s)||1);o[o.length-(s+1)]=u,(a=0===u)&&s++}i=s===o.length}}},{key:"_combinationMatchesKeys",value:function(e,t,n,o){var i=this;if(!n.events[o])return!1;var r=!1;return!Object.keys(n.keyDictionary).some(function(n){var s=i._getKeyState(t,n);return!s||(!i._keyIsCurrentlyTriggeringEvent(s,o)||(e&&e===i._getKeyAlias(t,n)&&(r=!i._keyAlreadyTriggeredEvent(s,o)),!1))})&&r}},{key:"_checkForModifierFlagDiscrepancies",value:function(e){var t=this;Object.keys(ModifierFlagsDictionary).forEach(function(n){var o=t._getCurrentKeyState(n),i=o&&!t._keyIsCurrentlyTriggeringEvent(o,KeyEventBitmapIndex.keyup);ModifierFlagsDictionary[n].forEach(function(o){!1===e[o]&&i&&t._addToCurrentKeyCombination(n,KeyEventBitmapIndex.keyup)})})}},{key:"_keyIsCurrentlyTriggeringEvent",value:function(e,t){return e&&e[KeyEventSequenceIndex.current][t]}},{key:"_keyAlreadyTriggeredEvent",value:function(e,t){return e&&e[KeyEventSequenceIndex.previous][t]}},{key:"_getCurrentKeyState",value:function(e){var t=this._getCurrentKeyCombination();return this._getKeyState(t,e)}},{key:"_getKeyState",value:function(e,t){var n=e.keys[t];if(n)return n;var o=e.keyAliases[t];return o?e.keys[o]:void 0}},{key:"_getKeyAlias",value:function(e,t){if(e.keys[t])return t;var n=e.keyAliases[t];return n||t}},{key:"_buildCombinationKeyAliases",value:function(e){var t=function(){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]}();return Object.keys(e).reduce(function(e,n){return resolveKeyAlias(n).forEach(function(o){t.forEach(function(t){t(o).forEach(function(t){t===n&&n===o||(e[t]=n)})})}),e},{})}}]),e}(),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}(),KeysWithoutPressEventDictionary={Shift:!0,Control:!0,Alt:!0,Meta:!0,Enter:!0,Tab:!0,BackSpace:!0,ArrowRight:!0,ArrowLeft:!0,ArrowUp:!0,ArrowDown:!0,CapsLock:!0},i=1;i<13;i++)KeysWithoutPressEventDictionary["F"+i]=!0;function hasKeyPressEvent(e){return!KeysWithoutPressEventDictionary[e]}function normalizeKeyName(e){return"+"===e?"plus":e}var FocusOnlyKeyEventStrategy=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];classCallCheck(this,t);var o=possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o.focusTreeId=0,o.currentEvent={key:null,type:null,handled:!1},o}return inherits(t,AbstractKeyEventStrategy),createClass(t,[{key:"_reset",value:function(){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_reset",this).call(this),this.componentId=0,this.focusTreeId+=1,this._clearEventPropagationState()}},{key:"_clearEventPropagationState",value:function(){this.eventPropagationState={previousComponentIndex:-1,actionHandled:!1,ignoreEvent:!1}}},{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];return(this.resetOnNextFocus||this.keyMaps)&&(this._reset(),this.resetOnNextFocus=!1),this.componentId=this.componentList.length,this._addComponentToList(this.componentId,e,t,n),[this.focusTreeId,this.componentId]}},{key:"updateHotKeys",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments[4];e===this.focusTreeId&&this.componentList[t]&&(this.componentList[t]=this._buildComponentOptions(t,n,o,i))}},{key:"removeHotKeys",value:function(e,t){return this.resetOnNextFocus||(this.resetOnNextFocus=!0),this.eventPropagationState.previousComponentIndex+1<t}},{key:"handleKeydown",value:function(e,t,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=normalizeKeyName(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())return this._ignoreEvent(e,n),!1;if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,KeyEventBitmapIndex.keydown),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return this._ignoreEvent(e,n),!1;this._checkForModifierFlagDiscrepancies(e),!!this._getCurrentKeyState(i)||this.keyCombinationIncludesKeyUp?this._startNewKeyCombination(i,KeyEventBitmapIndex.keydown,t,n):this._addToCurrentKeyCombination(i,KeyEventBitmapIndex.keydown,t,n)}return this._callHandlerIfActionNotHandled(e,i,KeyEventBitmapIndex.keydown,n,t),!hasKeyPressEvent(i)&&Configuration.option("simulateMissingKeyPressEvents")&&(e.persist(),this.keypressEventsToSimulate.push({event:e,focusTreeId:t,componentId:n,options:o,key:i})),this._isFocusTreeRoot(n)&&(this.keyEventManager.isGlobalListenersBound()||this.simulatePendingKeyPressEvents(i)),this._updateEventPropagationHistory(n),!1}},{key:"simulatePendingKeyPressEvents",value:function(){var e=this;this.keypressEventsToSimulate.length>0&&KeyEventCounter.incrementId(),this.keypressEventsToSimulate.forEach(function(t){var n=t.event,o=t.focusTreeId,i=t.componentId,r=t.options;e.handleKeypress(n,o,i,r)}),this.keypressEventsToSimulate=[],this._clearEventPropagationState()}},{key:"handleKeypress",value:function(e,t,n,o){var i=normalizeKeyName(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())this._ignoreEvent(e,n);else{if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,KeyEventBitmapIndex.keypress),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return void this._ignoreEvent(e,n);var r=this._getCurrentKeyState(i);r&&(r[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keypress]||r[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keyup])?this._startNewKeyCombination(i,KeyEventBitmapIndex.keypres,t,n):this._addToCurrentKeyCombination(i,KeyEventBitmapIndex.keypress,t,n)}this._callHandlerIfActionNotHandled(e,i,KeyEventBitmapIndex.keypress,n,t),this._updateEventPropagationHistory(n)}}},{key:"handleKeyup",value:function(e,t,n,o){var i=normalizeKeyName(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())this._ignoreEvent(e,n);else{if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,KeyEventBitmapIndex.keyup),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return void this._ignoreEvent(e,n);var r=this._getCurrentKeyState(i);r&&r[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keyup]?this._startNewKeyCombination(i,KeyEventBitmapIndex.keyup,t,n):this._addToCurrentKeyCombination(i,KeyEventBitmapIndex.keyup,t,n)}this._callHandlerIfActionNotHandled(e,i,KeyEventBitmapIndex.keyup,n,t),this._updateEventPropagationHistory(n)}}},{key:"_ignoreEvent",value:function(e,t){this._stopEventPropagationAfterIgnoringIfEnabled(e,t)?this._updateEventPropagationHistory(t,{forceReset:!0}):this._updateEventPropagationHistory(t)}},{key:"_alreadyEstablishedShouldIgnoreEvent",value:function(){return this.eventPropagationState.ignoreEvent}},{key:"_isNewKeyEvent",value:function(e){var t=this.eventPropagationState.previousComponentIndex;return-1===t||t>=e}},{key:"_updateEventPropagationHistory",value:function(e){(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{forceReset:!1}).forceReset||this._isFocusTreeRoot(e)?this._clearEventPropagationState():this.eventPropagationState.previousComponentIndex=e}},{key:"_setIgnoreEventFlag",value:function(e,t){this.eventPropagationState.ignoreEvent=t.ignoreEventsCondition(e)}},{key:"ignoreEvent",value:function(e){this.eventPropagationState.ignoreEvent=!0}},{key:"_isFocusTreeRoot",value:function(e){return e>=this.componentList.length-1}},{key:"_setNewEventParameters",value:function(e,t){KeyEventCounter.incrementId(),this.currentEvent={key:e.key,type:t,handled:!1}}},{key:"_startNewKeyCombination",value:function(e,n,o,i){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_startNewKeyCombination",this).call(this,e,n)}},{key:"_addToCurrentKeyCombination",value:function(e,n,o,i){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addToCurrentKeyCombination",this).call(this,e,n)}},{key:"_callHandlerIfActionNotHandled",value:function(e,t,n,o,i){this._describeCurrentKeyCombination();if(this.keyMapEventBitmap[n])if(this.eventPropagationState.actionHandled);else{var r=this.eventPropagationState.previousComponentIndex;this._callMatchingHandlerClosestToEventTarget(e,t,n,o,-1===r?0:r)&&(this.eventPropagationState.actionHandled=!0,this.currentEvent.handled=!0)}}},{key:"_logPrefix",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Logger.logIcons,o=Logger.eventIcons,i=Logger.componentIcons,r="HotKeys (";if(!1!==t.focusTreeId){var s=isUndefined(t.focusTreeId)?this.focusTreeId:t.focusTreeId;r+="FT"+s+n[s%n.length]+"-"}if(!1!==t.eventId){var a=isUndefined(t.eventId)?KeyEventCounter.getId():t.eventId;r+="E"+a+o[a%o.length]+"-"}return r+"C"+e+i[e%i.length]+"):"}}]),t}();function capitalize(e){return e.replace(/\b\w/g,function(e){return e.toUpperCase()})}function removeAtIndex(e,t){return[].concat(toConsumableArray(e.slice(0,t)),toConsumableArray(e.slice(t+1)))}function getEventCharCode(e){var t=void 0,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,10===t&&(t=13),t>=32||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"},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"};function getEventKey(e){if(e.key){var t=normalizeKey[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=getEventCharCode(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?translateToKey[e.keyCode]||"Unidentified":""}var GlobalKeyEventStrategy=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];classCallCheck(this,t);var o=possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o.componentId=-1,o.listenersBound=!1,o.eventOptions={ignoreEventsCondition:Configuration.option("ignoreEventsCondition")},o}return inherits(t,AbstractKeyEventStrategy),createClass(t,[{key:"_reset",value:function(){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_reset",this).call(this),this.componentIdDict={}}},{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2],o=arguments[3];return this.eventOptions=o,this.componentId+=1,this._addComponentToList(this.componentId,e,t,n),this._updateDocumentHandlers(),this.componentId}},{key:"updateHotKeys",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=arguments[4];this.eventOptions=i;var r=this._getComponentPosition(e);this.componentList[r]=this._buildComponentOptions(e,t,n,o),this._updateLongestKeySequenceIfNecessary(e),this._updateDocumentHandlers(),this._resetHandlerResolutionState()}},{key:"removeHotKeys",value:function(e){var t=this._getComponentAndPosition(e),n=slicedToArray(t,2),o=n[0].keyMapEventBitmap,i=n[1];this.componentList=removeAtIndex(this.componentList,i),this._updateLongestKeySequenceIfNecessary(e),this._updateComponentIndexDictFromList({startingAt:i}),this._updateDocumentHandlers(o,KeyEventBitmapManager.newBitmap()),this._resetHandlerResolutionState()}},{key:"_addComponentToList",value:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments[3];get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addComponentToList",this).call(this,e,n,o,i),this._setComponentPosition(e,this.componentList.length-1)}},{key:"_setComponentPosition",value:function(e,t){this.componentIdDict[e]=t}},{key:"_updateLongestKeySequenceIfNecessary",value:function(e){var t=this;e===this.longestSequenceComponentIndex&&(this.longestSequence=1,this.componentList.forEach(function(e){var n=e.longestSequence;n>t.longestSequence&&(t.longestSequence=n)}))}},{key:"_updateComponentIndexDictFromList",value:function(){for(var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{startingAt:0}).startAt;e<this.componentList.length;)this._setComponentPosition(this.componentList[e].componentId,e)}},{key:"_updateDocumentHandlers",value:function(){var e=this,t=this.keyMapEventBitmap.some(function(e){return e});if(!this.listenersBound&&t){for(var n=function(t){var n=describeKeyEvent(t);document["on"+n]=function(t){e.keyEventManager["handleGlobal"+capitalize(n)](t)}},o=0;o<this.keyMapEventBitmap.length;o++)n(o);this.listenersBound=!0}else if(this.listenersBound&&!t){for(o=0;o<this.keyMapEventBitmap.length;o++){var i=describeKeyEvent(o);delete document["on"+i]}this.listenersBound=!1}}},{key:"handleKeydown",value:function(e){this._checkForModifierFlagDiscrepancies(e);var t=normalizeKeyName(getEventKey(e));!!this._getCurrentKeyState(t)||this.keyCombinationIncludesKeyUp?this._startNewKeyCombination(t,KeyEventBitmapIndex.keydown):this._addToCurrentKeyCombination(t,KeyEventBitmapIndex.keydown);var n=this.keyEventManager.reactAppHistoryWithEvent(t,KeyEventBitmapIndex.keydown);if("handled"===n);else{if("seen"===n||KeyEventCounter.incrementId(),this.eventOptions.ignoreEventsCondition(e))return;this._callHandlerIfExists(e,t,KeyEventBitmapIndex.keydown),hasKeyPressEvent(t)||(this.keyEventManager.simulatePendingKeyPressEvents(),this.handleKeypress(e))}}},{key:"handleKeypress",value:function(e){var t=normalizeKeyName(getEventKey(e)),n=this._getCurrentKeyState(t);n&&(n[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keypress]||n[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keyup])?this._startNewKeyCombination(t,KeyEventBitmapIndex.keypress):this._addToCurrentKeyCombination(t,KeyEventBitmapIndex.keypress);var o=this.keyEventManager.reactAppHistoryWithEvent(t,KeyEventBitmapIndex.keypress);return"handled"!==o&&("seen"===o||KeyEventCounter.incrementId(),!this.eventOptions.ignoreEventsCondition(e)&&void this._callHandlerIfExists(e,t,KeyEventBitmapIndex.keypress))}},{key:"handleKeyup",value:function(e){var t=normalizeKeyName(getEventKey(e)),n=this._getCurrentKeyState(t);n&&n[KeyEventSequenceIndex.current][KeyEventBitmapIndex.keyup]?this._startNewKeyCombination(t,KeyEventBitmapIndex.keyup):this._addToCurrentKeyCombination(t,KeyEventBitmapIndex.keyup);var o=this.keyEventManager.reactAppHistoryWithEvent(t,KeyEventBitmapIndex.keyup);return"handled"!==o&&("seen"===o||KeyEventCounter.incrementId(),!this.eventOptions.ignoreEventsCondition(e)&&void this._callHandlerIfExists(e,t,KeyEventBitmapIndex.keyup))}},{key:"_startNewKeyCombination",value:function(e,n){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_startNewKeyCombination",this).call(this,e,n)}},{key:"_addToCurrentKeyCombination",value:function(e,n){get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addToCurrentKeyCombination",this).call(this,e,n)}},{key:"_getComponentPosition",value:function(e){return this.componentIdDict[e]}},{key:"_getComponent",value:function(e){var t=this._getComponentPosition(e);return this.componentList[t]}},{key:"_getComponentAndPosition",value:function(e){var t=this._getComponentPosition(e);return[this.componentList[t],t]}},{key:"_callHandlerIfExists",value:function(e,t,n){this._describeCurrentKeyCombination();this.keyMapEventBitmap[n]&&this._callMatchingHandlerClosestToEventTarget(e,t,n)}},{key:"_callMatchingHandlerClosestToEventTarget",value:function(e,n,o){for(var i=0;i<this.componentList.length;i++){if(get(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_callMatchingHandlerClosestToEventTarget",this).call(this,e,n,o,i,0))return}}},{key:"_logPrefix",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=Logger.eventIcons,o=Logger.componentIcons,i="HotKeys (GLOBAL";if(!1!==t.eventId){var r=isUndefined(t.eventId)?KeyEventCounter.getId():t.eventId;i=i+"-E"+r+n[r%n.length]}return isUndefined(e)?i+"):":i+"-C"+e+o[e%o.length]+"):"}}]),t}();function isFromFocusOnlyComponent(e){return!isUndefined(e)}var KeyEventManager=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};classCallCheck(this,e),this.logger=t.logger||new Logger(Configuration.option("logLevel")),this._focusOnlyEventStrategy=new FocusOnlyKeyEventStrategy({configuration:t,logger:this.logger},this),this._globalEventStrategy=new GlobalKeyEventStrategy({configuration:t,logger:this.logger},this),this.lastEventSeen=null}return createClass(e,null,[{key:"getInstance",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.instance||(this.instance=new e(t)),this.instance}},{key:"clear",value:function(){delete this.instance}}]),createClass(e,[{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];return this._focusOnlyEventStrategy.addHotKeys(e,t,n)}},{key:"updateHotKeys",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments[4];return this._focusOnlyEventStrategy.updateHotKeys(e,t,n,o,i)}},{key:"removeHotKeys",value:function(e,t){return this._focusOnlyEventStrategy.removeHotKeys(e,t)}},{key:"handleKeydown",value:function(e,t,n,o){if(isFromFocusOnlyComponent(t))return this._focusOnlyEventStrategy.handleKeydown(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"handleKeypress",value:function(e,t,n,o){if(isFromFocusOnlyComponent(t))return this._focusOnlyEventStrategy.handleKeypress(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"handleKeyup",value:function(e,t,n,o){if(isFromFocusOnlyComponent(t))return this._focusOnlyEventStrategy.handleKeyup(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"_recordLastSeenEvent",value:function(e){var t=e.key,n=e.type,o=e.nativeEvent;this.lastEventSeen={key:t,type:n,nativeEvent:o}}},{key:"addGlobalHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2],o=arguments[3];return this._globalEventStrategy.addHotKeys(e,t,n,o)}},{key:"updateGlobalHotKeys",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=arguments[4];return this._globalEventStrategy.updateHotKeys(e,t,n,o,i)}},{key:"removeGlobalHotKeys",value:function(e){return this._globalEventStrategy.removeHotKeys(e)}},{key:"handleGlobalKeydown",value:function(e){return this._globalEventStrategy.handleKeydown(e)}},{key:"handleGlobalKeypress",value:function(e){return this._globalEventStrategy.handleKeypress(e)}},{key:"handleGlobalKeyup",value:function(e){return this._globalEventStrategy.handleKeyup(e)}},{key:"ignoreEvent",value:function(e){this._focusOnlyEventStrategy.ignoreEvent(e)}},{key:"reactAppHistoryWithEvent",value:function(e,t){var n=this._focusOnlyEventStrategy.currentEvent;return n.key===e&&n.type===t?n.handled?"handled":"seen":"unseen"}},{key:"simulatePendingKeyPressEvents",value:function(){this._focusOnlyEventStrategy.simulatePendingKeyPressEvents()}},{key:"isGlobalListenersBound",value:function(){return this._globalEventStrategy.listenersBound}}]),e}();function withHotKeys(e){var t,n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};function i(e,t){return _extends({},o[e]||{},t[e]||{})}function r(e){return i("handlers",e)}function s(e){return i("keyMap",e)}return n=t=function(t){function n(e){classCallCheck(this,n);var t=possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t._handleFocus=t._handleFocus.bind(t),t._handleBlur=t._handleBlur.bind(t),t._handleKeyDown=t._handleKeyDown.bind(t),t._handleKeyPress=t._handleKeyPress.bind(t),t._handleKeyUp=t._handleKeyUp.bind(t),t._componentIsFocused=t._componentIsFocused.bind(t),t}return inherits(n,PureComponent),createClass(n,[{key:"render",value:function(){var t=this.props,n=(t.keyMap,t.handlers,t.allowChanges,objectWithoutProperties(t,["keyMap","handlers","allowChanges"])),o={onFocus:this._wrapFunction("onFocus",this._handleFocus),onBlur:this._wrapFunction("onBlur",this._handleBlur),tabIndex:Configuration.option("defaultTabIndex")};return this._shouldBindKeyListeners()&&(o.onKeyDown=this._handleKeyDown,o.onKeyPress=this._handleKeyPress,o.onKeyUp=this._handleKeyUp),React.createElement(e,_extends({hotKeys:o},n))}},{key:"_shouldBindKeyListeners",value:function(){var e=s(this.props);return!isEmpty(e)||Configuration.option("enableHardSequences")&&this._handlersIncludeHardSequences(e,r(this.props))}},{key:"_handlersIncludeHardSequences",value:function(e,t){return Object.keys(t).some(function(t){return!e[t]&&KeyCombinationSerializer.isValidKeySerialization(t)})}},{key:"_wrapFunction",value:function(e,t){var n=this;return"function"==typeof this.props[e]?function(o){n.props[e](o),t(o)}:t}},{key:"_focusTreeIdsPush",value:function(e){this._focusTreeIds||(this._focusTreeIds=[]),this._focusTreeIds.push(e)}},{key:"_focusTreeIdsShift",value:function(){this._focusTreeIds&&this._focusTreeIds.shift()}},{key:"_getFocusTreeId",value:function(){if(this._focusTreeIds)return this._focusTreeIds[0]}},{key:"componentDidUpdate",value:function(e){if(this._componentIsFocused()&&(this.props.allowChanges||!Configuration.option("ignoreKeymapAndHandlerChangesByDefault"))){var t=this.props,n=t.keyMap,o=t.handlers;KeyEventManager.getInstance().updateHotKeys(this._getFocusTreeId(),this._componentId,n,o,this._getComponentOptions())}}},{key:"componentWillUnmount",value:function(){this._handleBlur()}},{key:"_componentIsFocused",value:function(){return!0===this._focused}},{key:"_handleFocus",value:function(){var e;this.props.onFocus&&(e=this.props).onFocus.apply(e,arguments);var t=KeyEventManager.getInstance().addHotKeys(s(this.props),r(this.props),this._getComponentOptions()),n=slicedToArray(t,2),o=n[0],i=n[1];this._componentId=i,this._focusTreeIdsPush(o),this._focused=!0}},{key:"_handleBlur",value:function(){var e;this.props.onBlur&&(e=this.props).onBlur.apply(e,arguments);KeyEventManager.getInstance().removeHotKeys(this._getFocusTreeId(),this._componentId)||this._focusTreeIdsShift(),this._focused=!1}},{key:"_handleKeyDown",value:function(e){KeyEventManager.getInstance().handleKeydown(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_handleKeyPress",value:function(e){KeyEventManager.getInstance().handleKeypress(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_handleKeyUp",value:function(e){KeyEventManager.getInstance().handleKeyup(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_getComponentOptions",value:function(){return{defaultKeyEvent:Configuration.option("defaultKeyEvent")}}},{key:"_getEventOptions",value:function(){return{ignoreEventsCondition:Configuration.option("ignoreEventsCondition")}}}]),n}(),t.propTypes={keyMap:PropTypes.object,handlers:PropTypes.object,onFocus:PropTypes.func,onBlur:PropTypes.func,allowChanges:PropTypes.bool},n}var HotKeysWrapper=function(e){function t(){return classCallCheck(this,t),possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return inherits(t,Component),createClass(t,[{key:"render",value:function(){var e=this.props,t=e.hotKeys,n=objectWithoutProperties(e,["hotKeys"]),o=n.component||Configuration.option("defaultComponent");return React.createElement(o,_extends({},t,n))}}]),t}(),HotKeys=withHotKeys(HotKeysWrapper);function withHotKeysIgnore(e){var t,n,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{only:[],except:[]};return n=t=function(t){function n(e){classCallCheck(this,n);var t=possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t._handleKeyEvent=t._handleKeyEvent.bind(t),t._reloadDictionaries=t._reloadDictionaries.bind(t),t}return inherits(n,PureComponent),createClass(n,[{key:"getDefaultProps",value:function(){return o}}]),createClass(n,[{key:"render",value:function(){var t=this.props,n=(t.only,t.except,objectWithoutProperties(t,["only","except"])),o={onKeyDown:this._handleKeyEvent,onKeyPress:this._handleKeyEvent,onKeyUp:this._handleKeyEvent,onFocus:this._reloadDictionaries};return React.createElement(e,_extends({hotKeys:o},n))}},{key:"_reloadDictionaries",value:function(){var e=this.props,t=e.only,n=e.except;this._onlyDict=keyDictionary(t),this._exceptDict=keyDictionary(n)}},{key:"_shouldIgnoreEvent",value:function(e){var t=e.key;return isEmpty(this._onlyDict)?!!isEmpty(this._exceptDict)||!this._exceptDict[t]:isEmpty(this._exceptDict)?this._onlyDict[t]:this._onlyDict[t]&&!this._exceptDict[t]}},{key:"_handleKeyEvent",value:function(e){this._shouldIgnoreEvent(e)&&KeyEventManager.getInstance().ignoreEvent(e)}}]),n}(),t.propTypes={only:PropTypes.oneOfType([PropTypes.string,PropTypes.arrayOf(PropTypes.string)]),except:PropTypes.oneOfType([PropTypes.string,PropTypes.arrayOf(PropTypes.string)])},n}function keyDictionary(e){return arrayFrom(e).reduce(function(e,t){var n=standardizeKeyName(t);if(!isValidKey(n))throw new InvalidKeyNameError(t);return[resolveAltShiftedAlias,resolveUnaltShiftedAlias,resolveShiftedAlias,resolveUnshiftedAlias,resolveAltedAlias,resolveUnaltedAlias].forEach(function(t){e[t(n)]=!0}),e},{})}var HotKeysIgnore=function(e){function t(){return classCallCheck(this,t),possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return inherits(t,Component),createClass(t,[{key:"render",value:function(){var e=this.props,t=e.hotKeys,n=objectWithoutProperties(e,["hotKeys"]),o=n.component||Configuration.option("defaultComponent");return React.createElement(o,_extends({},t,n))}}]),t}(),HotKeysIgnore$1=withHotKeysIgnore(HotKeysIgnore),GlobalHotKeys=function(e){function t(){return classCallCheck(this,t),possibleConstructorReturn(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return inherits(t,Component),createClass(t,[{key:"render",value:function(){return this.props.children||null}},{key:"componentDidUpdate",value:function(){if(this.props.allowChanges||!Configuration.option("ignoreKeymapAndHandlerChangesByDefault")){var e=this.props,t=e.keyMap,n=e.handlers;KeyEventManager.getInstance().updateGlobalHotKeys(this._id,t,n,this._getComponentOptions(),this._getEventOptions())}}},{key:"componentDidMount",value:function(){var e=this.props,t=e.keyMap,n=e.handlers;this._id=KeyEventManager.getInstance().addGlobalHotKeys(t,n,this._getComponentOptions(),this._getEventOptions())}},{key:"componentWillUnmount",value:function(){KeyEventManager.getInstance().removeGlobalHotKeys(this._id)}},{key:"_getComponentOptions",value:function(){return{defaultKeyEvent:Configuration.option("defaultKeyEvent")}}},{key:"_getEventOptions",value:function(){return{ignoreEventsCondition:Configuration.option("ignoreEventsCondition")}}}]),t}();function configure(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Configuration.init(e)}GlobalHotKeys.propTypes={keyMap:PropTypes.object,handlers:PropTypes.object,onFocus:PropTypes.func,onBlur:PropTypes.func,allowChanges:PropTypes.bool};export{HotKeys,HotKeysIgnore$1 as HotKeysIgnore,withHotKeysIgnore,GlobalHotKeys,withHotKeys,configure};

@@ -1,5 +0,9 @@

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
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 _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

@@ -11,95 +15,355 @@

import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import HotKeys from './HotKeys';
import Configuration from './lib/Configuration';
import KeyEventManager from './lib/KeyEventManager';
import isEmpty from './utils/collection/isEmpty';
import KeyCombinationSerializer from './lib/KeyCombinationSerializer';
/**
* withHotKeys is an HOC that provides the wrappedComponent with the ability to implement keyboard actions
* without the user wrapping every component with a <HotKeys> component individually
* Wraps a React component in a HotKeysEnabled component, which passes down the
* callbacks and options necessary for React Hotkeys to work as a single prop value,
* hotkeys. These must be unwrapped and applied to a DOM-mountable element within
* the wrapped component (e.g. div, span, input, etc) in order for the key events
* to be recorded.
*
* See examples/master/HOCWrappedNode.js for an example implementation
* Follow the steps below to use the HOC:
*
* @example <caption>Example usage of withHotKeys.</caption>
* // Returns the HOC-wrapped component.
* // 1. Declared a key map that with the actionName as key and keyboardKeys as values
* const ACTION_KEY_MAP = {
* 'logConsole' : 'down',
* };
*
* class BasicBox extends React.Component {
*
* // 2. declare 'hotKeyHandlers' within the Component's class definition
* hotKeyHandlers: {
* 'logConsole': this.logConsole.bind(this),
* }
*
* logConsole() {
* console.log('a hotkey is pressed');
* }
*
* render() {
* return (
* <div tabIndex="0">
* Press the down arrow
* </div>
* );
* }
* }
*
* // 3. Wrap the Component with withHotKeys
* export default withHotKeys(ACTION_KEY_MAP)(BasicBox);
* @returns {function} Returns the HOC-wrapped component.
*
* @param {Object} keyMap an action-to-keyboard-key mapping
* @summary An HOC that provides the wrappedComponent with the ability to implement keyboard actions
* @param {React.ComponentClass} Component - Component class to wrap
* @param {Object} hotKeysOptions - Options that become the wrapping component's
* default prop values
* @returns {React.ComponentClass} Wrapped component that is passed all of the React hotkeys
* props in a single value, hotkeys.
*/
var withHotKeys = function withHotKeys(keyMap) {
return function (Component) {
return function (_PureComponent) {
_inherits(HotKeysWrapper, _PureComponent);
function withHotKeys(Component) {
var _class, _temp;
function HotKeysWrapper(props) {
_classCallCheck(this, HotKeysWrapper);
var hotKeysOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _this = _possibleConstructorReturn(this, (HotKeysWrapper.__proto__ || Object.getPrototypeOf(HotKeysWrapper)).call(this, props));
function mergeWithOptions(key, props) {
return _extends({}, hotKeysOptions[key] || {}, props[key] || {});
}
_this._setRef = _this._setRef.bind(_this);
_this.state = {
handlers: {}
function getHandlers(props) {
return mergeWithOptions('handlers', props);
}
function getKeyMap(props) {
return mergeWithOptions('keyMap', props);
}
/**
* Component that listens to key events when one of its children are in focus and
* selectively triggers actions (that may be handled by handler functions) when a
* sequence of events matches a list of pre-defined sequences or combinations
*/
return _temp = _class = function (_PureComponent) {
_inherits(HotKeysEnabled, _PureComponent);
function HotKeysEnabled(props) {
_classCallCheck(this, HotKeysEnabled);
/**
* The focus and blur handlers need access to the current component as 'this'
* so they need to be bound to it when the component is instantiated
*/
var _this = _possibleConstructorReturn(this, (HotKeysEnabled.__proto__ || Object.getPrototypeOf(HotKeysEnabled)).call(this, props));
_this._handleFocus = _this._handleFocus.bind(_this);
_this._handleBlur = _this._handleBlur.bind(_this);
_this._handleKeyDown = _this._handleKeyDown.bind(_this);
_this._handleKeyPress = _this._handleKeyPress.bind(_this);
_this._handleKeyUp = _this._handleKeyUp.bind(_this);
_this._componentIsFocused = _this._componentIsFocused.bind(_this);
return _this;
}
_createClass(HotKeysEnabled, [{
key: 'render',
value: function render() {
var _props = this.props,
keyMap = _props.keyMap,
handlers = _props.handlers,
allowChanges = _props.allowChanges,
props = _objectWithoutProperties(_props, ['keyMap', 'handlers', 'allowChanges']);
var hotKeys = {
onFocus: this._wrapFunction('onFocus', this._handleFocus),
onBlur: this._wrapFunction('onBlur', this._handleBlur),
tabIndex: Configuration.option('defaultTabIndex')
};
return _this;
if (this._shouldBindKeyListeners()) {
hotKeys.onKeyDown = this._handleKeyDown;
hotKeys.onKeyPress = this._handleKeyPress;
hotKeys.onKeyUp = this._handleKeyUp;
}
return React.createElement(Component, _extends({
hotKeys: hotKeys
}, props));
}
}, {
key: '_shouldBindKeyListeners',
value: function _shouldBindKeyListeners() {
var keyMap = getKeyMap(this.props);
_createClass(HotKeysWrapper, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.setState({ handlers: this._ref.hotKeyHandlers });
return !isEmpty(keyMap) || Configuration.option('enableHardSequences') && this._handlersIncludeHardSequences(keyMap, getHandlers(this.props));
}
}, {
key: '_handlersIncludeHardSequences',
value: function _handlersIncludeHardSequences(keyMap, handlers) {
return Object.keys(handlers).some(function (action) {
return !keyMap[action] && KeyCombinationSerializer.isValidKeySerialization(action);
});
}
}, {
key: '_wrapFunction',
value: function _wrapFunction(propName, func) {
var _this2 = this;
if (typeof this.props[propName] === 'function') {
return function (event) {
_this2.props[propName](event);
func(event);
};
} else {
return func;
}
}, {
key: '_setRef',
value: function _setRef(node) {
this._ref = node;
}
}, {
key: '_focusTreeIdsPush',
value: function _focusTreeIdsPush(componentId) {
if (!this._focusTreeIds) {
this._focusTreeIds = [];
}
}, {
key: 'render',
value: function render() {
var handlers = this.state.handlers;
// Setting component as documentfragment to avoid unexpected stylistic changes to the wrapped component
this._focusTreeIds.push(componentId);
}
}, {
key: '_focusTreeIdsShift',
value: function _focusTreeIdsShift() {
if (this._focusTreeIds) {
this._focusTreeIds.shift();
}
}
}, {
key: '_getFocusTreeId',
value: function _getFocusTreeId() {
if (this._focusTreeIds) {
return this._focusTreeIds[0];
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(previousProps) {
if (this._componentIsFocused() && (this.props.allowChanges || !Configuration.option('ignoreKeymapAndHandlerChangesByDefault'))) {
var _props2 = this.props,
keyMap = _props2.keyMap,
handlers = _props2.handlers;
return React.createElement(
HotKeys,
{ component: 'document-fragment', keyMap: keyMap, handlers: handlers },
React.createElement(Component, _extends({
ref: this._setRef
}, this.props))
);
KeyEventManager.getInstance().updateHotKeys(this._getFocusTreeId(), this._componentId, keyMap, handlers, this._getComponentOptions());
}
}]);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this._handleBlur();
}
}, {
key: '_componentIsFocused',
value: function _componentIsFocused() {
return this._focused === true;
}
return HotKeysWrapper;
}(PureComponent);
};
};
/**
* Handles when the component gains focus by calling onFocus prop, if defined, and
* registering itself with the KeyEventManager
* @private
*/
}, {
key: '_handleFocus',
value: function _handleFocus() {
if (this.props.onFocus) {
var _props3;
(_props3 = this.props).onFocus.apply(_props3, arguments);
}
var _KeyEventManager$getI = KeyEventManager.getInstance().addHotKeys(getKeyMap(this.props), getHandlers(this.props), this._getComponentOptions()),
_KeyEventManager$getI2 = _slicedToArray(_KeyEventManager$getI, 2),
focusTreeId = _KeyEventManager$getI2[0],
componentId = _KeyEventManager$getI2[1];
this._componentId = componentId;
this._focusTreeIdsPush(focusTreeId);
this._focused = true;
}
/**
* Handles when the component loses focus by calling the onBlur prop, if defined
* and removing itself from the KeyEventManager
* @private
*/
}, {
key: '_handleBlur',
value: function _handleBlur() {
if (this.props.onBlur) {
var _props4;
(_props4 = this.props).onBlur.apply(_props4, arguments);
}
var retainCurrentFocusTreeId = KeyEventManager.getInstance().removeHotKeys(this._getFocusTreeId(), this._componentId);
if (!retainCurrentFocusTreeId) {
this._focusTreeIdsShift();
}
this._focused = false;
}
/**
* Delegates handing the keydown event to the KeyEventManager
* @param {KeyboardEvent} event Key board event containing key name and state
* @private
*/
}, {
key: '_handleKeyDown',
value: function _handleKeyDown(event) {
var discardFocusTreeId = KeyEventManager.getInstance().handleKeydown(event, this._getFocusTreeId(), this._componentId, this._getEventOptions());
if (discardFocusTreeId) {
this._focusTreeIdsShift();
}
}
/**
* Delegates handing the keypress event to the KeyEventManager
* @param {KeyboardEvent} event Key board event containing key name and state
* @private
*/
}, {
key: '_handleKeyPress',
value: function _handleKeyPress(event) {
var discardFocusTreeId = KeyEventManager.getInstance().handleKeypress(event, this._getFocusTreeId(), this._componentId, this._getEventOptions());
if (discardFocusTreeId) {
this._focusTreeIdsShift();
}
}
/**
* Delegates handing the keyup event to the KeyEventManager
* @param {KeyboardEvent} event Key board event containing key name and state
* @private
*/
}, {
key: '_handleKeyUp',
value: function _handleKeyUp(event) {
var discardFocusTreeId = KeyEventManager.getInstance().handleKeyup(event, this._getFocusTreeId(), this._componentId, this._getEventOptions());
if (discardFocusTreeId) {
this._focusTreeIdsShift();
}
}
}, {
key: '_getComponentOptions',
value: function _getComponentOptions() {
return {
defaultKeyEvent: Configuration.option('defaultKeyEvent')
};
}
}, {
key: '_getEventOptions',
value: function _getEventOptions() {
return {
ignoreEventsCondition: Configuration.option('ignoreEventsCondition')
};
}
}]);
return HotKeysEnabled;
}(PureComponent), _class.propTypes = {
/**
* A unique key to associate with KeyEventMatchers that allows associating handler
* functions at a later stage
* @typedef {String} ActionName
*/
/**
* Name of a key event
* @typedef {'keyup'|'keydown'|'keypress'} KeyEventName
*/
/**
* A string or list of strings, that represent a sequence of one or more keys
* @typedef {String | Array.<String>} MouseTrapKeySequence
* @see {@link https://craig.is/killing/mice} for support key sequences
*/
/**
* Options for the mapping of a key sequence and event
* @typedef {Object} KeyEventOptions
* @property {MouseTrapKeySequence} sequence - The key sequence required to satisfy a
* KeyEventDescription
* @property {KeyEventName} action - The keyboard state required to satisfy a
* KeyEventDescription
*/
/**
* A description of key sequence of one or more key combinations
* @typedef {MouseTrapKeySequence|KeyMapOptions|Array<MouseTrapKeySequence>} KeyEventDescription
*/
/**
* A mapping from ActionName to KeyEventDescription
* @typedef {Object.<ActionName, KeyEventDescription>} KeyMap
*/
/**
* A map from action names to Mousetrap or Browser key sequences
* @type {KeyMap}
*/
keyMap: PropTypes.object,
/**
* A map from action names to event handler functions
* @typedef {Object<ActionName, Function>} HandlersMap
*/
/**
* A map from action names to event handler functions
* @type {HandlersMap}
*/
handlers: PropTypes.object,
/**
* Function to call when this component gains focus in the browser
* @type {Function}
*/
onFocus: PropTypes.func,
/**
* Function to call when this component loses focus in the browser
* @type {Function}
*/
onBlur: PropTypes.func,
/**
* Whether the keyMap or handlers are permitted to change after the
* component mounts. If false, changes to the keyMap and handlers
* props will be ignored
*/
allowChanges: PropTypes.bool
}, _temp;
}
export default withHotKeys;
import * as React from 'react';
type MouseTrapKeySequence = string | Array<string>;
export type MouseTrapKeySequence = string | Array<string>;
type KeyEventName = 'keyup' | 'keydown' | 'keypress';
export type KeyEventName = 'keyup' | 'keydown' | 'keypress';
type KeySequence = MouseTrapKeySequence | KeyMapOptions | Array<MouseTrapKeySequence>;
type KeyMap = { [key: string]: KeySequence };
interface KeyMapOptions {
export interface KeyMapOptions {
sequence: MouseTrapKeySequence;

@@ -16,13 +12,16 @@ action: KeyEventName;

interface FocusTrapProps {
/**
* The React component that should be used in the DOM to wrap the FocusTrap's
* children and have the internal key listeners bound to
*/
component?: React.Component | string;
}
export type KeySequence = MouseTrapKeySequence | KeyMapOptions | Array<MouseTrapKeySequence> | Array<KeyMapOptions>;
interface HotKeysProps extends React.HTMLAttributes<HotKeys>, FocusTrapProps {
export type KeyMap = { [key: string]: KeySequence };
/**
* Component that listens to key events when one of its children are in focus and
* selectively triggers actions (that may be handled by handler functions) when a
* sequence of events matches a list of pre-defined sequences or combinations
*/
export interface HotKeysEnabled extends React.Component<HotKeysProps, {}> { }
export interface HotKeysEnabledProps extends React.HTMLAttributes<HotKeys> {
/**
* A mapping of action names to key combinations
* A map from action names to Mousetrap or Browser key sequences
*/

@@ -32,3 +31,3 @@ keyMap?: KeyMap;

/**
* A mapping of action names to handler functions
* A map from action names to event handler functions
*/

@@ -38,38 +37,82 @@ handlers?: { [key: string]: (keyEvent?: KeyboardEvent) => void };

/**
* Whether the component should behave as if it current has browser focus
* event when it doesn't
* Function to call when this component gains focus in the browser
*/
focused?: boolean;
onFocus?: () => void;
/**
* The object that the internal key listeners should be bound to
* Function to call when this component loses focus in the browser
*/
attach?: React.Component | Element | Window;
onBlur?: () => void;
/**
* Function to call when this component gains focus in the browser
* Whether the keyMap or handlers are permitted to change after the
* component mounts. If false, changes to the keyMap and handlers
* props will be ignored
*/
onFocus?: () => void;
allowChanges?: boolean;
}
export interface HotKeysProps extends HotKeysEnabledProps {
/**
* Function to call when this component loses focus in the browser
* The React component that should be used in the DOM to wrap the FocusTrap's
* children and have the internal key listeners bound to
*/
onBlur?: () => void;
component?: React.ComponentClass | string;
}
/**
* Component that renders its children within a "focus trap" component that
* binds to key event listeners and calls specified event handler functions
* based on which key (or key combination) is activated.
* @see HotKeysEnabled
*/
export class HotKeys extends React.Component<HotKeysProps, {}> { }
export declare function withHotKeys(keyMap: { [key: string]: KeySequence }): HotKeys;
export class GlobalHotKeys extends React.Component<HotKeysEnabled, {}> { }
/**
* Component that renders a "focus trap" with a tabIndex property allowing
* it to be programmatically focused, but skip the user focusing it in the
* browser
* Wraps a React component in a HotKeysEnabled component, which passes down the
* callbacks and options necessary for React Hotkeys to work as a single prop value,
* hotkeys. These must be unwrapped and applied to a DOM-mountable element within
* the wrapped component (e.g. div, span, input, etc) in order for the key events
* to be recorded.
*/
export class FocusTrap extends React.Component<FocusTrapProps, {}> { }
export declare function withHotKeys(React.ComponentClass, HotKeysEnabledProps): HotKeysEnabled;
export declare function deprecatedWithHotKeys(keyMap: { [key: string]: KeySequence }): HotKeys;
export type ListOfKeys = string | Array<string>;
/**
* A component that causes React Hotkeys to ignore all matching key events
* triggered by its children. By default, this is all key events, but you can use
* the only prop to provide a whitelist, or the except prop to pass a blacklist (and
* cause HotKeys components to still observe these events).
*/
export interface HotKeysIgnored extends React.Component<HotKeysProps, {}> { }
export interface HotKeysIgnoredProps extends React.HTMLAttributes<HotKeys> {
/**
* The whitelist of keys that keyevents should be ignored. i.e. if you place
* a key in this list, all events related to it will be ignored by react hotkeys
*/
only: ListOfKeys,
/**
* The blacklist of keys that keyevents should be not ignored. i.e. if you place
* a key in this list, all events related to it will be still be observed by react
* hotkeys
*/
except: ListOfKeys
}
/**
* @see HotKeysIgnored
*/
export class HotKeysIgnore extends React.Component<HotKeysIgnoredProps, {}> { }
/**
* Wraps a React component in a HotKeysIgnored component, which passes down the
* callbacks and options necessary for React Hotkeys to work as a single prop value,
* hotkeys. These must be unwrapped and applied to a DOM-mountable element within
* the wrapped component (e.g. div, span, input, etc) in order for the key events
* to be recorded.
*/
export declare function withHotKeysIgnore(React.ComponentClass, HotKeysIgnoredProps): HotKeysIgnored;
{
"name": "react-hotkeys",
"version": "1.1.4",
"version": "2.0.0-pre1",
"description": "A declarative library for handling hotkeys and focus within a React application",

@@ -9,3 +9,4 @@ "main": "index",

"example": "examples",
"lib": "lib",
"src": "src",
"src/vendor": "src/vendor",
"test": "test"

@@ -20,3 +21,3 @@ },

"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-remove-comments": "^2.0.0",
"babel-plugin-transform-node-env-inline": "^0.4.3",
"babel-preset-es2015": "^6.9.0",

@@ -29,5 +30,6 @@ "babel-preset-react": "^6.11.1",

"cheerio": "^1.0.0-0",
"cross-env": "^5.2.0",
"css-loader": "^0.9.1",
"enzyme": "^3.0.0",
"enzyme-adapter-react-16": "^1.0.0",
"enzyme": "^3.3.0",
"enzyme-adapter-react-16": "^1.1.1",
"eslint": "^4.1.1",

@@ -46,21 +48,16 @@ "eslint-config-react-app": "^2.1.0",

"prompt": "^0.2.14",
"react": "^16.0.0",
"react-dom": "^16.0.0",
"react": "^16.3.2",
"react-dom": "^16.7.0",
"rollup": "^0.57.1",
"rollup-plugin-babel": "^3.0.3",
"rollup-plugin-license": "^0.6.0",
"rollup-plugin-replace": "^2.0.0",
"rollup-plugin-strip": "^1.2.0",
"rollup-plugin-uglify": "^3.0.0",
"simulant": "^0.2.2",
"sinon": "^4.0.0",
"sinon-chai": "^2.14.0",
"style-loader": "^0.9.0",
"webpack": "^1.7.3"
"sinon": "^4.5.0",
"sinon-chai": "^3.0.0",
"style-loader": "^0.9.0"
},
"dependencies": {
"lodash.isboolean": "^3.0.3",
"lodash.isequal": "^4.5.0",
"lodash.isobject": "^3.0.2",
"mousetrap": "^1.5.2",
"prop-types": "^15.6.0"
"prop-types": "^15.6.1"
},

@@ -79,4 +76,3 @@ "files": [

"peerDependencies": {
"react": ">= 0.14.0",
"react-dom": ">= 0.14.0"
"react": ">= 0.14.0, <0.17.0"
},

@@ -91,8 +87,8 @@ "scripts": {

"build-umd": "rm -rf umd && npm run build-umd-development && npm run build-umd-production",
"build-development": "BABEL_ENV=development NODE_ENV=development babel lib -d cjs",
"build-es-development": "BABEL_ENV=es-development NODE_ENV=development babel lib -d es",
"build-umd-development": "BABEL_ENV=umd-development NODE_ENV=development rollup --format umd --name ReactHotkeys -c --file umd/react-hotkeys.js",
"build-production": "BABEL_ENV=production NODE_ENV=production rollup --format cjs -c --file cjs/react-hotkeys.production.min.js",
"build-es-production": "BABEL_ENV=production NODE_ENV=production rollup --format es -c --file es/react-hotkeys.production.min.js",
"build-umd-production": "BABEL_ENV=production NODE_ENV=production rollup --format umd --name ReactHotkeys -c --file umd/react-hotkeys.min.js"
"build-development": "cross-env BABEL_ENV=development NODE_ENV=development babel src -d cjs",
"build-es-development": "cross-env BABEL_ENV=es-development NODE_ENV=development babel src -d es",
"build-umd-development": "cross-env BABEL_ENV=umd-development NODE_ENV=development rollup --format umd --name ReactHotkeys -c --file umd/react-hotkeys.js",
"build-production": "cross-env BABEL_ENV=production NODE_ENV=production rollup --format cjs -c --file cjs/react-hotkeys.production.min.js",
"build-es-production": "cross-env BABEL_ENV=production NODE_ENV=production rollup --format es -c --file es/react-hotkeys.production.min.js",
"build-umd-production": "cross-env BABEL_ENV=production NODE_ENV=production rollup --format umd --name ReactHotkeys -c --file umd/react-hotkeys.min.js"
},

@@ -103,3 +99,3 @@ "author": "Aleck Greenham",

],
"license": "MIT",
"license": "ISC",
"keywords": [

@@ -106,0 +102,0 @@ "react-component",

@@ -11,2 +11,4 @@ <p align="center">

> Warning: This Readme is for the latest pre-release. The documentation for the latest stable release is available [here](https://github.com/greena13/react-hotkeys/tree/v1.1.4).
A declarative library for handling hotkeys and focus areas in React applications.

@@ -16,31 +18,33 @@

- Minimal and declarative API
- Named hotkeys for easy customization
- Intuitive key commands thanks to [Mousetrap](https://github.com/ccampbell/mousetrap)
- Tree based priority - the deepest focused handler wins
- Easy-to-use [HOC](https://github.com/greena13/react-hotkeys/blob/master/lib/withHotKeys.js) available.
- Offers a minimal declarative [JSX](#HotKeys-component-API) and [HoC](#withHotKeys-HoC-API) APIs
- Supports [browser key names](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) and [Mousetrap syntax](https://github.com/ccampbell/mousetrap)
- Allows you to define [global](#GlobalHotKeys-component) and [in-focus](#HotKeys-component) hot keys
- Works with React's Synthetic KeyboardEvents and event delegation and provides [predictable and expected behaviour](#Interaction-with-React) to anyone familiar with React
- It is optimized by default, but allows you to turn off different optimisation measures in a granular fashion
- It's customizable through a simple [configuration API](#Configuration)
- [Optimized for larger applications](#Optimizations), with many hot keys active at once
- Depends only on `prop-types` and a peer dependency of `react`
- Uses rollup, Uglify and strips out comments and logging for a small production build
- Has more than [1800 automated tests](/tests)
## Usage
## Basic Usage
#### Key map
#### Define a key map
```javascript
import {HotKeys} from 'react-hotkeys';
import MyNode from './MyNode';
// Simple "name:key sequence/s" to create a hotkey map
const map = {
'snapLeft': 'command+left',
'deleteNode': ['del', 'backspace']
const keyMap = {
SNAP_LEFT: 'command+left',
DELETE_NODE: ['del', 'backspace']
};
// Component with a key map
const App = React.createClass({
render() {
return (
<HotKeys keyMap={map}>
<HotKeys keyMap={keyMap}>
<div>
<MyNode></MyNode>
<MyNode></MyNode>
<MyNode />
<MyNode />
</div>

@@ -51,5 +55,7 @@ </HotKeys>

});
export default App;
```
#### Handlers
#### Define handlers

@@ -59,12 +65,6 @@ ```javascript

/**
* Component with hotkey handlers, which are only called when the component
* is within the application's 'focus tree' and prevents cascading hotkeys from
* being called
*/
const MyNode = React.createClass({
render() {
const handlers = {
'deleteNode': this.deleteNode
DELETE_NODE: this.deleteNode
};

@@ -79,2 +79,4 @@

});
export default MyNode;
```

@@ -90,9 +92,25 @@

#### npm
#### The latest pre-release
##### npm
```
npm install react-hotkeys@next --save
```
##### yarn
```
yarn add react-hotkeys@next
```
#### Latest stable release
##### npm
```
npm install react-hotkeys --save
```
#### yarn
##### yarn

@@ -138,8 +156,11 @@ ```

The Bower version of the package will **not** be supported going forward (including fixing any outstanding issues).
## Defining Hot Keys
`react-hotkeys` uses key maps to separate defining keyboard shortcuts from the actions that they trigger. This allows adding or changing hot keys in the future, without having to also update the actions in many places across your application.
## Defining key maps
Hotkey maps are simple JavaScript objects, where the keys are the names of the actions triggered and the values are a [Mousetrap-supported key sequence](https://craig.is/killing/mice) that must be activated in order to trigger the action.
`react-hotkeys` uses key maps to decouple defining keyboard shortcuts from the functions they call. This allows hot keys and handler functions to be defined and maintained independent of one another.
> When a user presses the corresponding combination or sequence of keys, it is said they *match* the hot keys, which causes an action to be *triggered*. `react-hotkeys` may then resolve an appropriate handler function to *handle* the action.
Key maps are Plain Old JavaScript Objects, where the keys are the action names and the values are usually a [Mousetrap-supported](https://craig.is/killing/mice) or [Browser Key Values](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) sequence string (but can also be an [array](#Alternative-Hotkeys) or an [object](#Key-Combination-vs-Sequences)) that must be matched in order to trigger the action.
```javascript

@@ -152,17 +173,8 @@ const keyMap = {

#### Alternative Hotkeys
#### Key Combinations vs Sequences
You can specify multiple keys that will trigger the same action using arrays:
Every hotkey or sequence string is parsed and treated as a sequence of key combinations. The simplest case is a sequence of 1 key combination, consisting of 1 key: e.g. `'a'` or `'shift'`.
```javascript
const keyMap = {
'deleteNode': ['del', 'backspace'],
'moveUp': ['up', 'w']
};
```
#### Key Combinations & Sequences
```
// Single key sequence
// Key sequence with a combination of a single key
'4'

@@ -173,37 +185,52 @@

// Combination sequence
// Sequence of a single combination with multiple keys (keys must be pressed at the same time)
'command+shift+k'
// GMail style sequences
// Sequence of multiple combinations (keys must be pressed and released one after another)
'up down left right'
```
#### Binding to Special Keys
#### Full Reference
Modifier keys: `shift`, `ctrl`, `alt`/`option`, `command`/`meta`
Please refer to [Mousetrap's documentation](https://craig.is/killing/mice) or [Browser Key Values](https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key/Key_Values) for an exhaustive list of supported shortcuts and sequences.
Special keys: `backspace`, `tab`, `enter`, `return`, `capslock`, `esc`, `escape`, `space`, `pageup`, `pagedown`, `end`, `home`, `left`, `up`, `right`, `down`, `ins`, `del`, and `plus`
#### Alternative Hotkeys
#### Full Reference
You can specify multiple *alternative* key sequences (they will trigger the same action) using arrays:
Refer to [Mousetrap's documentation](https://craig.is/killing/mice) for an exhaustive list of supported shortcuts and sequences.
```javascript
const keyMap = {
DELETE_NODE: ['del', 'backspace'],
MOVE_UP: ['up', 'w']
};
```
#### Specifying key events (keydown, keypress, keyup)
#### Specifying Key Event
By default, `react-hotkeys` will match hotkey sequences on the `keydown` event (or, more precisely: on the `keydown` event of the last key to complete the last combination in a sequence).
`react-hotkeys` tries to automatically determine the best key event (usually `keypress`) to monitor based on the key sequence provided.
If you want to trigger a single action on a different key event, you can use the object syntax and the `action` attribute to explicitly set which key event you wish to bind to:
The object syntax and `action` attribute lets you explicitly set which key event you wish to bind to:
```javascript
const keyMap = {
'contract': 'alt+down',
'commandDown': {sequence: 'command', action: 'keydown'},
CONTRACT: 'alt+down',
COMMAND_DOWN: {sequence: 'command', action: 'keydown'},
};
```
If you want to change the default key event for all hotkeys, you can use the `defaultKeyEvent` option of the [configuration API](#Configuration).
The full list of valid key events is: `keypress`, `keydown`, and `keyup`.
#### Deciding which key map syntax to use
As a general rule, you should use the syntax that is the most brief, but still allows you to express the configuration you want.
| Question | Yes | No |
| :--- | :--- | :--- |
| **Need to define alternative key sequences to trigger the same action?** | Use an array of strings or objects. | Use a string or object. |
| **Need to explicitly define the key event to bind to (or some other additional option)?** | Use an object. | Use a string. |
## Defining Handlers
Key maps trigger named actions when matching keys are pressed - but do not define any behaviour. Handlers are the functions called to handle when a matching action is triggered and define how your application should respond.
Key maps trigger actions when they match a key sequence. Handlers are the functions that `react-hotkeys` calls to handle those actions.

@@ -216,7 +243,7 @@ Handlers may be defined in the same `<HotKeys />` component as the key map:

const keyMap = {
moveUp: 'up',
MOVE_UP: 'up',
}
const handlers = {
'moveUp': (event) => console.log('Move up hotkey called!')
MOVE_UP: (event) => console.log('Move up hotkey called!')
};

@@ -229,5 +256,4 @@

Or in any descendant of the `<HotKeys />` component that defines the key map:
Or they may be defined in any *descendant* of the `<HotKeys />` component that defines the key map:
```javascript

@@ -237,7 +263,7 @@ import {HotKeys} from 'react-hotkeys';

const keyMap = {
moveUp: 'up',
MOVE_UP: 'up',
}
const handlers = {
'moveUp': (event) => console.log('Move up hotkey called!')
MOVE_UP: (event) => console.log('Move up hotkey called!')
};

@@ -258,8 +284,17 @@

#### Hard Sequence Handlers
#### DEPRECATED: Hard Sequence Handlers
You can also explicitly define sequences as handlers in case you want a *hard*-override.
Handlers associated to actions with names that are valid key sequence strings implicitly define actions that are matched by the corresponding key sequence. This means you do not have to define the key maps in order for these handlers to "just work".
This functionality is not advised and exists mainly for backwards compatibility. It is generally advisable to explicitly define an action in a key map rather than rely on this behaviour.
To use hard sequence handlers, you must first enable them using the `enableHardSequences` [configuration option](#Configuration).
```javascript
// If no named hotkey 'up' exists we assume it is a key sequence
/**
* If no named 'up' action has been defined in a key map and it is a valid
* key sequence, react-hotkeys assumes it's a hard sequence handler and
* implicitly defines an action for it
*/
const handlers = {

@@ -270,36 +305,35 @@ 'up': (event) => console.log('up key called')

## Interaction with React
## Triggering Hot Keys
Rather than re-invent the wheel, `react-hotkeys` piggy-backs of the React SyntheticEvent and event propagation, so all of the normal React behaviour that you expect still applies.
Key handlers are only called under the following conditions (all must be true):
- Key events propagate up from a source or target towards the root of the application.
- If an event has `stopPropagation()` called on it, it will not be seen by components higher up in the render tree.
* One of the descendents of a `<HotKeys />` component that defines `handlers` is currently in focus (or the [focused prop](#simulating-an-elements-focus) is true)
* Either that `<HotKeys />` component, or one of its ancestors that is a `<HotKeys />` component, defines a `keyMap` that has a sequence that matches the keys being pressed
* The `<HotKeys />` component that defines `handlers` has a handler that matches the action being triggered
* A more deeply nested `<HotKeys />` component's handler has **not** already been called
## HotKeys components
A more exhaustive enumration of `react-hotkeys` behaviour can be found by reviewing the [test suite](/test).
`<HotKeys>` components listen only to key events that happen when one of their DOM-mounted descendents are in focus (`<div/>`, `<span/>`, `<input/>`, etc). This emulates (and re-uses) the behaviour of the browser and React's SyntheticEvent propagation.
### Elements must be in focus
This is the default type of `<HotKeys />` component, and should normally be your first choice for efficiency and clarity (the user generally expects keyboard input to affect the focused element in the browser).
In order for a hot key to be triggered, an element that is a descendent of the `<HotKey />` component that defines `handlers` must be in focus. It is not enough to have a descendent element of a `<HotKey />` that defines a `keyMap` in focus - it must be one that defines `handlers`. See [Managing focus in the browser](#Managing-focus-in-the-browser) for more details.
### How action handlers are resolved
### Simulating an element's focus
> If one of the DOM-mounted descendents of an `<HotKeys>` component are in focus (and it is listening to key events) AND those key events match a hot key in the component's key map, then the corresponding action is triggered.
You can cause a `<HotKey />` with a `handlers` prop to behave as if one of its descendents is currently focused (and call any matching handlers) using the `focused` prop:
`react-hotkeys` starts at the `<HotKeys />` component closest to the event's target (the element that was in focus when the key was pressed) and works its way up through the component tree of focused `<HotKeys />` components, looking for a matching handler for the action. The handler closest to the event target AND a descendant of the `<HotKeys />` component that defines the action (or the component itself), is the one that is called.
```javasript
<HotKeys keyMap={this.keyMap} handlers={this.handlers} focused>
<input />
</HotKeys>
```
That is:
### Hot Key Action Propagation
- Unless one of the DOM-mounted descendents of a `<HotKeys>` component is in focus, the component's actions are not matched
- Unless a `<HotKeys>` component is nested within the `<HotKeys />` component that defines the action (or is the same `<HotKeys />` component), its handler is not called
- If a `<HotKeys />` component closer to the event target has defined a handler for the same action, a `<HotKeys />` component's handler won't be called (the closer component's handler will)
Actions start at the `<HotKeys />` component that is the the closest ancestor to the element in focus and only propagate until they are handled the first time: handlers in parent `<HotKeys />` components will **not** be called if a child has already handled it.
A more exhaustive enumeration of `react-hotkeys` behaviour can be found by reviewing the [test suite](/test).
## Managing focus in the browser
### Managing focus in the browser
### Focusable elements
#### Focusable elements
HTML5 allows any element with a `tabindex` attribute to receive focus.
If you wish to support HTML4 you are limited to the following focusable elements:

@@ -316,6 +350,4 @@

HTML5 allows any element with a `tabindex` attribute to receive focus.
#### Tab Index
### Tab order
If no elements have a `tabindex` in a HTML document, the browser will tab between [focusable elements](#Focusable-elements) in the order that they appear in the DOM.

@@ -325,6 +357,21 @@

If any element is given a negative `tabindex`, it will be skipped when a user tabs through the document. However, a user may still click or touch on that element and it can be focused programmatically (see below). By default, `<Shortcuts>` elements are given a `tabindex` of `-1`.
If any element is given a negative `tabindex`, it will be skipped when a user tabs through the document. However, a user may still click or touch on that element and it can be focused programmatically (see below).
### Programmatically manage focus
> By default, `<HotKeys>` render its children inside an element with a `tabindex` of `-1`. You can change this by passing a `tabIndex` prop to `<HotKeys>` or you can change the default `tabindex` value for all <HotKeys>` components using the `defaultTabIndex` option for the [Configuration API](#Configuration).
#### Autofocus
HTML5 supports a boolean `autofocus` attribute on the following input elements:
* `<button>`
* `<input>`
* `<select>`
* `<textarea>`
It can be used to automatically focus parts of your React application, without the need to [programmatically manage focus](#Programmatically-manage-focus).
Only one element in the document should have this attribute at any one time (the last element to mount with the attribute will take effect).
#### Programmatically manage focus
To programmatically focus a DOM element, it must meet two requirements:

@@ -360,3 +407,3 @@

### Get the element currently in focus
#### Get the element currently in focus

@@ -369,10 +416,478 @@ You can retrieve the element that is currently focused using the following:

## HotKeys component API
The HotKeys component provides a declarative and native JSX syntax that is best for succinctly declaring hotkeys in a way that best maintains separation and encapsulation with regards to the rest of your code base.
However, it [does require that its children be wrapped in a DOM-mounted node](#Hotkeys-is-rendering-a-div-that-is-breaking-my-styling), which can break styling and add extra levels to your render tree.
```javascript
<HotKeys
/**
* An object that defines actions as keys and key sequences as values
* (using either a string, array or object).
*
* Actions defined in one HotKeys component are available to be handled
* in an descendent HotKeys component.
*
* Optional.
*/
keyMap={ {} }
/**
* An object that defines handler functions as values, and the actions
* that they handle as keys.
*
* Optional.
*/
handlers={ {} }
/**
* The type of DOM-mountable component that should be used to wrap
* the component's children.
*/
component={ 'div' }
/**
* tabindex value to pass to DOM-mountable component wrapping children
*/
tabIndex={-1}
/**
* Whether the keyMap or handlers are permitted to change after the
* component mounts. If false, changes to the keyMap and handlers
* props will be ignored
*
* Optional.
*/
allowChanges={false}
>
/**
* Wraps all children in a DOM-mountable component
*/
{ children }
</HotKeys>
```
## withHotKeys HoC API
The HotKeys component API is generally recommended, but if wrapping your component in a DOM-mountable node is not acceptable, or you need more control over how the `react-hotkeys` props are applied, then the `withHotKeys()` HoC is available.
### Simple use-case
The simplest use-case of `withHotKeys()` is to simply pass it your component class as the first argument. What is returned is a new component that will accept all of the same props as a `<HotKey>` component, so you can specify key maps and handlers at render time, for example.
> The component you wrap **must** take responsibility for passing the `hotKeys` props to a DOM-mountable element. If you fail to do this, key events will not be detected when a descendant of the component is in focus.
```javascript
import {withHotKeys} from 'react-hotkeys';
class MyComponent extends Component {
render() {
/**
* Must unwrap hotKeys prop and pass its values to a DOM-mountable
* element (like the div below).
*/
const {hotKeys, ...remainingProps} = this.props;
return (
<div { ... { ...hotKeys, ...remainingProps } } >
<span>My HotKeys are effective here</span>
{ this.props.children }
</div>
)
}
}
const MyHotKeysComponent = withHotKeys(MyComponent);
const keyMap = {
TEST: 't'
};
const handlers = {
TEST: ()=> console.log('Test')
};
<MyHotKeysComponent keyMap={ keyMap } handlers={ handlers }>
<div>
You can press 't' to log to the console.
</div>
</MyHotKeysComponent>
```
### Pre-defining default prop values
You can use the second argument of `withHotKeys` to specify default values for any props you would normally pass to `<HotKeys />`. This means you do not have to specify them at render-time.
> If you do provide prop values when you render the component, these will be merged with (and override) those defined in the second argument of `withHotKeys`.
```javascript
import {withHotKeys} from 'react-hotkeys';
class MyComponent extends Component {
render() {
/**
* Must unwrap hotKeys prop and pass its values to a DOM-mountable
* element (like the div below).
*/
const {hotKeys, ...remainingProps} = this.props;
return (
<div { ... { ...hotKeys, ...remainingProps } } >
<span>My HotKeys are effective here</span>
{ this.props.children }
</div>
)
}
}
const keyMap = {
TEST: 't'
};
const handlers = {
TEST: ()=> console.log('Test')
};
const MyHotKeysComponent = withHotKeys(MyComponent, {keyMap, handlers});
/**
* Render without having to specify prop values
*/
<MyHotKeysComponent>
<div>
You can press 't' to log to the console.
</div>
</MyHotKeysComponent>
```
## GlobalHotKeys component
`<GlobalHotKeys>` components match key events that occur anywhere in the document (even when no part of your React application is in focus).
```javascript
const keyMap = { SHOW_ALL_HOTKEYS: 'shift+?' };
const handlers = { SHOW_ALL_HOTKEYS: this.showHotKeysDialog };
<GlobalHotKeys keyMap={ keyMap } handlers={ handlers } />
```
`<GlobalHotKeys>` generally have no need for children, so should use a self-closing tag (as shown above). The only exception is when you are nesting other `<GlobalHotKeys>` components somewhere in the descendents (these are mounted before their parents, and so are generally matched first).
### How actions and handlers are resolved
Regardless of where `<GlobalHotKeys>` components appear in the render tree, they are matched with key events after the event has finished propagating through the React app (if the event originated in the React at all). This means if your React app is in focus and it handles a key event, it will be ignored by the `<GlobalHotKeys>` components.
The order used for resolving actions and handlers amongst `<GlobalHotKeys>` components, is the order in which they mounted (those mounted first, are given the chance to handle an action first). When a `<GlobalHotKeys>` component is unmounted, it is removed from consideration. This can get less deterministic over the course of a long session using a React app as components mount and unmount, so it is best to define actions and handlers that are globally unique.
It is recommended to use `<HotKeys>` components whenever possible for better performance and reliability.
> You can use the [autofocus attributes](#Autofocus) or [programmatically manage focus](#Programmatically-manage-focus) to automatically focus your React app so the user doesn't have to select it in order for hot keys to take effect. It is common practice to place a `<HotKeys>` component towards the top of your application to match hot keys across your entire React application.
## GlobalHotKeys component API
The GlobalHotKeys component provides a declarative and native JSX syntax for defining hotkeys that are applicable beyond you React application.
```javascript
<GlobalHotKeys
/**
* An object that defines actions as keys and key sequences as values
* (using either a string, array or object).
*
* Actions defined in one HotKeys component are available to be handled
* in an descendent HotKeys component.
*
* Optional.
*/
keyMap={ {} }
/**
* An object that defines handler functions as values, and the actions
* that they handle as keys.
*
* Optional.
*/
handlers={ {} }
/**
* Whether the keyMap or handlers are permitted to change after the
* component mounts. If false, changes to the keyMap and handlers
* props will be ignored
*
* Optional.
*/
allowChanges={false}
>
/**
* Wraps all children in a DOM-mountable component
*/
{ children }
</GlobalHotKeys>
```
## Ignoring events
By default, all key events that originate from `<input>`, `<select>` or `<textarea>`, or have a `isContentEditable` attribute of `true` are ignored by `react-hotkeys`.
If this is not what you want for your application, you can modify the list of tags using the `ignoreTags` [configuration option](#Configuration) or if you need additional control, you can specify a brand new function using the `ignoreEventsCondition` [configuration option](#Configuration).
### HotKeysIgnore component
If you want `react-hotkeys` to ignore key events coming from a particular area of your app when it is in focus, you can use the `<HotKeysIgnore/>` component:
```javascript
import {HotKeysIgnore} from 'react-hotkeys';
<HotKeysIgnore>
/**
* Children that, when in focus, should have its key events ignored by
* react hotkeys
*/
</HotKeysIgnore>
```
### HotKeysIgnore component API
By default, `<HotKeysIgnore />` will ignore all key events, but you can customize this behaviour by providing a whitelist or blacklist of events to ignore:
```javascript
<HotKeysIgnore
/**
* The whitelist of keys that keyevents should be ignored. i.e. if you place
* a key in this list, all events related to it will be ignored by react
* hotkeys.
*
* Accepts a string or an array of strings.
*/
only: { [] }
/**
* The blacklist of keys that keyevents should be not ignored. i.e.
* if you place a key in this list, all events related to it will be
* still be observed by react hotkeys
*/
except: { [] }
>
/**
* Children that, when in focus, should have its key events ignored by
* react hotkeys
*/
{ children }
</HotKeysIgnore>
```
### withHotKeysIgnore HoC API
Similar to the `<HotKeys>`'s `withHotKeys()` function, there is a `withHotKeysIgnore()` function for achieving the `<HotKeysIgnore>` functionality, without the need for rendering a surrounding DOM-mountable element.
```javascript
import {withHotKeysIgnore} from 'react-hotkeys';
class MyComponent extends Component {
render() {
/**
* Must unwrap hotKeys prop and pass its values to a DOM-mountable
* element (like the div below).
*/
const {hotKeys, ...remainingProps} = this.props;
return (
<div { ... { ...hotKeys, ...remainingProps } } >
<span>HotKeys ignores key events from here</span>
{ this.props.children }
</div>
)
}
}
const MyHotKeysComponent = withHotKeysIgnore(MyComponent);
<MyHotKeysComponent except={ 'Escape' }>
<div>
All key events except the 'Escape' key are ignored here
</div>
</MyHotKeysComponent>
```
`withHotKeysIgnore()` also accepts a second argument that becomes the default props of the component it returns:
```javascript
import {withHotKeysIgnore} from 'react-hotkeys';
class MyComponent extends Component {
render() {
/**
* Must unwrap hotKeys prop and pass its values to a DOM-mountable
* element (like the div below).
*/
const {hotKeys, ...remainingProps} = this.props;
return (
<div { ... { ...hotKeys, ...remainingProps } } >
<span>HotKeys ignores key events from here</span>
{ this.props.children }
</div>
)
}
}
const MyHotKeysComponent = withHotKeysIgnore(MyComponent, { except: 'Escape' });
<MyHotKeysComponent>
<div>
All key events except the 'Escape' key are ignored here
</div>
</MyHotKeysComponent>
```
## Allowing hotkeys and handlers props to change
For performance reasons, by default `react-hotkeys` takes the `keyMap` and `handlers` prop values when `<HotKeys>` components are focused and when `<GlobalHotKeys>` components are mounted. It ignores all subsequent updates
to their values when these props change.
If you need the ability to change them while `<HotKeys>` are still in focus, or while `<GlobalHotKeys>` are still mounted, then you can passe the `allowChanges` prop, permitting this behaviour for the particular component.
If you need to do this for all your `<HotKeys>` and `<GlobalHotKeys>` components, you can use the `ignoreKeymapAndHandlerChangesByDefault` option for the [Configuration API](#Configuration). This should normally never be done, as it can have significant performance implications.
## Configuration
The default behaviour across all `<HotKeys>` components is configured using the `configure` method.
> configure() should be called as your app is initialising and before the first time you mount a `<HotKeys>` component anywhere your app.
The following options are available (**default values are shown**):
```javascript
import {configure} from 'react-hotkeys';
configure({
/**
* The level of logging of its own behaviour React HotKeys should perform.
*/
logLevel: 'warn',
/**
* Default key event key maps are bound to (keydown|keypress|keyup)
*/
defaultKeyEvent: 'keydown',
/**
* The default component type to wrap HotKey components' children in, to provide
* the required focus and keyboard event listening for HotKeys to function
*/
defaultComponent: 'div',
/**
* The default tabIndex value passed to the wrapping component used to contain
* HotKey components' children. -1 skips focusing the element when tabbing through
* the DOM, but allows focusing programmatically.
*/
defaultTabIndex: '-1',
/**
* The HTML tags that React HotKeys should ignore key events from. This only works
* if you are using the default ignoreEventsCondition function.
* @type {String[]}
*/
ignoreTags: ['input', 'select', 'textarea'],
/**
* The function used to determine whether a key event should be ignored by React
* Hotkeys. By default, keyboard events originating elements with a tag name in
* ignoreTags, or a isContentEditable property of true, are ignored.
*
* @type {Function<KeyboardEvent>}
*/
ignoreEventsCondition: function,
/**
* Whether to allow hard sequences, or the binding of handlers to actions
* that have names that are valid key sequences, which implicitly define
* actions that are triggered by that key sequence
*/
enableHardSequences: false,
/**
* Whether to ignore changes to keyMap and handlers props by default
* (this reduces a significant amount of unnecessarily resetting
* internal state)
* @type {Boolean}
*/
ignoreKeymapAndHandlerChangesByDefault: true,
/**
* Whether React HotKeys should simulate keypress events for the keys that do not
* natively emit them.
* @type {Boolean}
*/
simulateMissingKeyPressEvents: true,
/**
* Whether to call stopPropagation() on events after they are
* handled (preventing the event from bubbling up any further, both within
* React Hotkeys and any other event listeners bound in React).
*
* This does not affect the behaviour of React Hotkeys, but rather what
* happens to the event once React Hotkeys is done with it (whether it's
* allowed to propagate any further through the Render tree).
*/
stopEventPropagationAfterHandling: true,
/**
* Whether to call stopPropagation() on events after they are
* ignored (preventing the event from bubbling up any further, both within
* React Hotkeys and any other event listeners bound in React).
*
* This does not affect the behaviour of React Hotkeys, but rather what
* happens to the event once React Hotkeys is done with it (whether it's
* allowed to propagate any further through the Render tree).
*/
stopEventPropagationAfterIgnoring: true,
});
```
## Troubleshooting & Gotchas
### Not compatible with lodash-webpack-plugin
#### Hotkeys is wrapping my components in a div that is breaking my styling
There is [some suggestion](https://github.com/greena13/react-hotkeys/issues/46) that `react-hotkeys` is not compatible with `lodash-webpack-plugin`. If you are experiencing issues where none of your handlers are being called and are using this webpack plugin, please try disabling it.
You have 3 options:
### Blue border appears around children of HotKeys
1. Use the [`component` prop](#HotKeys-component-API) to specify a `span` or some other alternative DOM-mountable component to wrap your component in, each time you render a component you don't want to wrap in a div element.
1. Use the [`defaultComponent` configuration option](#Configuration) to specify a `span` or some other alternative DOM-mountable component to wrap *all* `<HotKeys>` children in.
1. Use the [withHotKeys HoC API](#withHotKeys-HoC-API) to avoid rendering a wrapping component at all.
#### Other keyboard event listeners are no longer being triggered
For improved performance, by default `react-hotkeys` calls `stopPropagation()` on all events that it handles. You can change this using the `stopEventPropagationAfterHandling` and `stopEventPropagationAfterIgnoring` [configuration options](#Configuration).
#### Actions aren't being triggered when using withHotKeys
Check that you are [correctly passing the hotKeys props to a DOM-mountable component](#Pre-defining-default-prop-values).
#### Actions aren't being triggered for HotKeys
Make sure you are focusing a descendant of the `<HotKeys>` component before you press the keys.
Check that the `<HotKeys>` component that defines the handler is also an ancestor of the focused component, and is above (or *is*) the component that defines the `handlers`.
Also make sure your React application is not calling `stopPropagation()` on the key events before they reach the `<HotKeys>` component that defines the `keyMap`.
Finally, make sure your key event are not coming from one of the [tags ignored by react-hotkeys](#Ignoring-events).
#### Blue border appears around children of HotKeys
`react-hotkeys` adds a `<div />` around its children with a `tabindex="-1"` to allow them to be programmatically focused. This can result in browsers rendering a blue outline around them to visually indicate that they are the elements in the document that is currently in focus.

@@ -388,2 +903,376 @@

## Logging
`react-hotkeys` provides comprehensive logging of all of its internal behaviour and allows setting one of 6 log levels.
The default level is `warn`, which provides warnings and errors only, and is generally sufficient for most usage. However, if you are troubleshooting an issue or reporting a bug, you should increase the log level to `debug` or `verbose` to see what is going on, and be able to communicate it concisely.
You can set the logging level using the `logLevel` [configuration option](#Configuration).
For performance reasons, only some of the log levels are available in the production build. You will need to use the development build to get the full log output.
| Log Level | Severity | Description | Available in Dev | Available in Prod |
| :-- | :-- | :-- | :-- | :-- |
| verbose | (highest) | `debug` + internal data representations | Yes | No |
| debug | | `info` + event propagation info | Yes | No |
| info | | `warn` + general info | Yes | No |
| warn | (default) | `error` + warnings | Yes | Yes |
| error | | Errors only (ignore warnings) | Yes | Yes |
| none | (lowest) | Log nothing | Yes | Yes |
Logs appear in the developer console of the browser.
Each line is prefixed with (where applicable):
- The focus tree id
- The component id
- The event id
Each id is also given a coloured emoticon, to make it easy to visually trace the propagation of particular events through multiple components.
Below is an example (verbose) log output:
```
HotKeys (GLOBAL-C0🔺): Bound handler handleGlobalKeydown() to document.onkeydown()
HotKeys (GLOBAL-C0🔺): Bound handler handleGlobalKeypress() to document.onkeypress()
HotKeys (GLOBAL-C0🔺): Bound handler handleGlobalKeyup() to document.onkeyup()
HotKeys (GLOBAL-C0🔺): Mounted.
HotKeys (GLOBAL-C0🔺): Component options:
{
"actions": {
"KONAMI": [
{
"prefix": "ArrowUp ArrowUp ArrowDown ArrowDown ArrowLeft ArrowRight ArrowLeft ArrowRight b a",
"actionName": "KONAMI",
"sequenceLength": 11,
"id": "Enter",
"keyDictionary": {
"Enter": true
},
"eventBitmapIndex": 1,
"size": 1
}
],
"LOG_DOWN": [
{
"prefix": "",
"actionName": "LOG_DOWN",
"sequenceLength": 1,
"id": "Meta",
"keyDictionary": {
"Meta": true
},
"eventBitmapIndex": 0,
"size": 1
}
],
"LOG_UP": [
{
"prefix": "",
"actionName": "LOG_UP",
"sequenceLength": 1,
"id": "Meta",
"keyDictionary": {
"Meta": true
},
"eventBitmapIndex": 2,
"size": 1
}
]
},
"handlers": {
"KONAMI": "function () { [native code] }",
"LOG_DOWN": "function logCommandKeyDown() {\n console.log('command down');\n }",
"LOG_UP": "function logCommandKeyUp() {\n console.log('command up');\n }"
},
"componentId": 0,
"options": {
"defaultKeyEvent": "keydown"
}
}
HotKeys (FT0📕-E0❤️-C0🔺): Focused.
HotKeys (FT0📕-E0❤️-C0🔺): Component options:
{
"actions": {},
"handlers": {
"MOVE_UP": "function () { [native code] }",
"MOVE_DOWN": "function () { [native code] }",
"MOVE_LEFT": "function () { [native code] }",
"MOVE_RIGHT": "function () { [native code] }",
"DELETE": "function () { [native code] }",
"EXPAND": "function () { [native code] }",
"CONTRACT": "function () { [native code] }"
},
"componentId": 0,
"options": {
"defaultKeyEvent": "keydown"
}
}
HotKeys (FT0📕-E0❤️-C1⭐️): Focused.
HotKeys (FT0📕-E0❤️-C1⭐️): Component options:
{
"actions": {
"DELETE": [
{
"prefix": "",
"actionName": "DELETE",
"sequenceLength": 1,
"id": "Backspace",
"keyDictionary": {
"Backspace": true
},
"eventBitmapIndex": 2,
"size": 1
}
],
"EXPAND": [
{
"prefix": "",
"actionName": "EXPAND",
"sequenceLength": 1,
"id": "Alt+ArrowUp",
"keyDictionary": {
"Alt": true,
"ArrowUp": true
},
"eventBitmapIndex": 1,
"size": 2
}
],
"CONTRACT": [
{
"prefix": "",
"actionName": "CONTRACT",
"sequenceLength": 1,
"id": "Alt+ArrowDown",
"keyDictionary": {
"Alt": true,
"ArrowDown": true
},
"eventBitmapIndex": 1,
"size": 2
}
],
"MOVE_UP": [
{
"prefix": "",
"actionName": "MOVE_UP",
"sequenceLength": 1,
"id": "ArrowUp",
"keyDictionary": {
"ArrowUp": true
},
"eventBitmapIndex": 1,
"size": 1
}
],
"MOVE_DOWN": [
{
"prefix": "",
"actionName": "MOVE_DOWN",
"sequenceLength": 1,
"id": "ArrowDown",
"keyDictionary": {
"ArrowDown": true
},
"eventBitmapIndex": 1,
"size": 1
}
],
"MOVE_LEFT": [
{
"prefix": "",
"actionName": "MOVE_LEFT",
"sequenceLength": 1,
"id": "ArrowLeft",
"keyDictionary": {
"ArrowLeft": true
},
"eventBitmapIndex": 1,
"size": 1
}
],
"MOVE_RIGHT": [
{
"prefix": "",
"actionName": "MOVE_RIGHT",
"sequenceLength": 1,
"id": "ArrowRight",
"keyDictionary": {
"ArrowRight": true
},
"eventBitmapIndex": 1,
"size": 1
}
]
},
"handlers": {},
"componentId": 1,
"options": {
"defaultKeyEvent": "keydown"
}
}
HotKeys (FT0📕-E1💚-C0🔺): New 'ArrowDown' keydown event.
HotKeys (FT0📕-E1💚-C0🔺): Added 'ArrowDown' to current combination: ArrowDown.
HotKeys (FT0📕-E1💚-C0🔺): Ignored 'ArrowDown' keydown because it doesn't have any keydown handlers.
HotKeys (FT0📕-E1💚-C1⭐️): Ignored 'ArrowDown' keydown because it doesn't have any keydown handlers.
HotKeys (FT0📕-E1💚-C0🔺): Simulating 'ArrowDown' keypress event because 'ArrowDown' doesn't natively have one.
HotKeys (FT0📕-E2💙-C0🔺): New 'ArrowDown' keypress event.
HotKeys (FT0📕-E2💙-C0🔺): Attempting to find action matching 'ArrowDown' keypress . . .
HotKeys (FT0📕-E2💙-C0🔺): Internal key mapping:
{
"sequences": {
"": {
"combinations": {
"Backspace": {
"prefix": "",
"sequenceLength": 1,
"id": "Backspace",
"keyDictionary": {
"Backspace": true
},
"size": 1,
"events": {
"2": {
"actionName": "DELETE",
"eventBitmapIndex": 2,
"handler": "function () { [native code] }"
}
}
},
"Alt+ArrowUp": {
"prefix": "",
"sequenceLength": 1,
"id": "Alt+ArrowUp",
"keyDictionary": {
"Alt": true,
"ArrowUp": true
},
"size": 2,
"events": {
"1": {
"actionName": "EXPAND",
"eventBitmapIndex": 1,
"handler": "function () { [native code] }"
}
}
},
"Alt+ArrowDown": {
"prefix": "",
"sequenceLength": 1,
"id": "Alt+ArrowDown",
"keyDictionary": {
"Alt": true,
"ArrowDown": true
},
"size": 2,
"events": {
"1": {
"actionName": "CONTRACT",
"eventBitmapIndex": 1,
"handler": "function () { [native code] }"
}
}
},
"ArrowUp": {
"prefix": "",
"sequenceLength": 1,
"id": "ArrowUp",
"keyDictionary": {
"ArrowUp": true
},
"size": 1,
"events": {
"1": {
"actionName": "MOVE_UP",
"eventBitmapIndex": 1,
"handler": "function () { [native code] }"
}
}
},
"ArrowDown": {
"prefix": "",
"sequenceLength": 1,
"id": "ArrowDown",
"keyDictionary": {
"ArrowDown": true
},
"size": 1,
"events": {
"1": {
"actionName": "MOVE_DOWN",
"eventBitmapIndex": 1,
"handler": "function () { [native code] }"
}
}
},
"ArrowLeft": {
"prefix": "",
"sequenceLength": 1,
"id": "ArrowLeft",
"keyDictionary": {
"ArrowLeft": true
},
"size": 1,
"events": {
"1": {
"actionName": "MOVE_LEFT",
"eventBitmapIndex": 1,
"handler": "function () { [native code] }"
}
}
},
"ArrowRight": {
"prefix": "",
"sequenceLength": 1,
"id": "ArrowRight",
"keyDictionary": {
"ArrowRight": true
},
"size": 1,
"events": {
"1": {
"actionName": "MOVE_RIGHT",
"eventBitmapIndex": 1,
"handler": "function () { [native code] }"
}
}
}
}
}
},
"eventBitmap": [
false,
true,
true
],
"longestSequence": 1
}
HotKeys (FT0📕-E2💙-C0🔺): Found action that matches 'ArrowDown': MOVE_DOWN. Calling handler . . .
HotKeys (FT0📕-E2💙-C1⭐️): Simulating 'ArrowDown' keypress event because 'ArrowDown' doesn't natively have one.
HotKeys (FT0📕-E2💙-C1⭐️): Ignored 'ArrowDown' keypress as it has already been handled.
```
## Optimizations
`react-hotkeys` uses a lot of optimizations to help keep it as performant as possible (both in terms of time and memory). It can be helpful to be aware of some of these measures if you are seeing unexpected behaviour:
### Code optimizations
- If an event is handled by an earlier handler, it is ignored by an further components (this is really a design decision, rather than an optimization, but it helps).
- By default, `stopPropagation()` is called on all key events once `react-hotkeys` has handled them. This can be disabled via the `stopEventPropagationAfterHandling` and `stopEventPropagationAfterIgnoring` [configuration options](#Configuration).
- Events are ignored unless an action exists that is bound to that particular event type (keydown, keypress, keyup)
- Events are processed at each level, as they propagate up the React render tree. If a action is triggered by a leaf node, `react-hotkeys` stops there (and does not build the full application's mappings of key sequences and handlers)
- Changes to keyMaps and handlers are ignored unless you explicitly opt-in to the behaviour of resetting them each time their prop value changes.
- Key histories longer than the longest registered key sequence are discarded.
- The mapping between an action's key sequences and handlers is built "on-the-fly", so unless a particular action is triggered, `react-hotkeys` doesn't do the work of finding its corresponding handler.
- Global event listeners are only bound to `document` when a global hotkey is defined (and are removed when the last one is unmounted).
### Production optimizations
- The production build strips out all comments and logging statements below a level of warning, before undergoing minification using Uglify.
- An es6 version is also available, that allows for tree-shaking in compatible build setups.
## Support

@@ -399,7 +1288,3 @@

It has a non-comprehensive test suite. [![Build Status](https://travis-ci.org/greena13/react-hotkeys.svg)](https://travis-ci.org/greena13/react-hotkeys)
In November 2017, responsibility for maintaining `react-hotkeys` has changed hands. The new group of contributors will be working towards improving performance and providing *additional* functionality rather than having any breaking changes.
## Contribute, please!

@@ -413,6 +1298,2 @@

### Roadmap
The product roadmap is being currently being tracked in [Projects](https://github.com/greena13/react-hotkeys/projects), but is largely focused on improving performance, code quality and adding extra features to meet common requirements.
### Using GitHub Issues

@@ -434,7 +1315,1 @@

All credit, and many thanks, goes to [Chris Pearce](https://github.com/Chrisui) for the inception of `react-hotkeys` and all versions before `1.0.0`.
As of version `1.0.0`, [Aleck Greenham](https://github.com/greena13) is actively maintaining `react-hotkeys`. Please be patient while he gets up to speed.
## Thanks
Thanks to @ccampbell for [Mousetrap](https://github.com/ccampbell/mousetrap)

@@ -9,752 +9,6 @@ /**

* 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.
*
* PLEASE NOTE: SOURCE CODE FOUND IN THE lib/vendor DIRECTORY IS UNDER THE MIT LICENSE - PLEASE SEE THE LICENSE FILE FOR EACH DIRECTORY FOR MORE INFORMATION
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('prop-types'), require('react'), require('lodash.isequal'), require('react-dom'), require('lodash.isboolean'), require('lodash.isobject')) :
typeof define === 'function' && define.amd ? define(['exports', 'prop-types', 'react', 'lodash.isequal', 'react-dom', 'lodash.isboolean', 'lodash.isobject'], factory) :
(factory((global.ReactHotkeys = {}),global.PropTypes,global.React,global.isEqual,global.ReactDOM,global.isBool,global.isObject));
}(this, (function (exports,PropTypes,React,isEqual,ReactDOM,isBool,isObject) { 'use strict';
PropTypes = PropTypes && PropTypes.hasOwnProperty('default') ? PropTypes['default'] : PropTypes;
var React__default = 'default' in React ? React['default'] : React;
isEqual = isEqual && isEqual.hasOwnProperty('default') ? isEqual['default'] : isEqual;
ReactDOM = ReactDOM && ReactDOM.hasOwnProperty('default') ? ReactDOM['default'] : ReactDOM;
isBool = isBool && isBool.hasOwnProperty('default') ? isBool['default'] : isBool;
isObject = isObject && isObject.hasOwnProperty('default') ? isObject['default'] : isObject;
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
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 _extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
var inherits = function (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;
};
var objectWithoutProperties = function (obj, keys) {
var target = {};
for (var i in obj) {
if (keys.indexOf(i) >= 0) continue;
if (!Object.prototype.hasOwnProperty.call(obj, i)) continue;
target[i] = obj[i];
}
return target;
};
var possibleConstructorReturn = function (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;
};
/**
* Component to wrap its children in a parent that has a tabIndex of -1,
* making it programmatically focusable and with focus and blur handlers
*/
var FocusTrap = function (_Component) {
inherits(FocusTrap, _Component);
function FocusTrap() {
classCallCheck(this, FocusTrap);
return possibleConstructorReturn(this, (FocusTrap.__proto__ || Object.getPrototypeOf(FocusTrap)).apply(this, arguments));
}
createClass(FocusTrap, [{
key: 'render',
value: function render() {
var _props = this.props,
Component = _props.component,
children = _props.children,
props = objectWithoutProperties(_props, ['component', 'children']);
return React__default.createElement(
Component,
_extends({ tabIndex: '-1' }, props),
children
);
}
}]);
return FocusTrap;
}(React.Component);
FocusTrap.propTypes = {
/**
* Function to call when this component gains focus in the browser
*/
onFocus: PropTypes.func,
/**
* Function to call when this component loses focus in the browser
*/
onBlur: PropTypes.func,
/**
* Component (or component type as a string) to use as a wrapper or
* parent of this component's children
*/
component: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
/**
* Children to place in the wrapper or parent
*/
children: PropTypes.node
};
FocusTrap.defaultProps = {
component: 'div'
};
function sequencesFromKeyMap(hotKeyMap, hotKeyName) {
var sequences = hotKeyMap[hotKeyName];
if (!sequences) {
/**
* If no sequence is found with this name we assume the user is passing a
* hard-coded sequence as a key
*/
return [hotKeyName];
} else if (Array.isArray(sequences)) {
return sequences;
} else {
return [sequences];
}
}
function hasChanged(newValue, previousValue) {
return !isEqual(newValue, previousValue);
}
/**
* A string or list of strings, that represent a sequence of one or more keys
* @typedef {String | Array.<String>} MouseTrapKeySequence
* @see {@link https://craig.is/killing/mice} for support key sequences
*/
/**
* Name of a key event
* @typedef {'keyup'|'keydown'|'keypress'} KeyEventName
*/
/**
* Options for the mapping of a key sequence and event
* @typedef {Object} KeyEventOptions
* @property {MouseTrapKeySequence} The key sequence required to satisfy a KeyEventMatcher
* @property {KeyEventName} action The keyboard state required to satisfy a KeyEventMatcher
*/
/**
* A matcher used on keyboard sequences and events to trigger handler functions
* when matching sequences occur
* @typedef {MouseTrapKeySequence | KeyMapOptions | Array<MouseTrapKeySequence>} KeyEventMatcher
*/
/**
* A unique key to associate with KeyEventMatchers that allows associating handler
* functions at a later stage
* @typedef {String} ActionName
*/
/**
* A mapping from ActionNames to KeyEventMatchers
* @typedef {Object.<String, KeyEventMatcher>} KeySequence
*/
/**
* Component that wraps it children in a "focus trap" and allows key events to
* trigger function handlers when its children are in focus
*/
var HotKeys = function (_Component) {
inherits(HotKeys, _Component);
function HotKeys(props, context) {
classCallCheck(this, HotKeys);
/**
* The focus and blur handlers need access to the current component as 'this'
* so they need to be bound to it when the component is instantiated
*/
var _this = possibleConstructorReturn(this, (HotKeys.__proto__ || Object.getPrototypeOf(HotKeys)).call(this, props, context));
_this.onFocus = _this.onFocus.bind(_this);
_this.onBlur = _this.onBlur.bind(_this);
return _this;
}
/**
* Constructs the context object that contains references to this component
* and its KeyMap so that they may be accessed by any descendant HotKeys
* components
* @returns {{hotKeyParent: HotKeys, hotKeyMap: KeySequence}} Child context object
*/
createClass(HotKeys, [{
key: 'getChildContext',
value: function getChildContext() {
return {
hotKeyParent: this,
hotKeyMap: this.__hotKeyMap__
};
}
/**
* Sets this components KeyMap from its keyMap prop and the KeyMap of its
* ancestor KeyMap component (if one exists)
*/
}, {
key: 'componentWillMount',
value: function componentWillMount() {
this.updateMap();
}
/**
* Updates this component's KeyMap if either its own keyMap prop has changed
* or its ancestor's KeyMap has been update
*
* @returns {boolean} Whether the KeyMap was updated
*/
}, {
key: 'updateMap',
value: function updateMap() {
var newMap = this.buildMap();
if (!isEqual(newMap, this.__hotKeyMap__)) {
this.__hotKeyMap__ = newMap;
return true;
}
return false;
}
/**
* This component's KeyMap merged with that of its most direct ancestor that is a
* HotKeys component. This component's mappings take precedence over those defined
* in its ancestor.
* @returns {KeySequence} This component's KeyMap merged with its HotKeys ancestor's
*/
}, {
key: 'buildMap',
value: function buildMap() {
var parentMap = this.context.hotKeyMap || {};
var thisMap = this.props.keyMap || {};
/**
* TODO: This appears to only merge in the key maps of its most direct
* ancestor - what about grandparent components' KeyMap's?
*/
return _extends({}, parentMap, thisMap);
}
/**
* This component's KeyMap
* @returns {KeySequence} This component's KeyMap
*/
}, {
key: 'getMap',
value: function getMap() {
return this.__hotKeyMap__;
}
/**
* Imports mousetrap and stores a reference to it on the this component
*/
}, {
key: 'componentDidMount',
value: function componentDidMount() {
// import is here to support React's server rendering as Mousetrap immediately
// calls itself with window and it fails in Node environment
var Mousetrap = require('mousetrap');
/**
* TODO: Not optimal - imagine hundreds of this component. We need a top level
* delegation point for mousetrap
*/
this.__mousetrap__ = new Mousetrap(this.props.attach || ReactDOM.findDOMNode(this));
this.updateHotKeys(true);
}
/**
* Updates this component's KeyMap and synchronises the handlers across to
* Mousetrap after the component has been updated (passed new prop values)
* @param {Object} prevProps The props used on the component's last render
*/
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate(prevProps) {
this.updateHotKeys(false, prevProps);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(null);
}
if (this.__mousetrap__) {
this.__mousetrap__.reset();
}
}
/**
* Updates this component's KeyMap and synchronises the changes across
* to Mouestrap
* @param {Boolean} force Whether to force an update of the KeyMap and sync
* to Mousetrap, even if no relevant values appear to have changed
* since the last time
* @param {Object} prevProps The props used on the component's last render
*/
}, {
key: 'updateHotKeys',
value: function updateHotKeys() {
var force = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var prevProps = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var _props$handlers = this.props.handlers,
handlers = _props$handlers === undefined ? {} : _props$handlers;
var _prevProps$handlers = prevProps.handlers,
prevHandlers = _prevProps$handlers === undefined ? handlers : _prevProps$handlers;
var keyMapHasChanged = this.updateMap();
if (force || keyMapHasChanged || hasChanged(handlers, prevHandlers)) {
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(null);
}
this.syncHandlersToMousetrap();
}
}
/**
* Synchronises the KeyMap and handlers applied to this component over to
* Mousetrap
*/
}, {
key: 'syncHandlersToMousetrap',
value: function syncHandlersToMousetrap() {
var _this2 = this;
var _props$handlers2 = this.props.handlers,
handlers = _props$handlers2 === undefined ? {} : _props$handlers2;
var hotKeyMap = this.getMap();
var sequenceHandlers = [];
var mousetrap = this.__mousetrap__;
// Group all our handlers by sequence
Object.keys(handlers).forEach(function (hotKey) {
var handler = handlers[hotKey];
var sequencesAsArray = sequencesFromKeyMap(hotKeyMap, hotKey);
/**
* TODO: Could be optimized as every handler will get called across every bound
* component - imagine making a node a focus point and then having hundreds!
*/
sequencesAsArray.forEach(function (sequence) {
var action = void 0;
var callback = function callback(event, sequence) {
/**
* Check we are actually in focus and that a child hasn't already
* handled this sequence
*/
var isFocused = isBool(_this2.props.focused) ? _this2.props.focused : _this2.__isFocused__;
if (isFocused && sequence !== _this2.__lastChildSequence__) {
if (_this2.context.hotKeyParent) {
_this2.context.hotKeyParent.childHandledSequence(sequence);
}
return handler(event, sequence);
}
};
if (isObject(sequence)) {
action = sequence.action;
sequence = sequence.sequence;
}
sequenceHandlers.push({ callback: callback, action: action, sequence: sequence });
});
});
/**
* TODO: Hard reset our handlers (probably could be more efficient)
*/
mousetrap.reset();
sequenceHandlers.forEach(function (_ref) {
var sequence = _ref.sequence,
callback = _ref.callback,
action = _ref.action;
return mousetrap.bind(sequence, callback, action);
});
}
/**
* Stores a reference to the last key sequence handled by the most direct
* descendant HotKeys component, and passes that sequence to its own most
* direct HotKeys ancestor for it to do the same.
*
* This reference is stored so that parent HotKeys components do not try
* to handle a sequence that has already been handled by one of its
* descendants.
*
* @param {KeyEventMatcher} sequence The sequence handled most recently by
* a child HotKeys component
*/
}, {
key: 'childHandledSequence',
value: function childHandledSequence() {
var sequence = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
this.__lastChildSequence__ = sequence;
/**
* Traverse up any hot key parents so everyone is aware a child has
* handled a certain sequence
*/
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(sequence);
}
}
/**
* Renders the component's children wrapped in a FocusTrap with the necessary
* props to capture keyboard events
*
* @returns {FocusTrap} FocusTrap with necessary props to capture keyboard events
*/
}, {
key: 'render',
value: function render() {
var _props = this.props,
keyMap = _props.keyMap,
handlers = _props.handlers,
focused = _props.focused,
attach = _props.attach,
children = _props.children,
props = objectWithoutProperties(_props, ['keyMap', 'handlers', 'focused', 'attach', 'children']);
return React__default.createElement(
FocusTrap,
_extends({}, props, { onFocus: this.onFocus, onBlur: this.onBlur }),
children
);
}
/**
* Updates the internal focused state and calls the onFocus prop if it is
* defined
*/
}, {
key: 'onFocus',
value: function onFocus() {
this.__isFocused__ = true;
if (this.props.onFocus) {
var _props2;
(_props2 = this.props).onFocus.apply(_props2, arguments);
}
}
/**
* Updates the internal focused state and calls the onBlur prop if it is
* defined.
*
* Also registers a null sequence as being handled by this component with
* its ancestor HotKeys.
*/
}, {
key: 'onBlur',
value: function onBlur() {
this.__isFocused__ = false;
if (this.props.onBlur) {
var _props3;
(_props3 = this.props).onBlur.apply(_props3, arguments);
}
if (this.context.hotKeyParent) {
this.context.hotKeyParent.childHandledSequence(null);
}
}
}]);
return HotKeys;
}(React.Component);
HotKeys.propTypes = {
/**
* A map from action names to Mousetrap key sequences
*/
keyMap: PropTypes.object,
/**
* A map from action names to event handler functions
*/
handlers: PropTypes.object,
/**
* Whether HotKeys should behave as if it has focus in the browser,
* whether it does or not - a way to force focus behaviour
*/
focused: PropTypes.bool,
/**
* The DOM element the keyboard listeners should be attached to
*/
attach: PropTypes.any,
/**
* Children to wrap within a focus trap
*/
children: PropTypes.node,
/**
* Function to call when this component gains focus in the browser
*/
onFocus: PropTypes.func,
/**
* Function to call when this component loses focus in the browser
*/
onBlur: PropTypes.func
};
HotKeys.childContextTypes = {
/**
* Reference to this instance of HotKeys so that any descendents are aware
* that they are being rendered within another HotKeys component
*/
hotKeyParent: PropTypes.any,
/**
* Reference to this instance's KeyMap so that any descendents may merge it
* into its own
*/
hotKeyMap: PropTypes.object
};
HotKeys.contextTypes = {
/**
* Reference to the most direct ancestor that is a HotKeys component (if one
* exists) so that messages may be passed to it when necessary
*/
hotKeyParent: PropTypes.any,
/**
* Reference to the KeyMap of its most direct HotKeys ancestor, so that it may
* be merged into this components
*/
hotKeyMap: PropTypes.object
};
/**
* withHotKeys is an HOC that provides the wrappedComponent with the ability to implement keyboard actions
* without the user wrapping every component with a <HotKeys> component individually
*
* See examples/master/HOCWrappedNode.js for an example implementation
* Follow the steps below to use the HOC:
*
* @example <caption>Example usage of withHotKeys.</caption>
* // Returns the HOC-wrapped component.
* // 1. Declared a key map that with the actionName as key and keyboardKeys as values
* const ACTION_KEY_MAP = {
* 'logConsole' : 'down',
* };
*
* class BasicBox extends React.Component {
*
* // 2. declare 'hotKeyHandlers' within the Component's class definition
* hotKeyHandlers: {
* 'logConsole': this.logConsole.bind(this),
* }
*
* logConsole() {
* console.log('a hotkey is pressed');
* }
*
* render() {
* return (
* <div tabIndex="0">
* Press the down arrow
* </div>
* );
* }
* }
*
* // 3. Wrap the Component with withHotKeys
* export default withHotKeys(ACTION_KEY_MAP)(BasicBox);
* @returns {function} Returns the HOC-wrapped component.
*
* @param {Object} keyMap an action-to-keyboard-key mapping
* @summary An HOC that provides the wrappedComponent with the ability to implement keyboard actions
*/
var withHotKeys = function withHotKeys(keyMap) {
return function (Component) {
return function (_PureComponent) {
inherits(HotKeysWrapper, _PureComponent);
function HotKeysWrapper(props) {
classCallCheck(this, HotKeysWrapper);
var _this = possibleConstructorReturn(this, (HotKeysWrapper.__proto__ || Object.getPrototypeOf(HotKeysWrapper)).call(this, props));
_this._setRef = _this._setRef.bind(_this);
_this.state = {
handlers: {}
};
return _this;
}
createClass(HotKeysWrapper, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.setState({ handlers: this._ref.hotKeyHandlers });
}
}, {
key: '_setRef',
value: function _setRef(node) {
this._ref = node;
}
}, {
key: 'render',
value: function render() {
var handlers = this.state.handlers;
// Setting component as documentfragment to avoid unexpected stylistic changes to the wrapped component
return React__default.createElement(
HotKeys,
{ component: 'document-fragment', keyMap: keyMap, handlers: handlers },
React__default.createElement(Component, _extends({
ref: this._setRef
}, this.props))
);
}
}]);
return HotKeysWrapper;
}(React.PureComponent);
};
};
function HotKeyMapMixin() {
var hotKeyMap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
return {
contextTypes: {
hotKeyMap: PropTypes.object
},
childContextTypes: {
hotKeyMap: PropTypes.object
},
getChildContext: function getChildContext() {
return {
hotKeyMap: this.__hotKeyMap__
};
},
componentWillMount: function componentWillMount() {
this.updateMap();
},
updateMap: function updateMap() {
var newMap = this.buildMap();
if (!isEqual(newMap, this.__hotKeyMap__)) {
this.__hotKeyMap__ = newMap;
return true;
}
return false;
},
buildMap: function buildMap() {
var parentMap = this.context.hotKeyMap || {};
var thisMap = this.props.keyMap || {};
return _extends({}, parentMap, hotKeyMap, thisMap);
},
getMap: function getMap() {
return this.__hotKeyMap__;
}
};
}
exports.HotKeys = HotKeys;
exports.withHotKeys = withHotKeys;
exports.FocusTrap = FocusTrap;
exports.HotKeyMapMixin = HotKeyMapMixin;
Object.defineProperty(exports, '__esModule', { value: true });
})));
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("prop-types"),require("react")):"function"==typeof define&&define.amd?define(["exports","prop-types","react"],t):t(e.ReactHotkeys={},e.PropTypes,e.React)}(this,function(e,t,n){"use strict";t=t&&t.hasOwnProperty("default")?t.default:t;var o="default"in n?n.default:n;function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return e.reduce(function(e,n){return e[n]=t||{value:n},e},{})}var r="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},s=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),u=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},l=function e(t,n,o){null===t&&(t=Function.prototype);var i=Object.getOwnPropertyDescriptor(t,n);if(void 0===i){var r=Object.getPrototypeOf(t);return null===r?void 0:e(r,n,o)}if("value"in i)return i.value;var s=i.get;return void 0!==s?s.call(o):void 0},h=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},y=function(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n},p=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},d=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var n=[],o=!0,i=!1,r=void 0;try{for(var s,a=e[Symbol.iterator]();!(o=(s=a.next()).done)&&(n.push(s.value),!t||n.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{!o&&a.return&&a.return()}finally{if(i)throw r}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),v=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)},f={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 _.option("_ignoreTagsDict")[n]||t.isContentEditable}return!1},simulateMissingKeyPressEvents:!0,stopEventPropagationAfterHandling:!0,stopEventPropagationAfterIgnoring:!0},g=c({},f);g._ignoreTagsDict=i(g.ignoreTags,!0);var _=function(){function e(){s(this,e)}return a(e,null,[{key:"init",value:function(e){var t=this;e.ignoreTags&&(e._ignoreTagsDict=i(e.ignoreTags)),Object.keys(e).forEach(function(n){t.set(n,e[n])})}},{key:"set",value:function(e,t){g[e]=t}},{key:"reset",value:function(e){g[e]=f[e]}},{key:"option",value:function(e){return g[e]}}]),e}(),k=function(){function e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"warn";s(this,e),this.verbose=this.noop,this.debug=this.noop,this.info=this.noop,this.warn=this.noop,this.error=this.noop,this.logLevel=this.constructor.levels[n],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 a(e,[{key:"noop",value:function(){}}]),e}();function m(e){return void 0===e}k.logIcons=["📕","📗","📘","📙"],k.componentIcons=["🔺","⭐️","🔷","🔶","⬛️"],k.eventIcons=["❤️","💚","💙","💛","💜","🧡"],k.levels={none:0,error:1,warn:2,info:3,debug:4,verbose:5};var b=function(){function e(){s(this,e)}return a(e,null,[{key:"newBitmap",value:function(e){var t=[!1,!1,!1];if(!m(e))for(var n=0;n<=e;n++)t[n]=!0;return t}},{key:"setBit",value:function(e,t){return e[t]=!0,e}},{key:"clone",value:function(e){for(var t=this.newBitmap(),n=0;n<e.length;n++)t[n]=e[n];return t}},{key:"and",value:function(e,t){for(var n=[],o=0;o<e.length;o++)n[o]=e[o]&t[o];return n}}]),e}(),E={keydown:0,keypress:1,keyup:2},C={"`":["~"],1:["!"],2:["@",'"'],3:["#","£"],4:["$"],5:["%"],6:["^"],7:["&"],8:["*"],9:["("],0:[")"],"-":["_"],"=":["plus"],";":[":"],"'":['"',"@"],",":["<"],".":[">"],"/":["?"],"\\":["|"],"[":["{"],"]":["}"],"#":["~"]};function K(e){return C[e]||[1===e.length?e.toUpperCase():e]}function I(e){return Object.keys(e).reduce(function(t,n){return e[n].forEach(function(e){var o;o=e,t.hasOwnProperty(o)||(t[e]=[]),t[e].push(n)}),t},{})}var S=I(C);function w(e){return S[e]||[1===e.length?e.toLowerCase():e]}var O={Backspace:["Delete"]};var H={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:"Backspace",command:"Meta",option:"Alt",enter:"Enter",backspace:"Backspace",ins:"Insert",pageup:"PageUp",pagedown:"PageDown",end:"End",home:"Home",contextmenu:"ContextMenu",numlock:"Clear"};function P(e){return H[e.toLowerCase()]||(e.match(/^f\d+$/)?e.toUpperCase():e)}var T={Shift:!0,Control:!0,Alt:!0,Meta:!0,Enter:!0,Tab:!0,CapsLock:!0,BackSpace:!0};function A(e){return!!T[e]||String.fromCharCode(e.charCodeAt(0))===e}var x=function(e){function t(){return s(this,t),p(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return h(t,e),t}(Error);function D(e){return e.sort().join("+")}var B=function(){function e(){s(this,e)}return a(e,null,[{key:"parse",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=("string"==typeof(t=e)?t.trim().replace(/\s+/g," "):t).split(" ");try{var i=o.slice(0,o.length-1),r=o[o.length-1],s=i.map(function(e){var t=L(e,n);return D(Object.keys(t))}).join(" "),a=L(r,n),u={id:D(Object.keys(a)),keyDictionary:a,eventBitmapIndex:n.eventBitmapIndex,size:Object.keys(a).length};return{sequence:{prefix:s,size:i.length+1},combination:u}}catch(e){return{sequence:null,combination:null}}}}]),e}();function L(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e.replace(/^\+|(\s|[^+]\+)\+/,"$1plus").split("+").reduce(function(e,n){var o=P(n);if(t.ensureValidKeys&&!A(o))throw new x;return e[o]=!0,e},{})}var j={"`":["`"],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:["Ω"],"[":["“"],"]":["‘"],"\\":["«"],"'":["æ"],";":["…"],",":["≤"],".":["≥"],"/":["÷"]},M=I(j);function F(e){return M[e]||[e]}function q(e){return j[e]||[e]}var N={"`":["`"],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:["¸"],"[":["”"],"]":["’"],"\\":["»"],"'":["Æ"],";":["Ú"],",":["¯"],".":["˘"]},U=I(N);function R(e){return U[e]||w(e)}function z(e){return N[e]||[e]}var G=function(){function e(){s(this,e)}return a(e,null,[{key:"serialize",value:function(e){var t=e.Shift,n=e.Alt,o={};return Object.keys(e).sort().forEach(function(e){var i=[];if(t)if(n){var r=R(e),s=z(e);i=[].concat(v(i),[e],v(r),v(s))}else{var a=w(e),l=K(e);i=[].concat(v(i),[e],v(a),v(l))}else if(n){var h=F(e),y=q(e);i=[].concat(v(i),[e],v(h),v(y))}else{i.push(e);var p=O[e];p&&(i=[].concat(v(i),v(p)))}var d=Object.keys(o);d.length>0?d.forEach(function(e){i.forEach(function(t){o[e+"+"+t]=c({},o[e],u({},t,!0))}),delete o[e]}):i.forEach(function(e){o[e]=u({},e,!0)})}),Object.values(o).map(function(e){return Object.keys(e).sort().join("+")})}},{key:"isValidKeySerialization",value:function(e){return e.length>0&&!!B.parse(e,{ensureValidKeys:!0}).combination}}]),e}();function W(e){return Array.isArray(e)?e:e?[e]:[]}function V(e,t){return e[e.length-(t+1)]}function $(e){return!Array.isArray(e)&&"object"===(void 0===e?"undefined":r(e))&&null!==e}function J(e){return $(e)?0===Object.keys(e).length:!e||0===e.length}function Q(e){switch(parseInt(e,10)){case 0:return"keydown";case 1:return"keypress";default:return"keyup"}}var X=0,Y=1;for(var Z={Shift:["shiftKey"],Meta:["metaKey"],Control:["ctrlKey"],Alt:["altKey"]},ee=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];s(this,e),this.logger=t.logger||new k("warn"),this.componentId=0,this.keyEventManager=n,this._reset(),this._resetKeyCombinationHistory()}return a(e,[{key:"_reset",value:function(){this._resetRegisteredKeyMapsState(),this._resetHandlerResolutionState()}},{key:"_resetRegisteredKeyMapsState",value:function(){this.componentList=[],this.longestSequence=1,this.longestSequenceComponentIndex=null,this.keyMapEventBitmap=b.newBitmap()}},{key:"_resetHandlerResolutionState",value:function(){this.keyMaps=null,this.handlerResolutionSearchIndex=0,this.unmatchedHandlerStatus=null,this.handlersDictionary={},this.keySequencesDictionary={}}},{key:"_resetKeyCombinationHistory",value:function(){if(this.keyCombinationIncludesKeyUp=!1,this.keypressEventsToSimulate=[],!this.keyCombinationHistory||this.keyCombinationHistory.length<1)this.keyCombinationHistory=[];else{var e=this._getCurrentKeyCombination(),t=Object.keys(e.keys).reduce(function(t,n){var o=e.keys[n],i=o[Y];return i[E.keydown]&&!i[E.keyup]&&(t[n]=o),t},{});this.keyCombinationHistory=[{keys:t,ids:G.serialize(t)}]}}},{key:"_addComponentToList",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=this._buildComponentOptions(e,t,n,o);return this.componentList.push(i),i}},{key:"_buildComponentOptions",value:function(e,t,n,o){var i=this._applyHardSequences(t,n),r=i.keyMap,s=i.handlers;return{actions:this._buildActionDictionary(c({},t,r),o,e),handlers:s,componentId:e,options:o}}},{key:"_applyHardSequences",value:function(e,t){return _.option("enableHardSequences")?Object.keys(t).reduce(function(n,o){return!!!e[o]&&G.isValidKeySerialization(o)&&(n.keyMap[o]=o),n.handlers[o]=t[o],n},{keyMap:{},handlers:{}}):{keyMap:e,handlers:t}}},{key:"_buildActionDictionary",value:function(e,t,n){var o=this;return Object.keys(e).reduce(function(i,r){return W(e[r]).forEach(function(e){var s=function(){if($(e)){var n=e.sequence,o=e.action;return{keySequence:n,eventBitmapIndex:m(o)?E[t.defaultKeyEvent]:E[o]}}return{keySequence:e,eventBitmapIndex:E[t.defaultKeyEvent]}}(),a=s.keySequence,u=s.eventBitmapIndex,l=B.parse(a,{eventBitmapIndex:u}),h=l.sequence,y=l.combination;h.size>o.longestSequence&&(o.longestSequence=h.size,o.longestSequenceComponentIndex=n),b.setBit(o.keyMapEventBitmap,u),i[r]||(i[r]=[]),i[r].push(c({prefix:h.prefix,actionName:r,sequenceLength:h.size},y))}),i},{})}},{key:"_getCurrentKeyCombination",value:function(){return this.keyCombinationHistory.length>0?this.keyCombinationHistory[this.keyCombinationHistory.length-1]:{keys:{},ids:[""],keyAliases:{}}}},{key:"_addToCurrentKeyCombination",value:function(e,t){0===this.keyCombinationHistory.length&&this.keyCombinationHistory.push({keys:{},ids:[""],keyAliases:{}});var n=this._getCurrentKeyCombination(),o=this._getKeyAlias(n,e),i=this._getKeyState(n,e);n.keys[o]=i?[b.clone(i[1]),b.newBitmap(t)]:[b.newBitmap(),b.newBitmap(t)],n.ids=G.serialize(n.keys),n.keyAliases=this._buildCombinationKeyAliases(n.keys),t===E.keyup&&(this.keyCombinationIncludesKeyUp=!0)}},{key:"_startNewKeyCombination",value:function(e,t){this.keyCombinationHistory.length>this.longestSequence&&this.keyCombinationHistory.shift();var n=this._getCurrentKeyCombination(),o=c({},this._withoutKeyUps(n),u({},e,[b.newBitmap(),b.newBitmap(t)]));this.keyCombinationHistory.push({keys:o,ids:G.serialize(o),keyAliases:this._buildCombinationKeyAliases(o)}),this.keyCombinationIncludesKeyUp=!1}},{key:"_withoutKeyUps",value:function(e){return Object.keys(e.keys).reduce(function(t,n){var o=e.keys[n];return o[Y][E.keyup]||(t[n]=o),t},{})}},{key:"_callMatchingHandlerClosestToEventTarget",value:function(e,t,n,o,i){var r=this;for(this.keyMaps&&this.unmatchedHandlerStatus||(this.keyMaps=[],this.unmatchedHandlerStatus=[],this.componentList.forEach(function(e){var t=e.handlers;r.unmatchedHandlerStatus.push([Object.keys(t).length,{}]),r.keyMaps.push({})}));i<=o;){var s=this.unmatchedHandlerStatus[i][0];if(s>0)for(var a=function(){var e=r.componentList[r.handlerResolutionSearchIndex],t=e.handlers,n=e.actions;Object.keys(t).forEach(function(e){r.handlersDictionary[e]||(r.handlersDictionary[e]=[]),r.handlersDictionary[e].push(r.handlerResolutionSearchIndex)}),Object.keys(n).forEach(function(e){var t=r.handlersDictionary[e];if(t){var o=t[0],i=r.componentList[o].handlers[e],s=r.keyMaps[o];s.sequences||(s.sequences={}),n[e].forEach(function(e){var t=[e.prefix,e.id].join(" ");if(!(r.keySequencesDictionary[t]&&r.keySequencesDictionary[t].some(function(t){return t[1]===e.eventBitmapIndex}))){s.sequences[e.prefix]||(s.sequences[e.prefix]={combinations:{}});var n=e.prefix,a=e.sequenceLength,l=e.id,h=e.keyDictionary,y=e.size,p=e.eventBitmapIndex,d=e.actionName,v=s.sequences[e.prefix].combinations[e.id];s.sequences[e.prefix].combinations[e.id]=v?c({},v,{events:c({},v.events,u({},p,{actionName:d,eventBitmapIndex:p,handler:i}))}):{prefix:n,sequenceLength:a,id:l,keyDictionary:h,size:y,events:u({},p,{actionName:d,eventBitmapIndex:p,handler:i})},s.eventBitmap||(s.eventBitmap=b.newBitmap()),b.setBit(s.eventBitmap,e.eventBitmapIndex),(!s.longestSequence||s.longestSequence<e.sequenceLength)&&(s.longestSequence=e.sequenceLength),r.keySequencesDictionary[t]||(r.keySequencesDictionary[t]=[]),r.keySequencesDictionary[t].push([o,e.eventBitmapIndex])}}),t.forEach(function(t){var n=r.unmatchedHandlerStatus[t];n[1][e]||(n[1][e]=!0,n[0]--)})}}),r.handlerResolutionSearchIndex++};this.handlerResolutionSearchIndex<this.componentList.length&&s>0;)a();var l=this.keyMaps[i];if(l&&!J(l.sequences)&&l.eventBitmap[n])for(var h=l.sequences,y=l.longestSequence,p=this._getCurrentKeyCombination(),d=this._getKeyAlias(p,t),v=y;v>=0;){var f=this.keyCombinationHistory.slice(-v,-1).map(function(e){return e.ids}),g=this._tryMatchSequenceWithKeyAliases(h,f);if(g){g.order||function(){var e=Object.values(g.combinations).reduce(function(e,t){var n=t.id,o=t.size;return e[o]||(e[o]=[]),e[o].push(n),e},{});g.order=Object.keys(e).sort(function(e,t){return t-e}).reduce(function(t,n){return t.concat(e[n])},[])}();for(var _=g.order,k=0;k<_.length;){var m=_[k],E=g.combinations[m];if(this._combinationMatchesKeys(d,p,E,n)){G.serialize(E.keyDictionary);return E.events[n].handler(e),this._stopEventPropagationAfterHandlingIfEnabled(e,i),!0}k++}}v--}else;i++}}},{key:"_stopEventPropagationAfterHandlingIfEnabled",value:function(e,t){return!!_.option("stopEventPropagationAfterHandling")&&(this._stopEventPropagation(e,t),!0)}},{key:"_stopEventPropagationAfterIgnoringIfEnabled",value:function(e,t){return!!_.option("stopEventPropagationAfterIgnoring")&&(this._stopEventPropagation(e,t),!0)}},{key:"_stopEventPropagation",value:function(e,t){e.stopPropagation()}},{key:"_describeCurrentKeyCombination",value:function(){return this._getCurrentKeyCombination().ids[0]}},{key:"_tryMatchSequenceWithKeyAliases",value:function(e,t){if(0===t.length)return e[""];for(var n=t.map(function(e){return e.length}),o=t.map(function(){return 0}),i=!1;!i;){var r=o.map(function(e,n){return t[n][e]}).join(" ");if(e[r])return e[r];for(var s=0,a=!0;a&&s<o.length;){var u=(V(o,s)+1)%(V(n,s)||1);o[o.length-(s+1)]=u,(a=0===u)&&s++}i=s===o.length}}},{key:"_combinationMatchesKeys",value:function(e,t,n,o){var i=this;if(!n.events[o])return!1;var r=!1;return!Object.keys(n.keyDictionary).some(function(n){var s=i._getKeyState(t,n);return!s||(!i._keyIsCurrentlyTriggeringEvent(s,o)||(e&&e===i._getKeyAlias(t,n)&&(r=!i._keyAlreadyTriggeredEvent(s,o)),!1))})&&r}},{key:"_checkForModifierFlagDiscrepancies",value:function(e){var t=this;Object.keys(Z).forEach(function(n){var o=t._getCurrentKeyState(n),i=o&&!t._keyIsCurrentlyTriggeringEvent(o,E.keyup);Z[n].forEach(function(o){!1===e[o]&&i&&t._addToCurrentKeyCombination(n,E.keyup)})})}},{key:"_keyIsCurrentlyTriggeringEvent",value:function(e,t){return e&&e[Y][t]}},{key:"_keyAlreadyTriggeredEvent",value:function(e,t){return e&&e[X][t]}},{key:"_getCurrentKeyState",value:function(e){var t=this._getCurrentKeyCombination();return this._getKeyState(t,e)}},{key:"_getKeyState",value:function(e,t){var n=e.keys[t];if(n)return n;var o=e.keyAliases[t];return o?e.keys[o]:void 0}},{key:"_getKeyAlias",value:function(e,t){if(e.keys[t])return t;var n=e.keyAliases[t];return n||t}},{key:"_buildCombinationKeyAliases",value:function(e){var t=function(){if(e.Shift)return e.Alt?[z,R]:[K,w];if(e.Alt)return[q,F];var t=function(e){return[e]};return[t,t]}();return Object.keys(e).reduce(function(e,n){return function(e){return O[e]||[e]}(n).forEach(function(o){t.forEach(function(t){t(o).forEach(function(t){t===n&&n===o||(e[t]=n)})})}),e},{})}}]),e}(),te=function(){function e(){s(this,e)}return a(e,null,[{key:"getId",value:function(){return m(this.id)&&(this.id=0),this.id}},{key:"incrementId",value:function(){this.id=this.getId()+1}}]),e}(),ne={Shift:!0,Control:!0,Alt:!0,Meta:!0,Enter:!0,Tab:!0,BackSpace:!0,ArrowRight:!0,ArrowLeft:!0,ArrowUp:!0,ArrowDown:!0,CapsLock:!0},oe=1;oe<13;oe++)ne["F"+oe]=!0;function ie(e){return!ne[e]}function re(e){return"+"===e?"plus":e}var se=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];s(this,t);var o=p(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o.focusTreeId=0,o.currentEvent={key:null,type:null,handled:!1},o}return h(t,ee),a(t,[{key:"_reset",value:function(){l(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_reset",this).call(this),this.componentId=0,this.focusTreeId+=1,this._clearEventPropagationState()}},{key:"_clearEventPropagationState",value:function(){this.eventPropagationState={previousComponentIndex:-1,actionHandled:!1,ignoreEvent:!1}}},{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];return(this.resetOnNextFocus||this.keyMaps)&&(this._reset(),this.resetOnNextFocus=!1),this.componentId=this.componentList.length,this._addComponentToList(this.componentId,e,t,n),[this.focusTreeId,this.componentId]}},{key:"updateHotKeys",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments[4];e===this.focusTreeId&&this.componentList[t]&&(this.componentList[t]=this._buildComponentOptions(t,n,o,i))}},{key:"removeHotKeys",value:function(e,t){return this.resetOnNextFocus||(this.resetOnNextFocus=!0),this.eventPropagationState.previousComponentIndex+1<t}},{key:"handleKeydown",value:function(e,t,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=re(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())return this._ignoreEvent(e,n),!1;if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,E.keydown),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return this._ignoreEvent(e,n),!1;this._checkForModifierFlagDiscrepancies(e),!!this._getCurrentKeyState(i)||this.keyCombinationIncludesKeyUp?this._startNewKeyCombination(i,E.keydown,t,n):this._addToCurrentKeyCombination(i,E.keydown,t,n)}return this._callHandlerIfActionNotHandled(e,i,E.keydown,n,t),!ie(i)&&_.option("simulateMissingKeyPressEvents")&&(e.persist(),this.keypressEventsToSimulate.push({event:e,focusTreeId:t,componentId:n,options:o,key:i})),this._isFocusTreeRoot(n)&&(this.keyEventManager.isGlobalListenersBound()||this.simulatePendingKeyPressEvents(i)),this._updateEventPropagationHistory(n),!1}},{key:"simulatePendingKeyPressEvents",value:function(){var e=this;this.keypressEventsToSimulate.length>0&&te.incrementId(),this.keypressEventsToSimulate.forEach(function(t){var n=t.event,o=t.focusTreeId,i=t.componentId,r=t.options;e.handleKeypress(n,o,i,r)}),this.keypressEventsToSimulate=[],this._clearEventPropagationState()}},{key:"handleKeypress",value:function(e,t,n,o){var i=re(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())this._ignoreEvent(e,n);else{if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,E.keypress),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return void this._ignoreEvent(e,n);var r=this._getCurrentKeyState(i);r&&(r[Y][E.keypress]||r[Y][E.keyup])?this._startNewKeyCombination(i,E.keypres,t,n):this._addToCurrentKeyCombination(i,E.keypress,t,n)}this._callHandlerIfActionNotHandled(e,i,E.keypress,n,t),this._updateEventPropagationHistory(n)}}},{key:"handleKeyup",value:function(e,t,n,o){var i=re(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())this._ignoreEvent(e,n);else{if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,E.keyup),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return void this._ignoreEvent(e,n);var r=this._getCurrentKeyState(i);r&&r[Y][E.keyup]?this._startNewKeyCombination(i,E.keyup,t,n):this._addToCurrentKeyCombination(i,E.keyup,t,n)}this._callHandlerIfActionNotHandled(e,i,E.keyup,n,t),this._updateEventPropagationHistory(n)}}},{key:"_ignoreEvent",value:function(e,t){this._stopEventPropagationAfterIgnoringIfEnabled(e,t)?this._updateEventPropagationHistory(t,{forceReset:!0}):this._updateEventPropagationHistory(t)}},{key:"_alreadyEstablishedShouldIgnoreEvent",value:function(){return this.eventPropagationState.ignoreEvent}},{key:"_isNewKeyEvent",value:function(e){var t=this.eventPropagationState.previousComponentIndex;return-1===t||t>=e}},{key:"_updateEventPropagationHistory",value:function(e){(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{forceReset:!1}).forceReset||this._isFocusTreeRoot(e)?this._clearEventPropagationState():this.eventPropagationState.previousComponentIndex=e}},{key:"_setIgnoreEventFlag",value:function(e,t){this.eventPropagationState.ignoreEvent=t.ignoreEventsCondition(e)}},{key:"ignoreEvent",value:function(e){this.eventPropagationState.ignoreEvent=!0}},{key:"_isFocusTreeRoot",value:function(e){return e>=this.componentList.length-1}},{key:"_setNewEventParameters",value:function(e,t){te.incrementId(),this.currentEvent={key:e.key,type:t,handled:!1}}},{key:"_startNewKeyCombination",value:function(e,n,o,i){l(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_startNewKeyCombination",this).call(this,e,n)}},{key:"_addToCurrentKeyCombination",value:function(e,n,o,i){l(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addToCurrentKeyCombination",this).call(this,e,n)}},{key:"_callHandlerIfActionNotHandled",value:function(e,t,n,o,i){this._describeCurrentKeyCombination();if(this.keyMapEventBitmap[n])if(this.eventPropagationState.actionHandled);else{var r=this.eventPropagationState.previousComponentIndex;this._callMatchingHandlerClosestToEventTarget(e,t,n,o,-1===r?0:r)&&(this.eventPropagationState.actionHandled=!0,this.currentEvent.handled=!0)}}},{key:"_logPrefix",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=k.logIcons,o=k.eventIcons,i=k.componentIcons,r="HotKeys (";if(!1!==t.focusTreeId){var s=m(t.focusTreeId)?this.focusTreeId:t.focusTreeId;r+="FT"+s+n[s%n.length]+"-"}if(!1!==t.eventId){var a=m(t.eventId)?te.getId():t.eventId;r+="E"+a+o[a%o.length]+"-"}return r+"C"+e+i[e%i.length]+"):"}}]),t}();var ae={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},ue={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"};function ce(e){if(e.key){var t=ae[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=function(e){var t=void 0,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,10===t&&(t=13),t>=32||13===t?t:0}(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?ue[e.keyCode]||"Unidentified":""}var le=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];s(this,t);var o=p(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o.componentId=-1,o.listenersBound=!1,o.eventOptions={ignoreEventsCondition:_.option("ignoreEventsCondition")},o}return h(t,ee),a(t,[{key:"_reset",value:function(){l(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_reset",this).call(this),this.componentIdDict={}}},{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2],o=arguments[3];return this.eventOptions=o,this.componentId+=1,this._addComponentToList(this.componentId,e,t,n),this._updateDocumentHandlers(),this.componentId}},{key:"updateHotKeys",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=arguments[4];this.eventOptions=i;var r=this._getComponentPosition(e);this.componentList[r]=this._buildComponentOptions(e,t,n,o),this._updateLongestKeySequenceIfNecessary(e),this._updateDocumentHandlers(),this._resetHandlerResolutionState()}},{key:"removeHotKeys",value:function(e){var t,n,o=this._getComponentAndPosition(e),i=d(o,2),r=i[0].keyMapEventBitmap,s=i[1];this.componentList=(t=this.componentList,n=s,[].concat(v(t.slice(0,n)),v(t.slice(n+1)))),this._updateLongestKeySequenceIfNecessary(e),this._updateComponentIndexDictFromList({startingAt:s}),this._updateDocumentHandlers(r,b.newBitmap()),this._resetHandlerResolutionState()}},{key:"_addComponentToList",value:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments[3];l(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addComponentToList",this).call(this,e,n,o,i),this._setComponentPosition(e,this.componentList.length-1)}},{key:"_setComponentPosition",value:function(e,t){this.componentIdDict[e]=t}},{key:"_updateLongestKeySequenceIfNecessary",value:function(e){var t=this;e===this.longestSequenceComponentIndex&&(this.longestSequence=1,this.componentList.forEach(function(e){var n=e.longestSequence;n>t.longestSequence&&(t.longestSequence=n)}))}},{key:"_updateComponentIndexDictFromList",value:function(){for(var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{startingAt:0}).startAt;e<this.componentList.length;)this._setComponentPosition(this.componentList[e].componentId,e)}},{key:"_updateDocumentHandlers",value:function(){var e=this,t=this.keyMapEventBitmap.some(function(e){return e});if(!this.listenersBound&&t){for(var n=function(t){var n=Q(t);document["on"+n]=function(t){var o;e.keyEventManager["handleGlobal"+(o=n,o.replace(/\b\w/g,function(e){return e.toUpperCase()}))](t)}},o=0;o<this.keyMapEventBitmap.length;o++)n(o);this.listenersBound=!0}else if(this.listenersBound&&!t){for(o=0;o<this.keyMapEventBitmap.length;o++){var i=Q(o);delete document["on"+i]}this.listenersBound=!1}}},{key:"handleKeydown",value:function(e){this._checkForModifierFlagDiscrepancies(e);var t=re(ce(e));!!this._getCurrentKeyState(t)||this.keyCombinationIncludesKeyUp?this._startNewKeyCombination(t,E.keydown):this._addToCurrentKeyCombination(t,E.keydown);var n=this.keyEventManager.reactAppHistoryWithEvent(t,E.keydown);if("handled"===n);else{if("seen"===n||te.incrementId(),this.eventOptions.ignoreEventsCondition(e))return;this._callHandlerIfExists(e,t,E.keydown),ie(t)||(this.keyEventManager.simulatePendingKeyPressEvents(),this.handleKeypress(e))}}},{key:"handleKeypress",value:function(e){var t=re(ce(e)),n=this._getCurrentKeyState(t);n&&(n[Y][E.keypress]||n[Y][E.keyup])?this._startNewKeyCombination(t,E.keypress):this._addToCurrentKeyCombination(t,E.keypress);var o=this.keyEventManager.reactAppHistoryWithEvent(t,E.keypress);return"handled"!==o&&("seen"===o||te.incrementId(),!this.eventOptions.ignoreEventsCondition(e)&&void this._callHandlerIfExists(e,t,E.keypress))}},{key:"handleKeyup",value:function(e){var t=re(ce(e)),n=this._getCurrentKeyState(t);n&&n[Y][E.keyup]?this._startNewKeyCombination(t,E.keyup):this._addToCurrentKeyCombination(t,E.keyup);var o=this.keyEventManager.reactAppHistoryWithEvent(t,E.keyup);return"handled"!==o&&("seen"===o||te.incrementId(),!this.eventOptions.ignoreEventsCondition(e)&&void this._callHandlerIfExists(e,t,E.keyup))}},{key:"_startNewKeyCombination",value:function(e,n){l(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_startNewKeyCombination",this).call(this,e,n)}},{key:"_addToCurrentKeyCombination",value:function(e,n){l(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addToCurrentKeyCombination",this).call(this,e,n)}},{key:"_getComponentPosition",value:function(e){return this.componentIdDict[e]}},{key:"_getComponent",value:function(e){var t=this._getComponentPosition(e);return this.componentList[t]}},{key:"_getComponentAndPosition",value:function(e){var t=this._getComponentPosition(e);return[this.componentList[t],t]}},{key:"_callHandlerIfExists",value:function(e,t,n){this._describeCurrentKeyCombination();this.keyMapEventBitmap[n]&&this._callMatchingHandlerClosestToEventTarget(e,t,n)}},{key:"_callMatchingHandlerClosestToEventTarget",value:function(e,n,o){for(var i=0;i<this.componentList.length;i++){if(l(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_callMatchingHandlerClosestToEventTarget",this).call(this,e,n,o,i,0))return}}},{key:"_logPrefix",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=k.eventIcons,o=k.componentIcons,i="HotKeys (GLOBAL";if(!1!==t.eventId){var r=m(t.eventId)?te.getId():t.eventId;i=i+"-E"+r+n[r%n.length]}return m(e)?i+"):":i+"-C"+e+o[e%o.length]+"):"}}]),t}();function he(e){return!m(e)}var ye=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};s(this,e),this.logger=t.logger||new k(_.option("logLevel")),this._focusOnlyEventStrategy=new se({configuration:t,logger:this.logger},this),this._globalEventStrategy=new le({configuration:t,logger:this.logger},this),this.lastEventSeen=null}return a(e,null,[{key:"getInstance",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.instance||(this.instance=new e(t)),this.instance}},{key:"clear",value:function(){delete this.instance}}]),a(e,[{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];return this._focusOnlyEventStrategy.addHotKeys(e,t,n)}},{key:"updateHotKeys",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments[4];return this._focusOnlyEventStrategy.updateHotKeys(e,t,n,o,i)}},{key:"removeHotKeys",value:function(e,t){return this._focusOnlyEventStrategy.removeHotKeys(e,t)}},{key:"handleKeydown",value:function(e,t,n,o){if(he(t))return this._focusOnlyEventStrategy.handleKeydown(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"handleKeypress",value:function(e,t,n,o){if(he(t))return this._focusOnlyEventStrategy.handleKeypress(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"handleKeyup",value:function(e,t,n,o){if(he(t))return this._focusOnlyEventStrategy.handleKeyup(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"_recordLastSeenEvent",value:function(e){var t=e.key,n=e.type,o=e.nativeEvent;this.lastEventSeen={key:t,type:n,nativeEvent:o}}},{key:"addGlobalHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2],o=arguments[3];return this._globalEventStrategy.addHotKeys(e,t,n,o)}},{key:"updateGlobalHotKeys",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=arguments[4];return this._globalEventStrategy.updateHotKeys(e,t,n,o,i)}},{key:"removeGlobalHotKeys",value:function(e){return this._globalEventStrategy.removeHotKeys(e)}},{key:"handleGlobalKeydown",value:function(e){return this._globalEventStrategy.handleKeydown(e)}},{key:"handleGlobalKeypress",value:function(e){return this._globalEventStrategy.handleKeypress(e)}},{key:"handleGlobalKeyup",value:function(e){return this._globalEventStrategy.handleKeyup(e)}},{key:"ignoreEvent",value:function(e){this._focusOnlyEventStrategy.ignoreEvent(e)}},{key:"reactAppHistoryWithEvent",value:function(e,t){var n=this._focusOnlyEventStrategy.currentEvent;return n.key===e&&n.type===t?n.handled?"handled":"seen":"unseen"}},{key:"simulatePendingKeyPressEvents",value:function(){this._focusOnlyEventStrategy.simulatePendingKeyPressEvents()}},{key:"isGlobalListenersBound",value:function(){return this._globalEventStrategy.listenersBound}}]),e}();function pe(e){var i,r,u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};function l(e,t){return c({},u[e]||{},t[e]||{})}function v(e){return l("handlers",e)}function f(e){return l("keyMap",e)}return r=i=function(t){function n(e){s(this,n);var t=p(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t._handleFocus=t._handleFocus.bind(t),t._handleBlur=t._handleBlur.bind(t),t._handleKeyDown=t._handleKeyDown.bind(t),t._handleKeyPress=t._handleKeyPress.bind(t),t._handleKeyUp=t._handleKeyUp.bind(t),t._componentIsFocused=t._componentIsFocused.bind(t),t}return h(n,t),a(n,[{key:"render",value:function(){var t=this.props,n=(t.keyMap,t.handlers,t.allowChanges,y(t,["keyMap","handlers","allowChanges"])),i={onFocus:this._wrapFunction("onFocus",this._handleFocus),onBlur:this._wrapFunction("onBlur",this._handleBlur),tabIndex:_.option("defaultTabIndex")};return this._shouldBindKeyListeners()&&(i.onKeyDown=this._handleKeyDown,i.onKeyPress=this._handleKeyPress,i.onKeyUp=this._handleKeyUp),o.createElement(e,c({hotKeys:i},n))}},{key:"_shouldBindKeyListeners",value:function(){var e=f(this.props);return!J(e)||_.option("enableHardSequences")&&this._handlersIncludeHardSequences(e,v(this.props))}},{key:"_handlersIncludeHardSequences",value:function(e,t){return Object.keys(t).some(function(t){return!e[t]&&G.isValidKeySerialization(t)})}},{key:"_wrapFunction",value:function(e,t){var n=this;return"function"==typeof this.props[e]?function(o){n.props[e](o),t(o)}:t}},{key:"_focusTreeIdsPush",value:function(e){this._focusTreeIds||(this._focusTreeIds=[]),this._focusTreeIds.push(e)}},{key:"_focusTreeIdsShift",value:function(){this._focusTreeIds&&this._focusTreeIds.shift()}},{key:"_getFocusTreeId",value:function(){if(this._focusTreeIds)return this._focusTreeIds[0]}},{key:"componentDidUpdate",value:function(e){if(this._componentIsFocused()&&(this.props.allowChanges||!_.option("ignoreKeymapAndHandlerChangesByDefault"))){var t=this.props,n=t.keyMap,o=t.handlers;ye.getInstance().updateHotKeys(this._getFocusTreeId(),this._componentId,n,o,this._getComponentOptions())}}},{key:"componentWillUnmount",value:function(){this._handleBlur()}},{key:"_componentIsFocused",value:function(){return!0===this._focused}},{key:"_handleFocus",value:function(){var e;this.props.onFocus&&(e=this.props).onFocus.apply(e,arguments);var t=ye.getInstance().addHotKeys(f(this.props),v(this.props),this._getComponentOptions()),n=d(t,2),o=n[0],i=n[1];this._componentId=i,this._focusTreeIdsPush(o),this._focused=!0}},{key:"_handleBlur",value:function(){var e;this.props.onBlur&&(e=this.props).onBlur.apply(e,arguments);ye.getInstance().removeHotKeys(this._getFocusTreeId(),this._componentId)||this._focusTreeIdsShift(),this._focused=!1}},{key:"_handleKeyDown",value:function(e){ye.getInstance().handleKeydown(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_handleKeyPress",value:function(e){ye.getInstance().handleKeypress(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_handleKeyUp",value:function(e){ye.getInstance().handleKeyup(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_getComponentOptions",value:function(){return{defaultKeyEvent:_.option("defaultKeyEvent")}}},{key:"_getEventOptions",value:function(){return{ignoreEventsCondition:_.option("ignoreEventsCondition")}}}]),n}(n.PureComponent),i.propTypes={keyMap:t.object,handlers:t.object,onFocus:t.func,onBlur:t.func,allowChanges:t.bool},r}var de=pe(function(e){function t(){return s(this,t),p(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return h(t,e),a(t,[{key:"render",value:function(){var e=this.props,t=e.hotKeys,n=y(e,["hotKeys"]),i=n.component||_.option("defaultComponent");return o.createElement(i,c({},t,n))}}]),t}(n.Component));function ve(e){var i,r,u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{only:[],except:[]};return r=i=function(t){function n(e){s(this,n);var t=p(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t._handleKeyEvent=t._handleKeyEvent.bind(t),t._reloadDictionaries=t._reloadDictionaries.bind(t),t}return h(n,t),a(n,[{key:"getDefaultProps",value:function(){return u}}]),a(n,[{key:"render",value:function(){var t=this.props,n=(t.only,t.except,y(t,["only","except"])),i={onKeyDown:this._handleKeyEvent,onKeyPress:this._handleKeyEvent,onKeyUp:this._handleKeyEvent,onFocus:this._reloadDictionaries};return o.createElement(e,c({hotKeys:i},n))}},{key:"_reloadDictionaries",value:function(){var e=this.props,t=e.only,n=e.except;this._onlyDict=fe(t),this._exceptDict=fe(n)}},{key:"_shouldIgnoreEvent",value:function(e){var t=e.key;return J(this._onlyDict)?!!J(this._exceptDict)||!this._exceptDict[t]:J(this._exceptDict)?this._onlyDict[t]:this._onlyDict[t]&&!this._exceptDict[t]}},{key:"_handleKeyEvent",value:function(e){this._shouldIgnoreEvent(e)&&ye.getInstance().ignoreEvent(e)}}]),n}(n.PureComponent),i.propTypes={only:t.oneOfType([t.string,t.arrayOf(t.string)]),except:t.oneOfType([t.string,t.arrayOf(t.string)])},r}function fe(e){return W(e).reduce(function(e,t){var n=P(t);if(!A(n))throw new x(t);return[z,R,K,w,q,F].forEach(function(t){e[t(n)]=!0}),e},{})}var ge=ve(function(e){function t(){return s(this,t),p(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return h(t,e),a(t,[{key:"render",value:function(){var e=this.props,t=e.hotKeys,n=y(e,["hotKeys"]),i=n.component||_.option("defaultComponent");return o.createElement(i,c({},t,n))}}]),t}(n.Component)),_e=function(e){function t(){return s(this,t),p(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return h(t,e),a(t,[{key:"render",value:function(){return this.props.children||null}},{key:"componentDidUpdate",value:function(){if(this.props.allowChanges||!_.option("ignoreKeymapAndHandlerChangesByDefault")){var e=this.props,t=e.keyMap,n=e.handlers;ye.getInstance().updateGlobalHotKeys(this._id,t,n,this._getComponentOptions(),this._getEventOptions())}}},{key:"componentDidMount",value:function(){var e=this.props,t=e.keyMap,n=e.handlers;this._id=ye.getInstance().addGlobalHotKeys(t,n,this._getComponentOptions(),this._getEventOptions())}},{key:"componentWillUnmount",value:function(){ye.getInstance().removeGlobalHotKeys(this._id)}},{key:"_getComponentOptions",value:function(){return{defaultKeyEvent:_.option("defaultKeyEvent")}}},{key:"_getEventOptions",value:function(){return{ignoreEventsCondition:_.option("ignoreEventsCondition")}}}]),t}(n.Component);_e.propTypes={keyMap:t.object,handlers:t.object,onFocus:t.func,onBlur:t.func,allowChanges:t.bool},e.HotKeys=de,e.HotKeysIgnore=ge,e.withHotKeysIgnore=ve,e.GlobalHotKeys=_e,e.withHotKeys=pe,e.configure=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_.init(e)},Object.defineProperty(e,"__esModule",{value:!0})});

@@ -9,4 +9,6 @@ /**

* 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.
*
* PLEASE NOTE: SOURCE CODE FOUND IN THE lib/vendor DIRECTORY IS UNDER THE MIT LICENSE - PLEASE SEE THE LICENSE FILE FOR EACH DIRECTORY FOR MORE INFORMATION
*/
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("prop-types"),require("react"),require("lodash.isequal"),require("react-dom"),require("lodash.isboolean"),require("lodash.isobject")):"function"==typeof define&&define.amd?define(["exports","prop-types","react","lodash.isequal","react-dom","lodash.isboolean","lodash.isobject"],t):t(e.ReactHotkeys={},e.PropTypes,e.React,e.isEqual,e.ReactDOM,e.isBool,e.isObject)}(this,function(e,t,n,o,r,a,i){"use strict";t=t&&t.hasOwnProperty("default")?t.default:t;var u="default"in n?n.default:n;o=o&&o.hasOwnProperty("default")?o.default:o,r=r&&r.hasOwnProperty("default")?r.default:r,a=a&&a.hasOwnProperty("default")?a.default:a,i=i&&i.hasOwnProperty("default")?i.default:i;var s=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},c=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),p=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},h=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},l=function(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n},d=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},f=function(e){function t(){return s(this,t),d(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return h(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.component,n=e.children,o=l(e,["component","children"]);return u.createElement(t,p({tabIndex:"-1"},o),n)}}]),t}(n.Component);f.propTypes={onFocus:t.func,onBlur:t.func,component:t.oneOfType([t.func,t.string]),children:t.node},f.defaultProps={component:"div"};var y=function(e){function t(e,n){s(this,t);var o=d(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o.onFocus=o.onFocus.bind(o),o.onBlur=o.onBlur.bind(o),o}return h(t,e),c(t,[{key:"getChildContext",value:function(){return{hotKeyParent:this,hotKeyMap:this.__hotKeyMap__}}},{key:"componentWillMount",value:function(){this.updateMap()}},{key:"updateMap",value:function(){var e=this.buildMap();return!o(e,this.__hotKeyMap__)&&(this.__hotKeyMap__=e,!0)}},{key:"buildMap",value:function(){var e=this.context.hotKeyMap||{},t=this.props.keyMap||{};return p({},e,t)}},{key:"getMap",value:function(){return this.__hotKeyMap__}},{key:"componentDidMount",value:function(){var e=require("mousetrap");this.__mousetrap__=new e(this.props.attach||r.findDOMNode(this)),this.updateHotKeys(!0)}},{key:"componentDidUpdate",value:function(e){this.updateHotKeys(!1,e)}},{key:"componentWillUnmount",value:function(){this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(null),this.__mousetrap__&&this.__mousetrap__.reset()}},{key:"updateHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=this.props.handlers,r=void 0===n?{}:n,a=t.handlers,i=void 0===a?r:a,u=this.updateMap();(e||u||!o(r,i))&&(this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(null),this.syncHandlersToMousetrap())}},{key:"syncHandlersToMousetrap",value:function(){var e=this,t=this.props.handlers,n=void 0===t?{}:t,o=this.getMap(),r=[],u=this.__mousetrap__;Object.keys(n).forEach(function(t){var u=n[t];(function(e,t){var n=e[t];return n?Array.isArray(n)?n:[n]:[t]})(o,t).forEach(function(t){var n=void 0;i(t)&&(n=t.action,t=t.sequence),r.push({callback:function(t,n){if((a(e.props.focused)?e.props.focused:e.__isFocused__)&&n!==e.__lastChildSequence__)return e.context.hotKeyParent&&e.context.hotKeyParent.childHandledSequence(n),u(t,n)},action:n,sequence:t})})}),u.reset(),r.forEach(function(e){var t=e.sequence,n=e.callback,o=e.action;return u.bind(t,n,o)})}},{key:"childHandledSequence",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;this.__lastChildSequence__=e,this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(e)}},{key:"render",value:function(){var e=this.props,t=(e.keyMap,e.handlers,e.focused,e.attach,e.children),n=l(e,["keyMap","handlers","focused","attach","children"]);return u.createElement(f,p({},n,{onFocus:this.onFocus,onBlur:this.onBlur}),t)}},{key:"onFocus",value:function(){var e;(this.__isFocused__=!0,this.props.onFocus)&&(e=this.props).onFocus.apply(e,arguments)}},{key:"onBlur",value:function(){var e;(this.__isFocused__=!1,this.props.onBlur)&&(e=this.props).onBlur.apply(e,arguments);this.context.hotKeyParent&&this.context.hotKeyParent.childHandledSequence(null)}}]),t}(n.Component);y.propTypes={keyMap:t.object,handlers:t.object,focused:t.bool,attach:t.any,children:t.node,onFocus:t.func,onBlur:t.func},y.childContextTypes={hotKeyParent:t.any,hotKeyMap:t.object},y.contextTypes={hotKeyParent:t.any,hotKeyMap:t.object};e.HotKeys=y,e.withHotKeys=function(e){return function(t){return function(n){function o(e){s(this,o);var t=d(this,(o.__proto__||Object.getPrototypeOf(o)).call(this,e));return t._setRef=t._setRef.bind(t),t.state={handlers:{}},t}return h(o,n),c(o,[{key:"componentDidMount",value:function(){this.setState({handlers:this._ref.hotKeyHandlers})}},{key:"_setRef",value:function(e){this._ref=e}},{key:"render",value:function(){var n=this.state.handlers;return u.createElement(y,{component:"document-fragment",keyMap:e,handlers:n},u.createElement(t,p({ref:this._setRef},this.props)))}}]),o}(n.PureComponent)}},e.FocusTrap=f,e.HotKeyMapMixin=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{contextTypes:{hotKeyMap:t.object},childContextTypes:{hotKeyMap:t.object},getChildContext:function(){return{hotKeyMap:this.__hotKeyMap__}},componentWillMount:function(){this.updateMap()},updateMap:function(){var e=this.buildMap();return!o(e,this.__hotKeyMap__)&&(this.__hotKeyMap__=e,!0)},buildMap:function(){var t=this.context.hotKeyMap||{},n=this.props.keyMap||{};return p({},t,e,n)},getMap:function(){return this.__hotKeyMap__}}},Object.defineProperty(e,"__esModule",{value:!0})});
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("prop-types"),require("react")):"function"==typeof define&&define.amd?define(["exports","prop-types","react"],t):t(e.ReactHotkeys={},e.PropTypes,e.React)}(this,function(e,t,n){"use strict";t=t&&t.hasOwnProperty("default")?t.default:t;var o="default"in n?n.default:n;function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:null;return e.reduce(function(e,n){return e[n]=t||{value:n},e},{})}var r="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},s=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},a=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),u=function(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},c=function e(t,n,o){null===t&&(t=Function.prototype);var i=Object.getOwnPropertyDescriptor(t,n);if(void 0===i){var r=Object.getPrototypeOf(t);return null===r?void 0:e(r,n,o)}if("value"in i)return i.value;var s=i.get;return void 0!==s?s.call(o):void 0},h=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},y=function(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n},p=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},d=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var n=[],o=!0,i=!1,r=void 0;try{for(var s,a=e[Symbol.iterator]();!(o=(s=a.next()).done)&&(n.push(s.value),!t||n.length!==t);o=!0);}catch(e){i=!0,r=e}finally{try{!o&&a.return&&a.return()}finally{if(i)throw r}}return n}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),v=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)},f={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 _.option("_ignoreTagsDict")[n]||t.isContentEditable}return!1},simulateMissingKeyPressEvents:!0,stopEventPropagationAfterHandling:!0,stopEventPropagationAfterIgnoring:!0},g=l({},f);g._ignoreTagsDict=i(g.ignoreTags,!0);var _=function(){function e(){s(this,e)}return a(e,null,[{key:"init",value:function(e){var t=this;e.ignoreTags&&(e._ignoreTagsDict=i(e.ignoreTags)),-1!==["verbose","debug","info"].indexOf(e.logLevel)&&console.warn("React HotKeys: You have requested log level '"+e.logLevel+"' but for performance reasons, logging below severity level 'warning' is disabled in production. Please use the development build for complete logs."),Object.keys(e).forEach(function(n){t.set(n,e[n])})}},{key:"set",value:function(e,t){g[e]=t}},{key:"reset",value:function(e){g[e]=f[e]}},{key:"option",value:function(e){return g[e]}}]),e}(),k=function(){function e(){var t=this,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"warn";s(this,e),this.verbose=this.noop,this.debug=this.noop,this.info=this.noop,this.warn=this.noop,this.error=this.noop,this.logLevel=this.constructor.levels[n],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 a(e,[{key:"noop",value:function(){}}]),e}();function m(e){return void 0===e}k.logIcons=["📕","📗","📘","📙"],k.componentIcons=["🔺","⭐️","🔷","🔶","⬛️"],k.eventIcons=["❤️","💚","💙","💛","💜","🧡"],k.levels={none:0,error:1,warn:2,info:3,debug:4,verbose:5};var b=function(){function e(){s(this,e)}return a(e,null,[{key:"newBitmap",value:function(e){var t=[!1,!1,!1];if(!m(e))for(var n=0;n<=e;n++)t[n]=!0;return t}},{key:"setBit",value:function(e,t){return e[t]=!0,e}},{key:"clone",value:function(e){for(var t=this.newBitmap(),n=0;n<e.length;n++)t[n]=e[n];return t}},{key:"and",value:function(e,t){for(var n=[],o=0;o<e.length;o++)n[o]=e[o]&t[o];return n}}]),e}(),E={keydown:0,keypress:1,keyup:2},C={"`":["~"],1:["!"],2:["@",'"'],3:["#","£"],4:["$"],5:["%"],6:["^"],7:["&"],8:["*"],9:["("],0:[")"],"-":["_"],"=":["plus"],";":[":"],"'":['"',"@"],",":["<"],".":[">"],"/":["?"],"\\":["|"],"[":["{"],"]":["}"],"#":["~"]};function K(e){return C[e]||[1===e.length?e.toUpperCase():e]}function I(e){return Object.keys(e).reduce(function(t,n){return e[n].forEach(function(e){var o;o=e,t.hasOwnProperty(o)||(t[e]=[]),t[e].push(n)}),t},{})}var S=I(C);function w(e){return S[e]||[1===e.length?e.toLowerCase():e]}var O={Backspace:["Delete"]};var H={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:"Backspace",command:"Meta",option:"Alt",enter:"Enter",backspace:"Backspace",ins:"Insert",pageup:"PageUp",pagedown:"PageDown",end:"End",home:"Home",contextmenu:"ContextMenu",numlock:"Clear"};function P(e){return H[e.toLowerCase()]||(e.match(/^f\d+$/)?e.toUpperCase():e)}var T={Shift:!0,Control:!0,Alt:!0,Meta:!0,Enter:!0,Tab:!0,CapsLock:!0,BackSpace:!0};function A(e){return!!T[e]||String.fromCharCode(e.charCodeAt(0))===e}var x=function(e){function t(){return s(this,t),p(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return h(t,e),t}(Error);function D(e){return e.sort().join("+")}var B=function(){function e(){s(this,e)}return a(e,null,[{key:"parse",value:function(e){var t,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=("string"==typeof(t=e)?t.trim().replace(/\s+/g," "):t).split(" ");try{var i=o.slice(0,o.length-1),r=o[o.length-1],s=i.map(function(e){var t=L(e,n);return D(Object.keys(t))}).join(" "),a=L(r,n),u={id:D(Object.keys(a)),keyDictionary:a,eventBitmapIndex:n.eventBitmapIndex,size:Object.keys(a).length};return{sequence:{prefix:s,size:i.length+1},combination:u}}catch(e){return{sequence:null,combination:null}}}}]),e}();function L(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return e.replace(/^\+|(\s|[^+]\+)\+/,"$1plus").split("+").reduce(function(e,n){var o=P(n);if(t.ensureValidKeys&&!A(o))throw new x;return e[o]=!0,e},{})}var j={"`":["`"],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:["Ω"],"[":["“"],"]":["‘"],"\\":["«"],"'":["æ"],";":["…"],",":["≤"],".":["≥"],"/":["÷"]},M=I(j);function q(e){return M[e]||[e]}function F(e){return j[e]||[e]}var N={"`":["`"],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:["¸"],"[":["”"],"]":["’"],"\\":["»"],"'":["Æ"],";":["Ú"],",":["¯"],".":["˘"]},U=I(N);function R(e){return U[e]||w(e)}function z(e){return N[e]||[e]}var G=function(){function e(){s(this,e)}return a(e,null,[{key:"serialize",value:function(e){var t=e.Shift,n=e.Alt,o={};return Object.keys(e).sort().forEach(function(e){var i=[];if(t)if(n){var r=R(e),s=z(e);i=[].concat(v(i),[e],v(r),v(s))}else{var a=w(e),c=K(e);i=[].concat(v(i),[e],v(a),v(c))}else if(n){var h=q(e),y=F(e);i=[].concat(v(i),[e],v(h),v(y))}else{i.push(e);var p=O[e];p&&(i=[].concat(v(i),v(p)))}var d=Object.keys(o);d.length>0?d.forEach(function(e){i.forEach(function(t){o[e+"+"+t]=l({},o[e],u({},t,!0))}),delete o[e]}):i.forEach(function(e){o[e]=u({},e,!0)})}),Object.values(o).map(function(e){return Object.keys(e).sort().join("+")})}},{key:"isValidKeySerialization",value:function(e){return e.length>0&&!!B.parse(e,{ensureValidKeys:!0}).combination}}]),e}();function W(e){return Array.isArray(e)?e:e?[e]:[]}function V(e,t){return e[e.length-(t+1)]}function $(e){return!Array.isArray(e)&&"object"===(void 0===e?"undefined":r(e))&&null!==e}function Y(e){return $(e)?0===Object.keys(e).length:!e||0===e.length}function J(e){switch(parseInt(e,10)){case 0:return"keydown";case 1:return"keypress";default:return"keyup"}}var Q=0,X=1;for(var Z={Shift:["shiftKey"],Meta:["metaKey"],Control:["ctrlKey"],Alt:["altKey"]},ee=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];s(this,e),this.logger=t.logger||new k("warn"),this.componentId=0,this.keyEventManager=n,this._reset(),this._resetKeyCombinationHistory()}return a(e,[{key:"_reset",value:function(){this._resetRegisteredKeyMapsState(),this._resetHandlerResolutionState()}},{key:"_resetRegisteredKeyMapsState",value:function(){this.componentList=[],this.longestSequence=1,this.longestSequenceComponentIndex=null,this.keyMapEventBitmap=b.newBitmap()}},{key:"_resetHandlerResolutionState",value:function(){this.keyMaps=null,this.handlerResolutionSearchIndex=0,this.unmatchedHandlerStatus=null,this.handlersDictionary={},this.keySequencesDictionary={}}},{key:"_resetKeyCombinationHistory",value:function(){if(this.keyCombinationIncludesKeyUp=!1,this.keypressEventsToSimulate=[],!this.keyCombinationHistory||this.keyCombinationHistory.length<1)this.keyCombinationHistory=[];else{var e=this._getCurrentKeyCombination(),t=Object.keys(e.keys).reduce(function(t,n){var o=e.keys[n],i=o[X];return i[E.keydown]&&!i[E.keyup]&&(t[n]=o),t},{});this.keyCombinationHistory=[{keys:t,ids:G.serialize(t)}]}}},{key:"_addComponentToList",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=this._buildComponentOptions(e,t,n,o);return this.componentList.push(i),i}},{key:"_buildComponentOptions",value:function(e,t,n,o){var i=this._applyHardSequences(t,n),r=i.keyMap,s=i.handlers;return{actions:this._buildActionDictionary(l({},t,r),o,e),handlers:s,componentId:e,options:o}}},{key:"_applyHardSequences",value:function(e,t){return _.option("enableHardSequences")?Object.keys(t).reduce(function(n,o){return!!!e[o]&&G.isValidKeySerialization(o)&&(n.keyMap[o]=o),n.handlers[o]=t[o],n},{keyMap:{},handlers:{}}):{keyMap:e,handlers:t}}},{key:"_buildActionDictionary",value:function(e,t,n){var o=this;return Object.keys(e).reduce(function(i,r){return W(e[r]).forEach(function(e){var s=function(){if($(e)){var n=e.sequence,o=e.action;return{keySequence:n,eventBitmapIndex:m(o)?E[t.defaultKeyEvent]:E[o]}}return{keySequence:e,eventBitmapIndex:E[t.defaultKeyEvent]}}(),a=s.keySequence,u=s.eventBitmapIndex,c=B.parse(a,{eventBitmapIndex:u}),h=c.sequence,y=c.combination;h.size>o.longestSequence&&(o.longestSequence=h.size,o.longestSequenceComponentIndex=n),b.setBit(o.keyMapEventBitmap,u),i[r]||(i[r]=[]),i[r].push(l({prefix:h.prefix,actionName:r,sequenceLength:h.size},y))}),i},{})}},{key:"_getCurrentKeyCombination",value:function(){return this.keyCombinationHistory.length>0?this.keyCombinationHistory[this.keyCombinationHistory.length-1]:{keys:{},ids:[""],keyAliases:{}}}},{key:"_addToCurrentKeyCombination",value:function(e,t){0===this.keyCombinationHistory.length&&this.keyCombinationHistory.push({keys:{},ids:[""],keyAliases:{}});var n=this._getCurrentKeyCombination(),o=this._getKeyAlias(n,e),i=this._getKeyState(n,e);n.keys[o]=i?[b.clone(i[1]),b.newBitmap(t)]:[b.newBitmap(),b.newBitmap(t)],n.ids=G.serialize(n.keys),n.keyAliases=this._buildCombinationKeyAliases(n.keys),t===E.keyup&&(this.keyCombinationIncludesKeyUp=!0)}},{key:"_startNewKeyCombination",value:function(e,t){this.keyCombinationHistory.length>this.longestSequence&&this.keyCombinationHistory.shift();var n=this._getCurrentKeyCombination(),o=l({},this._withoutKeyUps(n),u({},e,[b.newBitmap(),b.newBitmap(t)]));this.keyCombinationHistory.push({keys:o,ids:G.serialize(o),keyAliases:this._buildCombinationKeyAliases(o)}),this.keyCombinationIncludesKeyUp=!1}},{key:"_withoutKeyUps",value:function(e){return Object.keys(e.keys).reduce(function(t,n){var o=e.keys[n];return o[X][E.keyup]||(t[n]=o),t},{})}},{key:"_callMatchingHandlerClosestToEventTarget",value:function(e,t,n,o,i){var r=this;for(this.keyMaps&&this.unmatchedHandlerStatus||(this.keyMaps=[],this.unmatchedHandlerStatus=[],this.componentList.forEach(function(e){var t=e.handlers;r.unmatchedHandlerStatus.push([Object.keys(t).length,{}]),r.keyMaps.push({})}));i<=o;){var s=this.unmatchedHandlerStatus[i][0];if(s>0)for(var a=function(){var e=r.componentList[r.handlerResolutionSearchIndex],t=e.handlers,n=e.actions;Object.keys(t).forEach(function(e){r.handlersDictionary[e]||(r.handlersDictionary[e]=[]),r.handlersDictionary[e].push(r.handlerResolutionSearchIndex)}),Object.keys(n).forEach(function(e){var t=r.handlersDictionary[e];if(t){var o=t[0],i=r.componentList[o].handlers[e],s=r.keyMaps[o];s.sequences||(s.sequences={}),n[e].forEach(function(e){var t=[e.prefix,e.id].join(" ");if(!(r.keySequencesDictionary[t]&&r.keySequencesDictionary[t].some(function(t){return t[1]===e.eventBitmapIndex}))){s.sequences[e.prefix]||(s.sequences[e.prefix]={combinations:{}});var n=e.prefix,a=e.sequenceLength,c=e.id,h=e.keyDictionary,y=e.size,p=e.eventBitmapIndex,d=e.actionName,v=s.sequences[e.prefix].combinations[e.id];s.sequences[e.prefix].combinations[e.id]=v?l({},v,{events:l({},v.events,u({},p,{actionName:d,eventBitmapIndex:p,handler:i}))}):{prefix:n,sequenceLength:a,id:c,keyDictionary:h,size:y,events:u({},p,{actionName:d,eventBitmapIndex:p,handler:i})},s.eventBitmap||(s.eventBitmap=b.newBitmap()),b.setBit(s.eventBitmap,e.eventBitmapIndex),(!s.longestSequence||s.longestSequence<e.sequenceLength)&&(s.longestSequence=e.sequenceLength),r.keySequencesDictionary[t]||(r.keySequencesDictionary[t]=[]),r.keySequencesDictionary[t].push([o,e.eventBitmapIndex])}}),t.forEach(function(t){var n=r.unmatchedHandlerStatus[t];n[1][e]||(n[1][e]=!0,n[0]--)})}}),r.handlerResolutionSearchIndex++};this.handlerResolutionSearchIndex<this.componentList.length&&s>0;)a();var c=this.keyMaps[i];if(c&&!Y(c.sequences)&&c.eventBitmap[n])for(var h=c.sequences,y=c.longestSequence,p=this._getCurrentKeyCombination(),d=this._getKeyAlias(p,t),v=y;v>=0;){var f=this.keyCombinationHistory.slice(-v,-1).map(function(e){return e.ids}),g=this._tryMatchSequenceWithKeyAliases(h,f);if(g){g.order||function(){var e=Object.values(g.combinations).reduce(function(e,t){var n=t.id,o=t.size;return e[o]||(e[o]=[]),e[o].push(n),e},{});g.order=Object.keys(e).sort(function(e,t){return t-e}).reduce(function(t,n){return t.concat(e[n])},[])}();for(var _=g.order,k=0;k<_.length;){var m=_[k],E=g.combinations[m];if(this._combinationMatchesKeys(d,p,E,n)){G.serialize(E.keyDictionary);return E.events[n].handler(e),this._stopEventPropagationAfterHandlingIfEnabled(e,i),!0}k++}}v--}else;i++}}},{key:"_stopEventPropagationAfterHandlingIfEnabled",value:function(e,t){return!!_.option("stopEventPropagationAfterHandling")&&(this._stopEventPropagation(e,t),!0)}},{key:"_stopEventPropagationAfterIgnoringIfEnabled",value:function(e,t){return!!_.option("stopEventPropagationAfterIgnoring")&&(this._stopEventPropagation(e,t),!0)}},{key:"_stopEventPropagation",value:function(e,t){e.stopPropagation()}},{key:"_describeCurrentKeyCombination",value:function(){return this._getCurrentKeyCombination().ids[0]}},{key:"_tryMatchSequenceWithKeyAliases",value:function(e,t){if(0===t.length)return e[""];for(var n=t.map(function(e){return e.length}),o=t.map(function(){return 0}),i=!1;!i;){var r=o.map(function(e,n){return t[n][e]}).join(" ");if(e[r])return e[r];for(var s=0,a=!0;a&&s<o.length;){var u=(V(o,s)+1)%(V(n,s)||1);o[o.length-(s+1)]=u,(a=0===u)&&s++}i=s===o.length}}},{key:"_combinationMatchesKeys",value:function(e,t,n,o){var i=this;if(!n.events[o])return!1;var r=!1;return!Object.keys(n.keyDictionary).some(function(n){var s=i._getKeyState(t,n);return!s||(!i._keyIsCurrentlyTriggeringEvent(s,o)||(e&&e===i._getKeyAlias(t,n)&&(r=!i._keyAlreadyTriggeredEvent(s,o)),!1))})&&r}},{key:"_checkForModifierFlagDiscrepancies",value:function(e){var t=this;Object.keys(Z).forEach(function(n){var o=t._getCurrentKeyState(n),i=o&&!t._keyIsCurrentlyTriggeringEvent(o,E.keyup);Z[n].forEach(function(o){!1===e[o]&&i&&t._addToCurrentKeyCombination(n,E.keyup)})})}},{key:"_keyIsCurrentlyTriggeringEvent",value:function(e,t){return e&&e[X][t]}},{key:"_keyAlreadyTriggeredEvent",value:function(e,t){return e&&e[Q][t]}},{key:"_getCurrentKeyState",value:function(e){var t=this._getCurrentKeyCombination();return this._getKeyState(t,e)}},{key:"_getKeyState",value:function(e,t){var n=e.keys[t];if(n)return n;var o=e.keyAliases[t];return o?e.keys[o]:void 0}},{key:"_getKeyAlias",value:function(e,t){if(e.keys[t])return t;var n=e.keyAliases[t];return n||t}},{key:"_buildCombinationKeyAliases",value:function(e){var t=function(){if(e.Shift)return e.Alt?[z,R]:[K,w];if(e.Alt)return[F,q];var t=function(e){return[e]};return[t,t]}();return Object.keys(e).reduce(function(e,n){return function(e){return O[e]||[e]}(n).forEach(function(o){t.forEach(function(t){t(o).forEach(function(t){t===n&&n===o||(e[t]=n)})})}),e},{})}}]),e}(),te=function(){function e(){s(this,e)}return a(e,null,[{key:"getId",value:function(){return m(this.id)&&(this.id=0),this.id}},{key:"incrementId",value:function(){this.id=this.getId()+1}}]),e}(),ne={Shift:!0,Control:!0,Alt:!0,Meta:!0,Enter:!0,Tab:!0,BackSpace:!0,ArrowRight:!0,ArrowLeft:!0,ArrowUp:!0,ArrowDown:!0,CapsLock:!0},oe=1;oe<13;oe++)ne["F"+oe]=!0;function ie(e){return!ne[e]}function re(e){return"+"===e?"plus":e}var se=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];s(this,t);var o=p(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o.focusTreeId=0,o.currentEvent={key:null,type:null,handled:!1},o}return h(t,ee),a(t,[{key:"_reset",value:function(){c(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_reset",this).call(this),this.componentId=0,this.focusTreeId+=1,this._clearEventPropagationState()}},{key:"_clearEventPropagationState",value:function(){this.eventPropagationState={previousComponentIndex:-1,actionHandled:!1,ignoreEvent:!1}}},{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];return(this.resetOnNextFocus||this.keyMaps)&&(this._reset(),this.resetOnNextFocus=!1),this.componentId=this.componentList.length,this._addComponentToList(this.componentId,e,t,n),[this.focusTreeId,this.componentId]}},{key:"updateHotKeys",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments[4];e===this.focusTreeId&&this.componentList[t]&&(this.componentList[t]=this._buildComponentOptions(t,n,o,i))}},{key:"removeHotKeys",value:function(e,t){return this.resetOnNextFocus||(this.resetOnNextFocus=!0),this.eventPropagationState.previousComponentIndex+1<t}},{key:"handleKeydown",value:function(e,t,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=re(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())return this._ignoreEvent(e,n),!1;if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,E.keydown),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return this._ignoreEvent(e,n),!1;this._checkForModifierFlagDiscrepancies(e),!!this._getCurrentKeyState(i)||this.keyCombinationIncludesKeyUp?this._startNewKeyCombination(i,E.keydown,t,n):this._addToCurrentKeyCombination(i,E.keydown,t,n)}return this._callHandlerIfActionNotHandled(e,i,E.keydown,n,t),!ie(i)&&_.option("simulateMissingKeyPressEvents")&&(e.persist(),this.keypressEventsToSimulate.push({event:e,focusTreeId:t,componentId:n,options:o,key:i})),this._isFocusTreeRoot(n)&&(this.keyEventManager.isGlobalListenersBound()||this.simulatePendingKeyPressEvents(i)),this._updateEventPropagationHistory(n),!1}},{key:"simulatePendingKeyPressEvents",value:function(){var e=this;this.keypressEventsToSimulate.length>0&&te.incrementId(),this.keypressEventsToSimulate.forEach(function(t){var n=t.event,o=t.focusTreeId,i=t.componentId,r=t.options;e.handleKeypress(n,o,i,r)}),this.keypressEventsToSimulate=[],this._clearEventPropagationState()}},{key:"handleKeypress",value:function(e,t,n,o){var i=re(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())this._ignoreEvent(e,n);else{if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,E.keypress),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return void this._ignoreEvent(e,n);var r=this._getCurrentKeyState(i);r&&(r[X][E.keypress]||r[X][E.keyup])?this._startNewKeyCombination(i,E.keypres,t,n):this._addToCurrentKeyCombination(i,E.keypress,t,n)}this._callHandlerIfActionNotHandled(e,i,E.keypress,n,t),this._updateEventPropagationHistory(n)}}},{key:"handleKeyup",value:function(e,t,n,o){var i=re(e.key);if(t!==this.focusTreeId)return this._ignoreEvent(e,n),!0;if(this._alreadyEstablishedShouldIgnoreEvent())this._ignoreEvent(e,n);else{if(this._isNewKeyEvent(n)){if(this._setNewEventParameters(e,E.keyup),this._setIgnoreEventFlag(e,o),this._alreadyEstablishedShouldIgnoreEvent())return void this._ignoreEvent(e,n);var r=this._getCurrentKeyState(i);r&&r[X][E.keyup]?this._startNewKeyCombination(i,E.keyup,t,n):this._addToCurrentKeyCombination(i,E.keyup,t,n)}this._callHandlerIfActionNotHandled(e,i,E.keyup,n,t),this._updateEventPropagationHistory(n)}}},{key:"_ignoreEvent",value:function(e,t){this._stopEventPropagationAfterIgnoringIfEnabled(e,t)?this._updateEventPropagationHistory(t,{forceReset:!0}):this._updateEventPropagationHistory(t)}},{key:"_alreadyEstablishedShouldIgnoreEvent",value:function(){return this.eventPropagationState.ignoreEvent}},{key:"_isNewKeyEvent",value:function(e){var t=this.eventPropagationState.previousComponentIndex;return-1===t||t>=e}},{key:"_updateEventPropagationHistory",value:function(e){(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{forceReset:!1}).forceReset||this._isFocusTreeRoot(e)?this._clearEventPropagationState():this.eventPropagationState.previousComponentIndex=e}},{key:"_setIgnoreEventFlag",value:function(e,t){this.eventPropagationState.ignoreEvent=t.ignoreEventsCondition(e)}},{key:"ignoreEvent",value:function(e){this.eventPropagationState.ignoreEvent=!0}},{key:"_isFocusTreeRoot",value:function(e){return e>=this.componentList.length-1}},{key:"_setNewEventParameters",value:function(e,t){te.incrementId(),this.currentEvent={key:e.key,type:t,handled:!1}}},{key:"_startNewKeyCombination",value:function(e,n,o,i){c(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_startNewKeyCombination",this).call(this,e,n)}},{key:"_addToCurrentKeyCombination",value:function(e,n,o,i){c(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addToCurrentKeyCombination",this).call(this,e,n)}},{key:"_callHandlerIfActionNotHandled",value:function(e,t,n,o,i){this._describeCurrentKeyCombination();if(this.keyMapEventBitmap[n])if(this.eventPropagationState.actionHandled);else{var r=this.eventPropagationState.previousComponentIndex;this._callMatchingHandlerClosestToEventTarget(e,t,n,o,-1===r?0:r)&&(this.eventPropagationState.actionHandled=!0,this.currentEvent.handled=!0)}}},{key:"_logPrefix",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=k.logIcons,o=k.eventIcons,i=k.componentIcons,r="HotKeys (";if(!1!==t.focusTreeId){var s=m(t.focusTreeId)?this.focusTreeId:t.focusTreeId;r+="FT"+s+n[s%n.length]+"-"}if(!1!==t.eventId){var a=m(t.eventId)?te.getId():t.eventId;r+="E"+a+o[a%o.length]+"-"}return r+"C"+e+i[e%i.length]+"):"}}]),t}();var ae={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},ue={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"};function le(e){if(e.key){var t=ae[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=function(e){var t=void 0,n=e.keyCode;return"charCode"in e?0===(t=e.charCode)&&13===n&&(t=13):t=n,10===t&&(t=13),t>=32||13===t?t:0}(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?ue[e.keyCode]||"Unidentified":""}var ce=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=arguments[1];s(this,t);var o=p(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));return o.componentId=-1,o.listenersBound=!1,o.eventOptions={ignoreEventsCondition:_.option("ignoreEventsCondition")},o}return h(t,ee),a(t,[{key:"_reset",value:function(){c(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_reset",this).call(this),this.componentIdDict={}}},{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2],o=arguments[3];return this.eventOptions=o,this.componentId+=1,this._addComponentToList(this.componentId,e,t,n),this._updateDocumentHandlers(),this.componentId}},{key:"updateHotKeys",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=arguments[4];this.eventOptions=i;var r=this._getComponentPosition(e);this.componentList[r]=this._buildComponentOptions(e,t,n,o),this._updateLongestKeySequenceIfNecessary(e),this._updateDocumentHandlers(),this._resetHandlerResolutionState()}},{key:"removeHotKeys",value:function(e){var t,n,o=this._getComponentAndPosition(e),i=d(o,2),r=i[0].keyMapEventBitmap,s=i[1];this.componentList=(t=this.componentList,n=s,[].concat(v(t.slice(0,n)),v(t.slice(n+1)))),this._updateLongestKeySequenceIfNecessary(e),this._updateComponentIndexDictFromList({startingAt:s}),this._updateDocumentHandlers(r,b.newBitmap()),this._resetHandlerResolutionState()}},{key:"_addComponentToList",value:function(e){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i=arguments[3];c(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addComponentToList",this).call(this,e,n,o,i),this._setComponentPosition(e,this.componentList.length-1)}},{key:"_setComponentPosition",value:function(e,t){this.componentIdDict[e]=t}},{key:"_updateLongestKeySequenceIfNecessary",value:function(e){var t=this;e===this.longestSequenceComponentIndex&&(this.longestSequence=1,this.componentList.forEach(function(e){var n=e.longestSequence;n>t.longestSequence&&(t.longestSequence=n)}))}},{key:"_updateComponentIndexDictFromList",value:function(){for(var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{startingAt:0}).startAt;e<this.componentList.length;)this._setComponentPosition(this.componentList[e].componentId,e)}},{key:"_updateDocumentHandlers",value:function(){var e=this,t=this.keyMapEventBitmap.some(function(e){return e});if(!this.listenersBound&&t){for(var n=function(t){var n=J(t);document["on"+n]=function(t){var o;e.keyEventManager["handleGlobal"+(o=n,o.replace(/\b\w/g,function(e){return e.toUpperCase()}))](t)}},o=0;o<this.keyMapEventBitmap.length;o++)n(o);this.listenersBound=!0}else if(this.listenersBound&&!t){for(o=0;o<this.keyMapEventBitmap.length;o++){var i=J(o);delete document["on"+i]}this.listenersBound=!1}}},{key:"handleKeydown",value:function(e){this._checkForModifierFlagDiscrepancies(e);var t=re(le(e));!!this._getCurrentKeyState(t)||this.keyCombinationIncludesKeyUp?this._startNewKeyCombination(t,E.keydown):this._addToCurrentKeyCombination(t,E.keydown);var n=this.keyEventManager.reactAppHistoryWithEvent(t,E.keydown);if("handled"===n);else{if("seen"===n||te.incrementId(),this.eventOptions.ignoreEventsCondition(e))return;this._callHandlerIfExists(e,t,E.keydown),ie(t)||(this.keyEventManager.simulatePendingKeyPressEvents(),this.handleKeypress(e))}}},{key:"handleKeypress",value:function(e){var t=re(le(e)),n=this._getCurrentKeyState(t);n&&(n[X][E.keypress]||n[X][E.keyup])?this._startNewKeyCombination(t,E.keypress):this._addToCurrentKeyCombination(t,E.keypress);var o=this.keyEventManager.reactAppHistoryWithEvent(t,E.keypress);return"handled"!==o&&("seen"===o||te.incrementId(),!this.eventOptions.ignoreEventsCondition(e)&&void this._callHandlerIfExists(e,t,E.keypress))}},{key:"handleKeyup",value:function(e){var t=re(le(e)),n=this._getCurrentKeyState(t);n&&n[X][E.keyup]?this._startNewKeyCombination(t,E.keyup):this._addToCurrentKeyCombination(t,E.keyup);var o=this.keyEventManager.reactAppHistoryWithEvent(t,E.keyup);return"handled"!==o&&("seen"===o||te.incrementId(),!this.eventOptions.ignoreEventsCondition(e)&&void this._callHandlerIfExists(e,t,E.keyup))}},{key:"_startNewKeyCombination",value:function(e,n){c(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_startNewKeyCombination",this).call(this,e,n)}},{key:"_addToCurrentKeyCombination",value:function(e,n){c(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_addToCurrentKeyCombination",this).call(this,e,n)}},{key:"_getComponentPosition",value:function(e){return this.componentIdDict[e]}},{key:"_getComponent",value:function(e){var t=this._getComponentPosition(e);return this.componentList[t]}},{key:"_getComponentAndPosition",value:function(e){var t=this._getComponentPosition(e);return[this.componentList[t],t]}},{key:"_callHandlerIfExists",value:function(e,t,n){this._describeCurrentKeyCombination();this.keyMapEventBitmap[n]&&this._callMatchingHandlerClosestToEventTarget(e,t,n)}},{key:"_callMatchingHandlerClosestToEventTarget",value:function(e,n,o){for(var i=0;i<this.componentList.length;i++){if(c(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"_callMatchingHandlerClosestToEventTarget",this).call(this,e,n,o,i,0))return}}},{key:"_logPrefix",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=k.eventIcons,o=k.componentIcons,i="HotKeys (GLOBAL";if(!1!==t.eventId){var r=m(t.eventId)?te.getId():t.eventId;i=i+"-E"+r+n[r%n.length]}return m(e)?i+"):":i+"-C"+e+o[e%o.length]+"):"}}]),t}();function he(e){return!m(e)}var ye=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};s(this,e),this.logger=t.logger||new k(_.option("logLevel")),this._focusOnlyEventStrategy=new se({configuration:t,logger:this.logger},this),this._globalEventStrategy=new ce({configuration:t,logger:this.logger},this),this.lastEventSeen=null}return a(e,null,[{key:"getInstance",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return this.instance||(this.instance=new e(t)),this.instance}},{key:"clear",value:function(){delete this.instance}}]),a(e,[{key:"addHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2];return this._focusOnlyEventStrategy.addHotKeys(e,t,n)}},{key:"updateHotKeys",value:function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},i=arguments[4];return this._focusOnlyEventStrategy.updateHotKeys(e,t,n,o,i)}},{key:"removeHotKeys",value:function(e,t){return this._focusOnlyEventStrategy.removeHotKeys(e,t)}},{key:"handleKeydown",value:function(e,t,n,o){if(he(t))return this._focusOnlyEventStrategy.handleKeydown(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"handleKeypress",value:function(e,t,n,o){if(he(t))return this._focusOnlyEventStrategy.handleKeypress(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"handleKeyup",value:function(e,t,n,o){if(he(t))return this._focusOnlyEventStrategy.handleKeyup(e,t,n,o);this._recordLastSeenEvent(e)}},{key:"_recordLastSeenEvent",value:function(e){var t=e.key,n=e.type,o=e.nativeEvent;this.lastEventSeen={key:t,type:n,nativeEvent:o}}},{key:"addGlobalHotKeys",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2],o=arguments[3];return this._globalEventStrategy.addHotKeys(e,t,n,o)}},{key:"updateGlobalHotKeys",value:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=arguments[3],i=arguments[4];return this._globalEventStrategy.updateHotKeys(e,t,n,o,i)}},{key:"removeGlobalHotKeys",value:function(e){return this._globalEventStrategy.removeHotKeys(e)}},{key:"handleGlobalKeydown",value:function(e){return this._globalEventStrategy.handleKeydown(e)}},{key:"handleGlobalKeypress",value:function(e){return this._globalEventStrategy.handleKeypress(e)}},{key:"handleGlobalKeyup",value:function(e){return this._globalEventStrategy.handleKeyup(e)}},{key:"ignoreEvent",value:function(e){this._focusOnlyEventStrategy.ignoreEvent(e)}},{key:"reactAppHistoryWithEvent",value:function(e,t){var n=this._focusOnlyEventStrategy.currentEvent;return n.key===e&&n.type===t?n.handled?"handled":"seen":"unseen"}},{key:"simulatePendingKeyPressEvents",value:function(){this._focusOnlyEventStrategy.simulatePendingKeyPressEvents()}},{key:"isGlobalListenersBound",value:function(){return this._globalEventStrategy.listenersBound}}]),e}();function pe(e){var i,r,u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};function c(e,t){return l({},u[e]||{},t[e]||{})}function v(e){return c("handlers",e)}function f(e){return c("keyMap",e)}return r=i=function(t){function n(e){s(this,n);var t=p(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t._handleFocus=t._handleFocus.bind(t),t._handleBlur=t._handleBlur.bind(t),t._handleKeyDown=t._handleKeyDown.bind(t),t._handleKeyPress=t._handleKeyPress.bind(t),t._handleKeyUp=t._handleKeyUp.bind(t),t._componentIsFocused=t._componentIsFocused.bind(t),t}return h(n,t),a(n,[{key:"render",value:function(){var t=this.props,n=(t.keyMap,t.handlers,t.allowChanges,y(t,["keyMap","handlers","allowChanges"])),i={onFocus:this._wrapFunction("onFocus",this._handleFocus),onBlur:this._wrapFunction("onBlur",this._handleBlur),tabIndex:_.option("defaultTabIndex")};return this._shouldBindKeyListeners()&&(i.onKeyDown=this._handleKeyDown,i.onKeyPress=this._handleKeyPress,i.onKeyUp=this._handleKeyUp),o.createElement(e,l({hotKeys:i},n))}},{key:"_shouldBindKeyListeners",value:function(){var e=f(this.props);return!Y(e)||_.option("enableHardSequences")&&this._handlersIncludeHardSequences(e,v(this.props))}},{key:"_handlersIncludeHardSequences",value:function(e,t){return Object.keys(t).some(function(t){return!e[t]&&G.isValidKeySerialization(t)})}},{key:"_wrapFunction",value:function(e,t){var n=this;return"function"==typeof this.props[e]?function(o){n.props[e](o),t(o)}:t}},{key:"_focusTreeIdsPush",value:function(e){this._focusTreeIds||(this._focusTreeIds=[]),this._focusTreeIds.push(e)}},{key:"_focusTreeIdsShift",value:function(){this._focusTreeIds&&this._focusTreeIds.shift()}},{key:"_getFocusTreeId",value:function(){if(this._focusTreeIds)return this._focusTreeIds[0]}},{key:"componentDidUpdate",value:function(e){if(this._componentIsFocused()&&(this.props.allowChanges||!_.option("ignoreKeymapAndHandlerChangesByDefault"))){var t=this.props,n=t.keyMap,o=t.handlers;ye.getInstance().updateHotKeys(this._getFocusTreeId(),this._componentId,n,o,this._getComponentOptions())}}},{key:"componentWillUnmount",value:function(){this._handleBlur()}},{key:"_componentIsFocused",value:function(){return!0===this._focused}},{key:"_handleFocus",value:function(){var e;this.props.onFocus&&(e=this.props).onFocus.apply(e,arguments);var t=ye.getInstance().addHotKeys(f(this.props),v(this.props),this._getComponentOptions()),n=d(t,2),o=n[0],i=n[1];this._componentId=i,this._focusTreeIdsPush(o),this._focused=!0}},{key:"_handleBlur",value:function(){var e;this.props.onBlur&&(e=this.props).onBlur.apply(e,arguments);ye.getInstance().removeHotKeys(this._getFocusTreeId(),this._componentId)||this._focusTreeIdsShift(),this._focused=!1}},{key:"_handleKeyDown",value:function(e){ye.getInstance().handleKeydown(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_handleKeyPress",value:function(e){ye.getInstance().handleKeypress(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_handleKeyUp",value:function(e){ye.getInstance().handleKeyup(e,this._getFocusTreeId(),this._componentId,this._getEventOptions())&&this._focusTreeIdsShift()}},{key:"_getComponentOptions",value:function(){return{defaultKeyEvent:_.option("defaultKeyEvent")}}},{key:"_getEventOptions",value:function(){return{ignoreEventsCondition:_.option("ignoreEventsCondition")}}}]),n}(n.PureComponent),i.propTypes={keyMap:t.object,handlers:t.object,onFocus:t.func,onBlur:t.func,allowChanges:t.bool},r}var de=pe(function(e){function t(){return s(this,t),p(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return h(t,e),a(t,[{key:"render",value:function(){var e=this.props,t=e.hotKeys,n=y(e,["hotKeys"]),i=n.component||_.option("defaultComponent");return o.createElement(i,l({},t,n))}}]),t}(n.Component));function ve(e){var i,r,u=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{only:[],except:[]};return r=i=function(t){function n(e){s(this,n);var t=p(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));return t._handleKeyEvent=t._handleKeyEvent.bind(t),t._reloadDictionaries=t._reloadDictionaries.bind(t),t}return h(n,t),a(n,[{key:"getDefaultProps",value:function(){return u}}]),a(n,[{key:"render",value:function(){var t=this.props,n=(t.only,t.except,y(t,["only","except"])),i={onKeyDown:this._handleKeyEvent,onKeyPress:this._handleKeyEvent,onKeyUp:this._handleKeyEvent,onFocus:this._reloadDictionaries};return o.createElement(e,l({hotKeys:i},n))}},{key:"_reloadDictionaries",value:function(){var e=this.props,t=e.only,n=e.except;this._onlyDict=fe(t),this._exceptDict=fe(n)}},{key:"_shouldIgnoreEvent",value:function(e){var t=e.key;return Y(this._onlyDict)?!!Y(this._exceptDict)||!this._exceptDict[t]:Y(this._exceptDict)?this._onlyDict[t]:this._onlyDict[t]&&!this._exceptDict[t]}},{key:"_handleKeyEvent",value:function(e){this._shouldIgnoreEvent(e)&&ye.getInstance().ignoreEvent(e)}}]),n}(n.PureComponent),i.propTypes={only:t.oneOfType([t.string,t.arrayOf(t.string)]),except:t.oneOfType([t.string,t.arrayOf(t.string)])},r}function fe(e){return W(e).reduce(function(e,t){var n=P(t);if(!A(n))throw new x(t);return[z,R,K,w,F,q].forEach(function(t){e[t(n)]=!0}),e},{})}var ge=ve(function(e){function t(){return s(this,t),p(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return h(t,e),a(t,[{key:"render",value:function(){var e=this.props,t=e.hotKeys,n=y(e,["hotKeys"]),i=n.component||_.option("defaultComponent");return o.createElement(i,l({},t,n))}}]),t}(n.Component)),_e=function(e){function t(){return s(this,t),p(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return h(t,e),a(t,[{key:"render",value:function(){return this.props.children||null}},{key:"componentDidUpdate",value:function(){if(this.props.allowChanges||!_.option("ignoreKeymapAndHandlerChangesByDefault")){var e=this.props,t=e.keyMap,n=e.handlers;ye.getInstance().updateGlobalHotKeys(this._id,t,n,this._getComponentOptions(),this._getEventOptions())}}},{key:"componentDidMount",value:function(){var e=this.props,t=e.keyMap,n=e.handlers;this._id=ye.getInstance().addGlobalHotKeys(t,n,this._getComponentOptions(),this._getEventOptions())}},{key:"componentWillUnmount",value:function(){ye.getInstance().removeGlobalHotKeys(this._id)}},{key:"_getComponentOptions",value:function(){return{defaultKeyEvent:_.option("defaultKeyEvent")}}},{key:"_getEventOptions",value:function(){return{ignoreEventsCondition:_.option("ignoreEventsCondition")}}}]),t}(n.Component);_e.propTypes={keyMap:t.object,handlers:t.object,onFocus:t.func,onBlur:t.func,allowChanges:t.bool},e.HotKeys=de,e.HotKeysIgnore=ge,e.withHotKeysIgnore=ve,e.GlobalHotKeys=_e,e.withHotKeys=pe,e.configure=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_.init(e)},Object.defineProperty(e,"__esModule",{value:!0})});

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc