UNPKG

react-use-konami

Version:

react hook that adds konami code to your component

95 lines (85 loc) 3.16 kB
'use strict'; var react = require('react'); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var ReducerAction; (function (ReducerAction) { ReducerAction["KeyUp"] = "KEY_UP"; ReducerAction["Reset"] = "RESET"; })(ReducerAction || (ReducerAction = {})); var initialState = function (initialCode) { if (initialCode === void 0) { initialCode = [ 'ArrowUp', 'ArrowUp', 'ArrowDown', 'ArrowDown', 'ArrowLeft', 'ArrowRight', 'ArrowLeft', 'ArrowRight', 'b', 'a', 'Enter', ]; } return { success: false, code: initialCode, initialCode: initialCode, }; }; var konamiReducer = function (state, action) { switch (action.type) { case ReducerAction.KeyUp: { if (state.success) { return state; } else if (state.code[0] === action.payload) { var code = state.code.slice(1); return __assign({}, state, { success: code.length === 0, code: code }); } return initialState(state.initialCode); } case ReducerAction.Reset: return initialState(state.initialCode); default: return state; } }; var useKonami = function (handler, options) { var _a = react.useReducer(konamiReducer, initialState(options && options.code)), state = _a[0], dispatch = _a[1]; react.useEffect(function () { var listener = function (e) { return dispatch({ type: ReducerAction.KeyUp, payload: e.key, }); }; window.addEventListener('keyup', listener); return function () { return window.removeEventListener('keyup', listener); }; }, []); react.useEffect(function () { if (state.success) { handler(); dispatch({ type: ReducerAction.Reset }); } }, [state, handler]); }; module.exports = useKonami;