├── .husky └── pre-commit ├── .gitignore ├── index.js ├── .npmignore ├── .prettierrc ├── jest.config.js ├── tsconfig.json ├── LICENSE ├── package.json ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── README.md └── src ├── index.tsx └── __tests__ └── index.tsx /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | npx lint-staged 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | node_modules 3 | dist 4 | *.log 5 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /** @format */ 2 | 3 | module.exports = require('./dist/index.js'); 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | src/ 2 | .travis.yml 3 | yarn.lock 4 | *.md 5 | *.json 6 | LICENSE 7 | jest.* 8 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "avoid", 3 | "bracketSpacing": true, 4 | "insertPragma": true, 5 | "printWidth": 100, 6 | "requirePragma": false, 7 | "semi": true, 8 | "singleQuote": true, 9 | "tabWidth": 2, 10 | "useTabs": false, 11 | "trailingComma": "all" 12 | } 13 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | /** @format */ 2 | 3 | module.exports = { 4 | roots: ['/src'], 5 | transform: { 6 | '^.+\\.tsx?$': 'ts-jest', 7 | }, 8 | testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$', 9 | testEnvironment: 'jsdom', 10 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], 11 | }; 12 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "declaration": true, 4 | "jsx": "react-jsx", 5 | "lib": ["esnext", "dom"], 6 | "module": "commonjs", 7 | "removeComments": true, 8 | "strictNullChecks": true, 9 | "noUnusedLocals": true, 10 | "noImplicitAny": true, 11 | "outDir": "./dist", 12 | "sourceMap": true, 13 | "strict": true, 14 | "target": "es5" 15 | }, 16 | "include": ["./src/**/*"], 17 | "exclude": ["node_modules", "**/__tests__/**/*"] 18 | } 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | ===================== 3 | 4 | Copyright © 2018 Unicorn Heart Club LLC 5 | 6 | Permission is hereby granted, free of charge, to any person 7 | obtaining a copy of this software and associated documentation 8 | files (the “Software”), to deal in the Software without 9 | restriction, including without limitation the rights to use, 10 | copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | copies of the Software, and to permit persons to whom the 12 | Software is furnished to do so, subject to the following 13 | conditions: 14 | 15 | The above copyright notice and this permission notice shall be 16 | included in all copies or substantial portions of the Software. 17 | 18 | THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, 19 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 20 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 21 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 22 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 23 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 24 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 25 | OTHER DEALINGS IN THE SOFTWARE. 26 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-keybind", 3 | "version": "0.10.0", 4 | "description": "Global keybindings for your React application", 5 | "scripts": { 6 | "prepare": "husky", 7 | "prepublishOnly": "npm run build", 8 | "build": "tsc && uglifyjs dist/index.js --compress --mangle -o dist/index.js --source-map \"filename='dist/index.js.map'\"", 9 | "test": "jest", 10 | "test:dev": "jest --watch" 11 | }, 12 | "main": "index.js", 13 | "types": "dist/index.d.ts", 14 | "author": "Unicorn Heart Club", 15 | "license": "MIT", 16 | "repository": "github:UnicornHeartClub/react-keybind", 17 | "devDependencies": { 18 | "@testing-library/react": "^14.2.1", 19 | "@types/jest": "^29.5.12", 20 | "@types/node": "^14.6.4", 21 | "@types/react": "^18.2.56", 22 | "@types/react-dom": "^18.2.19", 23 | "husky": "^9.0.11", 24 | "jest": "^29.7.0", 25 | "jest-environment-jsdom": "^29.7.0", 26 | "lint-staged": "^15.2.2", 27 | "prettier": "^3.2.5", 28 | "react": "^18.2.0", 29 | "react-dom": "^18.2.0", 30 | "ts-jest": "^29.1.2", 31 | "typescript": "^5.3.3", 32 | "uglify-js": "^3.17.4" 33 | }, 34 | "volta": { 35 | "node": "18.19.1" 36 | }, 37 | "lint-staged": { 38 | "*.{jsx?,tsx?,json,md}": "prettier --write" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # Contributor Covenant Code of Conduct 4 | 5 | ## Our Pledge 6 | 7 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 8 | 9 | ## Our Standards 10 | 11 | Examples of behavior that contributes to creating a positive environment include: 12 | 13 | - Using welcoming and inclusive language 14 | - Being respectful of differing viewpoints and experiences 15 | - Gracefully accepting constructive criticism 16 | - Focusing on what is best for the community 17 | - Showing empathy towards other community members 18 | 19 | Examples of unacceptable behavior by participants include: 20 | 21 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 22 | - Trolling, insulting/derogatory comments, and personal or political attacks 23 | - Public or private harassment 24 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 25 | - Other conduct which could reasonably be considered inappropriate in a professional setting 26 | 27 | ## Our Responsibilities 28 | 29 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 30 | 31 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 32 | 33 | ## Scope 34 | 35 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 36 | 37 | ## Enforcement 38 | 39 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at support@dddice.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 40 | 41 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 42 | 43 | ## Attribution 44 | 45 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 46 | 47 | [homepage]: http://contributor-covenant.org 48 | [version]: http://contributor-covenant.org/version/1/4/ 49 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | When contributing to this repository, please first discuss the change you wish to make via issue, 4 | email, or any other method with the owners of this repository before making a change. 5 | 6 | Please note we have a code of conduct, please follow it in all your interactions with the project. 7 | 8 | ## Pull Request Process 9 | 10 | 1. Ensure any install or build dependencies are removed before the end of the layer when doing a 11 | build. 12 | 2. Update the README.md with details of changes to the interface, this includes new environment 13 | variables, exposed ports, useful file locations and container parameters. 14 | 3. Increase the version numbers in any examples files and the README.md to the new version that this 15 | Pull Request would represent. The versioning scheme we use is [SemVer](http://semver.org/). 16 | 4. You may merge the Pull Request in once you have the sign-off of two other developers, or if you 17 | do not have permission to do that, you may request the second reviewer to merge it for you. 18 | 19 | ## Code of Conduct 20 | 21 | ### Our Pledge 22 | 23 | In the interest of fostering an open and welcoming environment, we as 24 | contributors and maintainers pledge to making participation in our project and 25 | our community a harassment-free experience for everyone, regardless of age, body 26 | size, disability, ethnicity, gender identity and expression, level of experience, 27 | nationality, personal appearance, race, religion, or sexual identity and 28 | orientation. 29 | 30 | ### Our Standards 31 | 32 | Examples of behavior that contributes to creating a positive environment 33 | include: 34 | 35 | * Using welcoming and inclusive language 36 | * Being respectful of differing viewpoints and experiences 37 | * Gracefully accepting constructive criticism 38 | * Focusing on what is best for the community 39 | * Showing empathy towards other community members 40 | 41 | Examples of unacceptable behavior by participants include: 42 | 43 | * The use of sexualized language or imagery and unwelcome sexual attention or 44 | advances 45 | * Trolling, insulting/derogatory comments, and personal or political attacks 46 | * Public or private harassment 47 | * Publishing others' private information, such as a physical or electronic 48 | address, without explicit permission 49 | * Other conduct which could reasonably be considered inappropriate in a 50 | professional setting 51 | 52 | ### Our Responsibilities 53 | 54 | Project maintainers are responsible for clarifying the standards of acceptable 55 | behavior and are expected to take appropriate and fair corrective action in 56 | response to any instances of unacceptable behavior. 57 | 58 | Project maintainers have the right and responsibility to remove, edit, or 59 | reject comments, commits, code, wiki edits, issues, and other contributions 60 | that are not aligned to this Code of Conduct, or to ban temporarily or 61 | permanently any contributor for other behaviors that they deem inappropriate, 62 | threatening, offensive, or harmful. 63 | 64 | ### Scope 65 | 66 | This Code of Conduct applies both within project spaces and in public spaces 67 | when an individual is representing the project or its community. Examples of 68 | representing a project or community include using an official project e-mail 69 | address, posting via an official social media account, or acting as an appointed 70 | representative at an online or offline event. Representation of a project may be 71 | further defined and clarified by project maintainers. 72 | 73 | ### Enforcement 74 | 75 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 76 | reported by contacting the project team at [INSERT EMAIL ADDRESS]. All 77 | complaints will be reviewed and investigated and will result in a response that 78 | is deemed necessary and appropriate to the circumstances. The project team is 79 | obligated to maintain confidentiality with regard to the reporter of an incident. 80 | Further details of specific enforcement policies may be posted separately. 81 | 82 | Project maintainers who do not follow or enforce the Code of Conduct in good 83 | faith may face temporary or permanent repercussions as determined by other 84 | members of the project's leadership. 85 | 86 | ### Attribution 87 | 88 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 89 | available at [http://contributor-covenant.org/version/1/4][version] 90 | 91 | [homepage]: http://contributor-covenant.org 92 | [version]: http://contributor-covenant.org/version/1/4/ 93 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # react-keybind ⌨️ 4 | 5 | ![npm](https://img.shields.io/npm/v/react-keybind.svg) 6 | 7 | A lightweight library to manage global keyboard shortcuts for your [React](https://reactjs.org) 8 | application. Just how lightweight is it? 9 | 10 | ![minified size](https://badgen.net/bundlephobia/min/react-keybind) 11 | ![minzipped size](https://badgen.net/bundlephobia/minzip/react-keybind) 12 | 13 | ### Who should use this library? 14 | 15 | - Your application contains many components that require keyboard shortcuts 16 | - Your application frequently changes keyboard shortcuts depending on the screen 17 | - Your application needs a list of all active shortcuts on the screen 18 | - Your application needs a simple way to manage keyboard shortcuts 19 | 20 | ### Why another keyboard shortcut library? 21 | 22 | We wrote `react-keybind` with a few main goals: 23 | 24 | - **No External Dependencies** - We wanted full control over the experience and size of the library 25 | - **No RFC/Experimental Features** - We wanted to build on top of a stable API 26 | - **TypeScript Support** - We wanted to support [TypeScript](https://www.typescriptlang.org/) 27 | 28 | ## Features 29 | 30 | - Register shortcuts for single keypresses 31 | - Register shortcuts for combination keypresses (e.g. ctrl+c, ctrl+alt+a) 32 | - Register shortcuts for keypresses held after a duration 33 | - Register shortcuts for sequenced keypresses (e.g. up, up, down, down, enter) 34 | - Creates one listener for all keyboard shortcuts - _fast and lightweight!_ 35 | 36 | ### Roadmap 37 | 38 | - **Focus** - Support executing shortcuts when a particular element is focused 39 | 40 | ## Installation 41 | 42 | ```bash 43 | $ npm i react-keybind --save 44 | ``` 45 | 46 | ### Requirements 47 | 48 | This library uses [React Context](https://reactjs.org/docs/context.html) which requires React 16.3+. 49 | 50 | ### TypeScript 51 | 52 | This library utilizes [TypeScript](https://www.typescriptlang.org/) and exposes a full set of 53 | TypeScript definitions. 54 | 55 | ## Usage 56 | 57 | This library exposes a default `withShortcut` 58 | [Higher-Order Component](https://reactjs.org/docs/higher-order-components.html) which is used to 59 | wrap any component that wants to utilize keyboard shortcuts. 60 | 61 | Your main application should be wrapped in the exposed ``. 62 | 63 | ### Example 64 | 65 | ```typescript 66 | import { useCallback, useEffect, useState } from 'react'; 67 | import { useShortcut } from 'react-keybind'; 68 | 69 | // Component that implements a shortcut 70 | const MyComponent = () => { 71 | const {registerShortcut, unregisterShortcut} = useShortcut(); 72 | const [state, setState] = useState({ 73 | isSaved: false, 74 | }); 75 | 76 | const save = useCallback(async (e) => { 77 | setState(nextState => ({ 78 | ...nextState, 79 | isSaved: true, 80 | })); 81 | }, [state]); 82 | 83 | useEffect(() => { 84 | registerShortcut(save, ['ctrl+s', 'cmd+s'], 'Save', 'Save the file') 85 | return () => { 86 | unregisterShortcut(['ctrl+s', 'cmd+s']) 87 | } 88 | }, []) 89 | 90 | return ( 91 |
92 | The file is saved: {state.isSaved ? 'true' : 'false'} 93 |
94 | ); 95 | } 96 | 97 | // Root application 98 | const App = () => ( 99 | 100 | 101 | 102 | ); 103 | ``` 104 | 105 | ## API 106 | 107 | react-keybind exposes a small set of Components to use in your application. 108 | 109 | ### `` 110 | 111 | Initializes the main provider for shortcuts. This component should be placed at the root of your 112 | application where you want to start listening on keyboard shortcuts. 113 | 114 | #### Props 115 | 116 | | **Prop** | **Type** | **Default** | **Description** | 117 | | ------------------- | -------- | ----------- | ----------------------------------------------------------------- | 118 | | **ignoreKeys** | string[] | [] | Array of keys to ignore (e.g. ['shift', 'ctrl']) | 119 | | **ignoreTagNames** | string[] | ['input'] | Array of tagNames to ignore (e.g. ['input', 'article']) | 120 | | **preventDefault** | boolean | true | Call `preventDefault()` automatically when a shortcut is executed | 121 | | **sequenceTimeout** | number | 2000 | How long to wait before checking if a sequence is complete | 122 | 123 | ### `useShortcut()` 124 | 125 | Hook to consume shortcuts. Provides the following interface: 126 | 127 | ```typescript 128 | { 129 | registerShortcut: ( 130 | method: (e?: React.KeyboardEvent) => any, 131 | keys: string[], 132 | title: string, 133 | description: string, 134 | holdDuration?: number, 135 | ) => void; 136 | registerSequenceShortcut: ( 137 | method: () => any, 138 | keys: string[], 139 | title: string, 140 | description: string, 141 | ) => void; 142 | shortcuts: Shortcut[]; 143 | triggerShortcut: (key: string) => any; 144 | unregisterShortcut: (keys: string[]) => void; 145 | setEnabled: (enabled: boolean) => void; 146 | } 147 | ``` 148 | 149 | ## Use Cases 150 | 151 | This library was built specifically for [dddice](https://dddice.com), an 152 | online platform to roll dice for tabletop roleplaying games. 153 | 154 | The dddice platform contains many different screens than handle a wide variety of purposes. Each 155 | screen in dddice might contain several dozens of keyboard shortcuts. 156 | 157 | Instead of managing each screen individually and keeping track of which shortcuts are used where, 158 | we simplify the process by letting components decide which shortcuts they want to define and 159 | tracking the list of active shortcuts globally. This is especially useful for rendering a quick 160 | "Shortcut Menu" for our users no matter where the user might be in the application. 161 | 162 | We open-sourced this library in hopes that other projects might find it useful 💙 163 | 164 | ## License 165 | 166 | MIT 167 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | /** 2 | * react-keybind 3 | * 4 | * Creates keyboard shortcuts for your React application 5 | * 6 | * @format 7 | */ 8 | 9 | import { 10 | memo, 11 | createContext, 12 | useCallback, 13 | useEffect, 14 | useRef, 15 | useState, 16 | ReactNode, 17 | useMemo, 18 | PropsWithChildren, 19 | } from 'react'; 20 | import { useContext } from 'react'; 21 | 22 | /** 23 | * Shortcut 24 | */ 25 | export interface IShortcut { 26 | description: string; 27 | hold: boolean; 28 | holdDuration: number; 29 | id: string; 30 | keys: string[]; 31 | method: (props: any) => any; 32 | sequence: boolean; 33 | title: string; 34 | } 35 | 36 | /** 37 | * Shortcut binding 38 | */ 39 | export interface IShortcutBinding { 40 | [key: string]: IShortcut; 41 | } 42 | 43 | /** 44 | * Shortcut Props 45 | */ 46 | export interface IShortcutProviderProps { 47 | children?: ReactNode; 48 | ignoreKeys?: string[]; 49 | ignoreTagNames?: string[]; 50 | preventDefault?: boolean; 51 | sequenceTimeout?: number; 52 | } 53 | 54 | /** 55 | * Shortcut State 56 | */ 57 | export type IShortcutProviderState = IShortcut[]; 58 | 59 | /** 60 | * Shortcut Render Props 61 | */ 62 | export type IShortcutProviderRenderProps = { 63 | registerShortcut: ( 64 | method: (e?: KeyboardEvent) => any, 65 | keys: string[], 66 | title: string, 67 | description: string, 68 | holdDuration?: number, 69 | ) => void; 70 | registerSequenceShortcut: ( 71 | method: () => any, 72 | keys: string[], 73 | title: string, 74 | description: string, 75 | ) => void; 76 | setEnabled: (enabled: boolean) => void; 77 | triggerShortcut: (key: string) => any; 78 | unregisterShortcut: (keys: string[]) => void; 79 | } & { shortcuts: IShortcutProviderState }; 80 | 81 | /** 82 | * Listener Interface 83 | */ 84 | interface ISingleShortcutListener { 85 | [key: string]: (e?: KeyboardEvent) => any; 86 | } 87 | 88 | /** 89 | * MultiListener Interface 90 | * Uses an array to store multiple different shortcuts. Only applies to standard shortcuts 91 | */ 92 | interface IShortcutListener { 93 | [key: string]: ((e?: KeyboardEvent) => any)[]; 94 | } 95 | 96 | /** 97 | * Default tags to ignore shortcuts when focused 98 | */ 99 | const ignoreForTagNames = ['input', 'textarea', 'select']; 100 | 101 | const ShortcutContext = createContext(undefined); 102 | 103 | /** 104 | * Route known keys to their proper exectued counterpart 105 | * 106 | * Mappings: 107 | * - opt, option = alt 108 | * - control = ctrl 109 | * - cmd, command = meta 110 | */ 111 | const transformKeys = (keys: string[]) => { 112 | return keys.map(rawKeys => { 113 | // force keys to be a string (we might have a number) 114 | const splitKeys = `${rawKeys}`.split('+'); 115 | const transformedKeys = splitKeys.map(key => { 116 | const keyEvent = key.toLowerCase(); 117 | switch (keyEvent) { 118 | case 'opt': 119 | case 'option': 120 | return 'alt'; 121 | case 'control': 122 | return 'ctrl'; 123 | case 'cmd': 124 | case 'command': 125 | return 'meta'; 126 | default: 127 | return keyEvent; 128 | } 129 | }); 130 | return transformedKeys.join('+'); 131 | }); 132 | }; 133 | 134 | export const ShortcutProvider = memo( 135 | ({ children, ...props }: PropsWithChildren) => { 136 | const holdDurations = useRef<{ 137 | [key: string]: number; 138 | }>({}); 139 | const holdInterval = useRef(); 140 | const holdListeners = useRef({}); 141 | const holdTimer = useRef(0); 142 | const keysDown = useRef([]); 143 | const listeners = useRef({}); 144 | const previousKeys = useRef([]); 145 | const sequenceListeners = useRef({}); 146 | const sequenceTimer = useRef(); 147 | const shortcuts = useRef([]); 148 | 149 | const [shortcutsState, setShortcutsState] = useState([]); 150 | const isEnabled = useRef(true); 151 | 152 | /** 153 | * Create an interval timer to check the duration of held keypresses 154 | */ 155 | const createTimer = useCallback((callback: () => void) => { 156 | holdInterval.current = window.setInterval(() => { 157 | callback(); 158 | holdTimer.current += 100; 159 | }, 100); 160 | }, []); 161 | 162 | /** 163 | * Handle "keydown" events and run the appropriate registered method 164 | */ 165 | const keyDown = useCallback( 166 | (e: KeyboardEvent) => { 167 | if (!isEnabled.current) return; 168 | 169 | const { ignoreKeys = [], ignoreTagNames, preventDefault = true } = props; 170 | const target = e.target as HTMLElement; 171 | // ignore listening when certain elements are focused 172 | const ignore = ignoreTagNames 173 | ? ignoreTagNames.map(tag => tag.toLowerCase()) 174 | : ignoreForTagNames; 175 | // The currently pressed key 176 | const key: string = e.key?.toLowerCase(); 177 | 178 | // ensure that we're not focused on an element such as an 179 | if ( 180 | key && 181 | ignore.indexOf(target.tagName.toLowerCase()) < 0 && 182 | keysDown.current.indexOf(key) < 0 183 | ) { 184 | const nextKeysDown: string[] = []; 185 | const nextModKeys: string[] = []; 186 | if ((key === 'control' || e.ctrlKey) && ignoreKeys.indexOf('ctrl') < 0) { 187 | if (keysDown.current.indexOf('ctrl') < 0) nextKeysDown.push('ctrl'); 188 | if (key === 'control') nextModKeys.push(key); 189 | } 190 | if ((key === 'alt' || e.altKey) && ignoreKeys.indexOf('alt') < 0) { 191 | if (keysDown.current.indexOf('alt') < 0) nextKeysDown.push('alt'); 192 | if (key === 'alt') nextModKeys.push(key); 193 | } 194 | if ( 195 | (key === 'meta' || e.metaKey) && 196 | ignoreKeys.indexOf('meta') < 0 && 197 | ignoreKeys.indexOf('cmd') < 0 198 | ) { 199 | if (keysDown.current.indexOf('meta') < 0) nextKeysDown.push('meta'); 200 | if (key === 'meta') nextModKeys.push(key); 201 | } 202 | if ((key === 'shift' || e.shiftKey) && ignoreKeys.indexOf('shift') < 0) { 203 | if (keysDown.current.indexOf('shift') < 0) nextKeysDown.push('shift'); 204 | if (key === 'shift') nextModKeys.push(key); 205 | } 206 | 207 | if ([...ignoreKeys, ...nextModKeys].indexOf(key) < 0) { 208 | nextKeysDown.push(key); 209 | } 210 | 211 | keysDown.current = [...keysDown.current, ...nextKeysDown]; 212 | 213 | const keyPress = keysDown.current.join('+'); 214 | if (listeners.current[keyPress]) { 215 | // automatically preventDefault on the key 216 | if (preventDefault) { 217 | e.preventDefault(); 218 | } 219 | listeners.current[keyPress].forEach(method => method(e)); 220 | } 221 | 222 | // create an interval to check the duration every 100ms 223 | resetTimer(); 224 | createTimer(() => { 225 | nextKeysDown.forEach(key => { 226 | if (holdTimer.current >= holdDurations.current[key]) { 227 | // we're paseed the duration - execute and reset the timer check 228 | holdListeners.current?.[keyPress](e); 229 | resetTimer(); 230 | } 231 | }); 232 | }); 233 | 234 | // check if we fulfilled a sequence 235 | if (sequenceTimer.current !== undefined) { 236 | window.clearTimeout(sequenceTimer.current); 237 | } 238 | 239 | // Track previously pressed keys 240 | previousKeys.current.push(...nextKeysDown); 241 | 242 | const sequenceKeys = previousKeys.current.join(','); 243 | if (sequenceListeners.current[sequenceKeys] !== undefined) { 244 | sequenceListeners.current[sequenceKeys](e); 245 | if (sequenceTimer.current) { 246 | window.clearTimeout(sequenceTimer.current); 247 | sequenceTimer.current = undefined; 248 | previousKeys.current = []; 249 | } 250 | } 251 | 252 | // we have 2s to keep sequencing keys otherwise we'll reset the previous array 253 | sequenceTimer.current = window.setTimeout(() => { 254 | previousKeys.current = []; 255 | sequenceTimer.current = undefined; 256 | }, props.sequenceTimeout ?? 2000); 257 | } 258 | }, 259 | [props], 260 | ); 261 | 262 | /** 263 | * Unset the previously pressed keys 264 | */ 265 | const keyUp = useCallback((e: KeyboardEvent) => { 266 | const keysUp: string[] = []; 267 | const key: string = e.key?.toLowerCase(); 268 | 269 | if (key === 'control' || e.ctrlKey) { 270 | keysUp.push('ctrl'); 271 | } 272 | if (key === 'alt' || e.altKey) { 273 | keysUp.push('alt'); 274 | } 275 | if (key === 'meta' || e.metaKey) { 276 | keysUp.push('meta'); 277 | } 278 | if (key === 'shift' || e.shiftKey) { 279 | keysUp.push('shift'); 280 | } 281 | 282 | const specialKeys = ['control', 'alt', 'meta', 'shift']; 283 | if (specialKeys.indexOf(key) < 0) { 284 | keysUp.push(key); 285 | } 286 | 287 | keysDown.current = keysDown.current.filter(key => keysUp.indexOf(key) < 0); 288 | 289 | resetTimer(); 290 | }, []); 291 | 292 | /** 293 | * On blur of the window, we unset keyDown because the keyUp event happens outside of the window focus 294 | */ 295 | const windowBlur = useCallback(() => { 296 | keysDown.current = []; 297 | resetTimer(); 298 | }, []); 299 | 300 | /** 301 | * Register a new shortcut for the application 302 | * 303 | * Set a holdDuration to execute the shortcut only after the set keys have been pressed for the 304 | * configured duration. 305 | */ 306 | const registerShortcut = useCallback( 307 | ( 308 | method: (e?: KeyboardEvent) => any, 309 | keys: string[] = [], 310 | title: string, 311 | description: string, 312 | holdDuration?: number, 313 | ) => { 314 | const nextShortcuts = [...shortcuts.current]; 315 | 316 | // do we need to hold this shortcut? 317 | const hold = holdDuration !== undefined; 318 | const duration = holdDuration !== undefined ? holdDuration : 0; 319 | const transformedKeys = transformKeys(keys); 320 | 321 | // create new shortcut 322 | const shortcut: IShortcut = { 323 | id: Date.now().toString(36), 324 | description, 325 | hold, 326 | holdDuration: duration, 327 | keys: transformedKeys, 328 | method, 329 | sequence: false, 330 | title, 331 | }; 332 | // add it to the list of shortcuts 333 | nextShortcuts.push(shortcut); 334 | 335 | // create a listener for each key 336 | transformedKeys.forEach(key => { 337 | if (hold) { 338 | holdDurations.current[key] = duration; 339 | holdListeners.current[key] = method; 340 | } else { 341 | if (!listeners.current[key]) { 342 | listeners.current[key] = []; 343 | } 344 | 345 | listeners.current[key] = [...listeners.current[key], method]; 346 | } 347 | }); 348 | 349 | shortcuts.current = nextShortcuts; 350 | setShortcutsState(nextShortcuts); 351 | }, 352 | [], 353 | ); 354 | 355 | /** 356 | * Register a shortcut that listens for a sequence of keys to be pressed 357 | * 358 | * Unlike the registerShortcut method, the array of keys represents the keys that need to be 359 | * pressed in the configured order 360 | */ 361 | const registerSequenceShortcut = useCallback( 362 | (method: () => any, keys: string[] = [], title: string, description: string) => { 363 | const nextShortcuts = [...shortcuts.current]; 364 | 365 | // create new shortcut 366 | const shortcut: IShortcut = { 367 | id: Date.now().toString(36), 368 | description, 369 | hold: false, 370 | holdDuration: 0, 371 | keys, 372 | method, 373 | sequence: true, 374 | title, 375 | }; 376 | 377 | // check if we already have existing keys for the new keys being passed 378 | let exists = false; 379 | const keyEvent = keys.join(',').toLowerCase(); 380 | Object.keys(sequenceListeners.current).forEach(existingKey => { 381 | exists = exists || keyEvent === existingKey; 382 | }); 383 | 384 | if (!exists) { 385 | nextShortcuts.push(shortcut); 386 | 387 | // create a listener for each key 388 | sequenceListeners.current[keyEvent] = method; 389 | 390 | shortcuts.current = nextShortcuts; 391 | 392 | setShortcutsState(nextShortcuts); 393 | } 394 | }, 395 | [], 396 | ); 397 | 398 | /** 399 | * Reset the keypress timer 400 | */ 401 | const resetTimer = useCallback(() => { 402 | if (holdInterval.current !== undefined) { 403 | window.clearInterval(holdInterval.current); 404 | holdInterval.current = undefined; 405 | holdTimer.current = 0; 406 | } 407 | }, []); 408 | 409 | /** 410 | * Programatically trigger a shortcut using a key sequence 411 | * 412 | * Note: This ignores any ignored keys meaning this method is useful for bypassing otherwise 413 | * disabled shortcuts. 414 | */ 415 | const triggerShortcut = useCallback((key: string) => { 416 | const transformedKeys = transformKeys([key]); 417 | const transformKey = transformedKeys.pop(); 418 | if (transformKey && listeners.current[transformKey]) { 419 | listeners.current[transformKey].forEach(method => method()); 420 | } 421 | }, []); 422 | 423 | /** 424 | * Remove a shortcut from the application 425 | */ 426 | const unregisterShortcut = useCallback((keys: string[], sequence: boolean = false) => { 427 | const transformedKeys = transformKeys(keys); 428 | if (!sequence) { 429 | transformedKeys.forEach(key => { 430 | if (listeners.current[key]) { 431 | listeners.current[key].pop(); 432 | 433 | if (listeners.current[key].length === 0) { 434 | delete listeners.current[key]; 435 | } 436 | } 437 | delete holdListeners.current[key]; 438 | delete holdDurations.current[key]; 439 | }); 440 | } else { 441 | const keyEvent = transformedKeys.join(','); 442 | delete sequenceListeners.current[keyEvent]; 443 | } 444 | 445 | // Delete the shortcut 446 | const nextShortcuts = shortcuts.current.filter(({ keys: shortcutKeys }) => { 447 | let match = true; 448 | shortcutKeys.forEach(shortcutKey => { 449 | match = match && transformedKeys.indexOf(shortcutKey) >= 0; 450 | }); 451 | return !match; 452 | }); 453 | 454 | shortcuts.current = nextShortcuts; 455 | setShortcutsState(nextShortcuts); 456 | }, []); 457 | 458 | const setEnabled = useCallback((enabled: boolean) => { 459 | isEnabled.current = enabled; 460 | }, []); 461 | 462 | const value = useMemo( 463 | () => 464 | ({ 465 | registerSequenceShortcut, 466 | registerShortcut, 467 | shortcuts: shortcutsState, 468 | triggerShortcut, 469 | unregisterShortcut, 470 | setEnabled, 471 | }) satisfies IShortcutProviderRenderProps, 472 | [ 473 | shortcutsState, 474 | registerShortcut, 475 | registerSequenceShortcut, 476 | triggerShortcut, 477 | unregisterShortcut, 478 | setEnabled, 479 | ], 480 | ); 481 | 482 | useEffect(() => { 483 | window.addEventListener('keydown', keyDown); 484 | window.addEventListener('keyup', keyUp); 485 | window.addEventListener('blur', windowBlur); 486 | 487 | return () => { 488 | window.removeEventListener('keydown', keyDown); 489 | window.removeEventListener('keyup', keyUp); 490 | window.removeEventListener('blur', windowBlur); 491 | }; 492 | }, [keyDown, keyUp, windowBlur]); 493 | 494 | return {children}; 495 | }, 496 | ); 497 | 498 | /** 499 | * Default useShortcut hook 500 | * 501 | * Returns methods to register/unregister shortcuts 502 | */ 503 | export const useShortcut = () => useContext(ShortcutContext); 504 | -------------------------------------------------------------------------------- /src/__tests__/index.tsx: -------------------------------------------------------------------------------- 1 | /** @format */ 2 | 3 | import { 4 | act, 5 | createEvent, 6 | fireEvent, 7 | screen, 8 | renderHook, 9 | RenderHookResult, 10 | } from '@testing-library/react'; 11 | import { 12 | ShortcutProvider, 13 | useShortcut, 14 | IShortcutProviderRenderProps, 15 | IShortcutProviderProps, 16 | } from '../index'; 17 | import {DragEventHandler, PropsWithChildren, useCallback} from 'react'; 18 | 19 | const createWrapper = 20 | ({ children: wrapperChildren, ...props }: PropsWithChildren = {}) => 21 | ({ children }: PropsWithChildren) => ( 22 | 23 |
24 | {wrapperChildren} 25 | {children} 26 |
27 |
28 | ); 29 | 30 | describe('react-keybind', () => { 31 | describe('ShortcutProvider', () => { 32 | let wrapper: (props: PropsWithChildren) => JSX.Element; 33 | let hook: RenderHookResult; 34 | let method: jest.Mock; 35 | let node: HTMLElement; 36 | 37 | beforeEach(() => { 38 | wrapper = createWrapper(); 39 | hook = renderHook(useShortcut, { wrapper }); 40 | node = screen.getByTestId('test'); 41 | method = jest.fn(); 42 | 43 | jest.useFakeTimers(); 44 | }); 45 | 46 | describe('.registerShortcut', () => { 47 | it('executes callback method for single keypresses', () => { 48 | act(() => { 49 | hook.result.current?.registerShortcut(method, ['x'], 'Test Title', 'Some description'); 50 | }); 51 | 52 | fireEvent.keyDown(node, { key: 'x' }); 53 | expect(method).toHaveBeenCalledTimes(1); 54 | }); 55 | 56 | it('calls preventDefault on shortcut execution', () => { 57 | act(() => { 58 | hook.result.current?.registerShortcut(method, ['x'], 'Test Title', 'Some description'); 59 | }); 60 | 61 | const stub = createEvent.keyDown(node, { key: 'x' }); 62 | fireEvent(node, stub); 63 | expect(stub.defaultPrevented).toBe(true); 64 | }); 65 | 66 | it('skips calling preventDefault on shortcut execution if option passed', () => { 67 | wrapper = createWrapper({ preventDefault: false }); 68 | hook = renderHook(useShortcut, { wrapper }); 69 | act(() => { 70 | hook.result.current?.registerShortcut(method, ['x'], 'Test Title', 'Some description'); 71 | }); 72 | 73 | const stub = createEvent.keyDown(node, { key: 'x' }); 74 | fireEvent(node, stub); 75 | expect(stub.defaultPrevented).toBe(false); 76 | }); 77 | 78 | it('does not execute callback for unregistered keypresses', () => { 79 | act(() => { 80 | hook.result.current?.registerShortcut(method, ['x'], 'Test Title', 'Some description'); 81 | }); 82 | fireEvent.keyDown(node, { key: 'a' }); 83 | expect(method).toHaveBeenCalledTimes(0); 84 | }); 85 | 86 | it('executes callback method for ctrl+{key} keypresses', () => { 87 | act(() => { 88 | hook.result.current?.registerShortcut(method, ['ctrl+x'], 'Cut', 'Test cut description'); 89 | }); 90 | fireEvent.keyDown(node, { key: 'x', ctrlKey: true }); 91 | expect(method).toHaveBeenCalledTimes(1); 92 | }); 93 | 94 | it('executes callback method for alt+{key} keypresses', () => { 95 | act(() => { 96 | hook.result.current?.registerShortcut(method, ['alt+a'], 'All', 'Test select all'); 97 | }); 98 | fireEvent.keyDown(node, { key: 'a', altKey: true }); 99 | expect(method).toHaveBeenCalledTimes(1); 100 | }); 101 | 102 | it('executes callback method for ctrl+alt+{key} keypresses', () => { 103 | act(() => { 104 | hook.result.current?.registerShortcut( 105 | method, 106 | ['ctrl+alt+s'], 107 | 'Shutdown all', 108 | 'Test shutdown all processes', 109 | ); 110 | }); 111 | fireEvent.keyDown(node, { key: 's', altKey: true, ctrlKey: true }); 112 | expect(method).toHaveBeenCalledTimes(1); 113 | }); 114 | 115 | it('is case-insensitive', () => { 116 | act(() => { 117 | hook.result.current?.registerShortcut(method, ['X'], 'Test Title', 'Some description'); 118 | }); 119 | fireEvent.keyDown(node, { key: 'x' }); 120 | expect(method).toHaveBeenCalledTimes(1); 121 | }); 122 | 123 | it('ignores callback method execution for ignored element types', () => { 124 | wrapper = createWrapper({ children: }); 125 | hook = renderHook(useShortcut, { wrapper }); 126 | act(() => { 127 | hook.result.current?.registerShortcut(method, ['a'], 'Test', 'Some description'); 128 | }); 129 | 130 | fireEvent.keyDown(screen.getByTestId('input'), { key: 'a' }); 131 | expect(method).toHaveBeenCalledTimes(0); 132 | }); 133 | 134 | it('executes callback method after a duration', () => { 135 | act(() => { 136 | hook.result.current?.registerShortcut( 137 | method, 138 | ['f'], 139 | 'Pay respects', 140 | 'Some description', 141 | 1000, 142 | ); 143 | }); 144 | fireEvent.keyDown(node, { key: 'f' }); 145 | expect(method).toHaveBeenCalledTimes(0); 146 | jest.advanceTimersByTime(2000); 147 | expect(method).toHaveBeenCalledTimes(1); // we should not keep calling the method 148 | }); 149 | 150 | it('executes callback method for sequenced keypresses', () => { 151 | act(() => { 152 | hook.result.current?.registerSequenceShortcut( 153 | method, 154 | ['up', 'down', 'up', 'down'], 155 | 'Test', 156 | 'test', 157 | ); 158 | }); 159 | 160 | fireEvent.keyDown(node, { key: 'up' }); 161 | fireEvent.keyUp(node, { key: 'up' }); 162 | fireEvent.keyDown(node, { key: 'down' }); 163 | fireEvent.keyUp(node, { key: 'down' }); 164 | fireEvent.keyDown(node, { key: 'up' }); 165 | fireEvent.keyUp(node, { key: 'up' }); 166 | fireEvent.keyDown(node, { key: 'down' }); 167 | fireEvent.keyUp(node, { key: 'down' }); 168 | 169 | expect(method).toHaveBeenCalledTimes(1); 170 | }); 171 | 172 | it('allows some duration of time to pass between sequenced keypresses', () => { 173 | act(() => { 174 | hook.result.current?.registerSequenceShortcut( 175 | method, 176 | ['up', 'down', 'up', 'down'], 177 | 'Test', 178 | 'test', 179 | ); 180 | }); 181 | 182 | fireEvent.keyDown(node, { key: 'up' }); 183 | fireEvent.keyUp(node, { key: 'up' }); 184 | fireEvent.keyDown(node, { key: 'down' }); 185 | fireEvent.keyUp(node, { key: 'down' }); 186 | 187 | jest.advanceTimersByTime(100); 188 | 189 | fireEvent.keyDown(node, { key: 'up' }); 190 | fireEvent.keyUp(node, { key: 'up' }); 191 | fireEvent.keyDown(node, { key: 'down' }); 192 | fireEvent.keyUp(node, { key: 'down' }); 193 | 194 | expect(method).toHaveBeenCalledTimes(1); 195 | }); 196 | 197 | it('cancels callback method for sequenced keypresses after a duration', () => { 198 | act(() => { 199 | hook.result.current?.registerSequenceShortcut( 200 | method, 201 | ['up', 'down', 'up', 'down'], 202 | 'Test', 203 | 'test', 204 | ); 205 | }); 206 | 207 | fireEvent.keyDown(node, { key: 'up' }); 208 | fireEvent.keyUp(node, { key: 'up' }); 209 | fireEvent.keyDown(node, { key: 'down' }); 210 | fireEvent.keyUp(node, { key: 'down' }); 211 | 212 | jest.advanceTimersByTime(2000); 213 | 214 | fireEvent.keyDown(node, { key: 'up' }); 215 | fireEvent.keyUp(node, { key: 'up' }); 216 | fireEvent.keyDown(node, { key: 'down' }); 217 | fireEvent.keyUp(node, { key: 'down' }); 218 | 219 | expect(method).toHaveBeenCalledTimes(0); 220 | }); 221 | 222 | it('resets sequenced keypresses timer after a successful execution', () => { 223 | const executeSequence = () => { 224 | fireEvent.keyDown(node, { key: 'a' }); 225 | fireEvent.keyUp(node, { key: 'a' }); 226 | fireEvent.keyDown(node, { key: 'b' }); 227 | fireEvent.keyUp(node, { key: 'b' }); 228 | fireEvent.keyDown(node, { key: 'c' }); 229 | fireEvent.keyUp(node, { key: 'c' }); 230 | fireEvent.keyDown(node, { key: 'd' }); 231 | fireEvent.keyUp(node, { key: 'd' }); 232 | }; 233 | 234 | act(() => { 235 | hook.result.current?.registerSequenceShortcut( 236 | method, 237 | ['a', 'b', 'c', 'd'], 238 | 'Test', 239 | 'test', 240 | ); 241 | }); 242 | 243 | executeSequence(); 244 | expect(method).toHaveBeenCalledTimes(1); 245 | 246 | executeSequence(); 247 | expect(method).toHaveBeenCalledTimes(2); 248 | }); 249 | 250 | it('can reregister shortcuts after they have been unregistered', () => { 251 | act(() => { 252 | hook.result.current?.registerShortcut(method, ['a'], 'Test Title', 'Some description'); 253 | hook.result.current?.unregisterShortcut(['a']); 254 | hook.result.current?.registerShortcut(method, ['a'], 'Test Title', 'Some description'); 255 | }); 256 | 257 | fireEvent.keyDown(node, { key: 'a' }); 258 | expect(method).toHaveBeenCalledTimes(1); 259 | }); 260 | 261 | it('calls multiple callbacks', () => { 262 | const methodX = jest.fn(); 263 | act(() => { 264 | hook.result.current?.registerShortcut( 265 | method, 266 | ['ctrl+a', 'a'], 267 | 'Test Title', 268 | 'Some description', 269 | ); 270 | hook.result.current?.registerShortcut(methodX, ['a'], 'Test Title X', 'Some description'); 271 | }); 272 | 273 | fireEvent.keyDown(node, { key: 'a' }); 274 | expect(method).toHaveBeenCalledTimes(1); 275 | expect(methodX).toHaveBeenCalledTimes(1); 276 | }); 277 | 278 | it('detects modifier keys', () => { 279 | act(() => { 280 | hook.result.current?.registerShortcut( 281 | method, 282 | ['ctrl+x', 'shift+Y', 'alt+z', 'cmd+a'], 283 | '', 284 | '', 285 | ); 286 | }); 287 | fireEvent.keyDown(node, { key: 'x', ctrlKey: true }); 288 | fireEvent.keyUp(node, { key: 'x', ctrlKey: true }); 289 | 290 | fireEvent.keyDown(node, { key: 'y', shiftKey: true }); 291 | fireEvent.keyUp(node, { key: 'y', shiftKey: true }); 292 | 293 | fireEvent.keyDown(node, { key: 'z', altKey: true }); 294 | fireEvent.keyUp(node, { key: 'z', altKey: true }); 295 | 296 | fireEvent.keyDown(node, { key: 'a', metaKey: true }); 297 | fireEvent.keyUp(node, { key: 'a', metaKey: true }); 298 | 299 | expect(method).toHaveBeenCalledTimes(4); 300 | }); 301 | 302 | it('detects alternative modifier keys', () => { 303 | act(() => { 304 | hook.result.current?.registerShortcut( 305 | method, 306 | ['ctrl+x', 'shift+Y', 'alt+z', 'cmd+a'], 307 | '', 308 | '', 309 | ); 310 | }); 311 | 312 | fireEvent.keyDown(node, { key: 'Control' }); 313 | fireEvent.keyDown(node, { key: 'x' }); 314 | fireEvent.keyUp(node, { key: 'x', ctrlKey: true }); 315 | 316 | fireEvent.keyDown(node, { key: 'Shift' }); 317 | fireEvent.keyDown(node, { key: 'y' }); 318 | fireEvent.keyUp(node, { key: 'y', shiftKey: true }); 319 | 320 | fireEvent.keyDown(node, { key: 'Alt' }); 321 | fireEvent.keyDown(node, { key: 'z' }); 322 | fireEvent.keyUp(node, { key: 'z', altKey: true }); 323 | 324 | fireEvent.keyDown(node, { key: 'Meta' }); 325 | fireEvent.keyDown(node, { key: 'a' }); 326 | fireEvent.keyUp(node, { key: 'a', metaKey: true }); 327 | 328 | expect(method).toHaveBeenCalledTimes(4); 329 | }); 330 | 331 | it('ctrl sequences can be triggered multiple times', () => { 332 | act(() => { 333 | hook.result.current?.registerShortcut(method, ['ctrl+a', 'cmd+a'], '', ''); 334 | }); 335 | fireEvent.keyDown(node, { key: 'a', ctrlKey: true }); 336 | fireEvent.keyUp(node, { key: 'a', ctrlKey: true }); 337 | fireEvent.keyDown(node, { key: 'a', ctrlKey: true }); 338 | fireEvent.keyUp(node, { key: 'a', ctrlKey: true }); 339 | expect(method).toHaveBeenCalledTimes(2); 340 | }); 341 | 342 | it('cmd sequences can be triggered multiple times', () => { 343 | act(() => { 344 | hook.result.current?.registerShortcut(method, ['ctrl+a', 'cmd+a'], '', ''); 345 | }); 346 | const stub = createEvent.keyDown(node, { key: 'a', metaKey: true }); 347 | fireEvent(node, stub); 348 | expect(stub.defaultPrevented).toBe(true); 349 | 350 | fireEvent.keyUp(node, { key: 'a', metaKey: true }); 351 | const stub2 = createEvent.keyDown(node, { key: 'a', metaKey: true }); 352 | fireEvent(node, stub2); 353 | expect(stub2.defaultPrevented).toBe(true); 354 | 355 | fireEvent.keyUp(node, { key: 'a', metaKey: true }); 356 | expect(method).toHaveBeenCalledTimes(2); 357 | }); 358 | 359 | it('safely handles invalid number input', () => { 360 | act(() => { 361 | // @ts-ignore we are testing invalid input 362 | hook.result.current?.registerShortcut(method, [1], '', ''); 363 | }); 364 | fireEvent.keyDown(node, { key: '1' }); 365 | expect(method).toHaveBeenCalledTimes(1); 366 | }); 367 | 368 | it('safely ignores events with undefined key', () => { 369 | act(() => { 370 | hook.result.current?.registerShortcut(method, ['f'], '', ''); 371 | }); 372 | fireEvent.keyDown(node, { key: undefined }); 373 | expect(method).not.toHaveBeenCalled(); 374 | }); 375 | 376 | it('ignores special keys', () => { 377 | wrapper = createWrapper({ ignoreKeys: ['shift', 'ctrl', 'alt', 'cmd'] }); 378 | hook = renderHook(useShortcut, { wrapper }); 379 | act(() => { 380 | hook.result.current?.registerShortcut(method, ['x', 'Y', 'z', 'a'], '', ''); 381 | }); 382 | 383 | fireEvent.keyDown(node, { key: 'x', ctrlKey: true }); 384 | fireEvent.keyUp(node, { key: 'x', ctrlKey: true }); 385 | fireEvent.keyDown(node, { key: 'y', shiftKey: true }); 386 | fireEvent.keyUp(node, { key: 'y', shiftKey: true }); 387 | fireEvent.keyDown(node, { key: 'z', altKey: true }); 388 | fireEvent.keyUp(node, { key: 'z', altKey: true }); 389 | fireEvent.keyDown(node, { key: 'a', metaKey: true }); 390 | fireEvent.keyUp(node, { key: 'a', metaKey: true }); 391 | 392 | expect(method).toHaveBeenCalledTimes(4); 393 | }); 394 | 395 | it('accepts "meta" or "cmd" to ignore', () => { 396 | wrapper = createWrapper({ ignoreKeys: ['cmd'] }); 397 | hook = renderHook(useShortcut, { wrapper }); 398 | act(() => { 399 | hook.result.current?.registerShortcut(method, ['x'], '', ''); 400 | }); 401 | 402 | fireEvent.keyDown(node, { key: 'x', metaKey: true }); 403 | expect(method).toHaveBeenCalledTimes(1); 404 | 405 | wrapper = createWrapper({ ignoreKeys: ['meta'] }); 406 | hook = renderHook(useShortcut, { wrapper }); 407 | act(() => { 408 | hook.result.current?.registerShortcut(method, ['x'], '', ''); 409 | }); 410 | 411 | fireEvent.keyDown(node, { key: 'x', metaKey: true }); 412 | expect(method).toHaveBeenCalledTimes(2); 413 | }); 414 | 415 | it('ignores keys', () => { 416 | wrapper = createWrapper({ ignoreKeys: ['t'] }); 417 | hook = renderHook(useShortcut, { wrapper }); 418 | act(() => { 419 | hook.result.current?.registerSequenceShortcut(method, ['a', 'b'], '', ''); 420 | }); 421 | 422 | fireEvent.keyDown(node, { key: 'a' }); 423 | fireEvent.keyDown(node, { key: 't' }); // this is ignored 424 | fireEvent.keyDown(node, { key: 'b' }); 425 | expect(method).toHaveBeenCalledTimes(1); 426 | }); 427 | 428 | it('is a function', () => { 429 | expect(typeof hook.result.current?.registerShortcut).toEqual('function'); 430 | }); 431 | 432 | it('creates a new listener', () => { 433 | act(() => { 434 | hook.result.current?.registerShortcut( 435 | method, 436 | ['ctrl+c', 'k'], 437 | 'Test Title', 438 | 'Some description', 439 | ); 440 | }); 441 | 442 | expect(hook.result.current?.shortcuts).toHaveLength(1); 443 | expect(hook.result.current?.shortcuts[0].method).toEqual(method); 444 | expect(hook.result.current?.shortcuts[0].keys).toEqual(['ctrl+c', 'k']); 445 | }); 446 | 447 | it('allows multiple methods to use the same listeners', () => { 448 | const methodX = jest.fn(); 449 | act(() => { 450 | hook.result.current?.registerShortcut( 451 | method, 452 | ['shift+x'], 453 | 'Test Title', 454 | 'Some description', 455 | ); 456 | hook.result.current?.registerShortcut( 457 | methodX, 458 | ['shift+x', 'x'], 459 | 'Test Title', 460 | 'Some description', 461 | ); 462 | }); 463 | 464 | expect(hook.result.current?.shortcuts).toHaveLength(2); 465 | expect(hook.result.current?.shortcuts[0].method).toEqual(method); 466 | expect(hook.result.current?.shortcuts[0].keys).toEqual(['shift+x']); 467 | expect(hook.result.current?.shortcuts[1].method).toEqual(methodX); 468 | expect(hook.result.current?.shortcuts[1].keys).toEqual(['shift+x', 'x']); 469 | }); 470 | 471 | it('lowercases key bindings', () => { 472 | act(() => { 473 | hook.result.current?.registerShortcut( 474 | method, 475 | ['cTrL+C', 'K'], 476 | 'Test Title', 477 | 'Some description', 478 | ); 479 | }); 480 | expect(hook.result.current?.shortcuts).toHaveLength(1); 481 | expect(hook.result.current?.shortcuts[0].method).toEqual(method); 482 | expect(hook.result.current?.shortcuts[0].keys).toEqual(['ctrl+c', 'k']); 483 | }); 484 | 485 | it('creates a shortcut with a hold duration', () => { 486 | act(() => { 487 | hook.result.current?.registerShortcut( 488 | method, 489 | ['f'], 490 | 'Pay respects', 491 | 'Some description', 492 | 2000, 493 | ); 494 | }); 495 | 496 | expect(hook.result.current?.shortcuts).toHaveLength(1); 497 | expect(hook.result.current?.shortcuts[0].method).toEqual(method); 498 | expect(hook.result.current?.shortcuts[0].keys).toEqual(['f']); 499 | }); 500 | 501 | it('can unregister then reregister a shortcut', () => { 502 | act(() => { 503 | hook.result.current?.registerShortcut(method, ['a'], 'Test Title', 'Some description'); 504 | hook.result.current?.unregisterShortcut(['a']); 505 | hook.result.current?.registerShortcut(method, ['a'], 'Test Title', 'Some description'); 506 | }); 507 | 508 | expect(hook.result.current?.shortcuts).toHaveLength(1); 509 | expect(hook.result.current?.shortcuts[0].method).toEqual(method); 510 | expect(hook.result.current?.shortcuts[0].keys).toEqual(['a']); 511 | }); 512 | 513 | it('transform shortcut keys into the appropriately stored keys', () => { 514 | act(() => { 515 | hook.result.current?.registerShortcut( 516 | method, 517 | ['opt+s'], 518 | 'Test Title', 519 | 'Some description', 520 | ); 521 | hook.result.current?.registerShortcut( 522 | method, 523 | ['option+k'], 524 | 'Test Title', 525 | 'Some description', 526 | ); 527 | hook.result.current?.registerShortcut( 528 | method, 529 | ['cmd+x'], 530 | 'Test Title', 531 | 'Some description', 532 | ); 533 | hook.result.current?.registerShortcut( 534 | method, 535 | ['command+y'], 536 | 'Test Title', 537 | 'Some description', 538 | ); 539 | hook.result.current?.registerShortcut( 540 | method, 541 | ['control+s'], 542 | 'Test Title', 543 | 'Some description', 544 | ); 545 | }); 546 | 547 | expect(hook.result.current?.shortcuts).toHaveLength(5); 548 | expect(hook.result.current?.shortcuts[0].keys).toEqual(['alt+s']); 549 | expect(hook.result.current?.shortcuts[1].keys).toEqual(['alt+k']); 550 | expect(hook.result.current?.shortcuts[2].keys).toEqual(['meta+x']); 551 | expect(hook.result.current?.shortcuts[3].keys).toEqual(['meta+y']); 552 | expect(hook.result.current?.shortcuts[4].keys).toEqual(['ctrl+s']); 553 | }); 554 | 555 | it('executes a shortcut when the mouse is pressed', () => { 556 | act(() => { 557 | hook.result.current?.registerShortcut(method, ['a'], '', ''); 558 | }); 559 | 560 | fireEvent.mouseDown(node); 561 | fireEvent.keyDown(node, { key: 'a' }); 562 | expect(method).toHaveBeenCalled(); 563 | }); 564 | 565 | it('executes a shortcut when an element is being dragged', () => { 566 | const DragComponent = () => { 567 | const onDragStart = useCallback((event) => {}, []) as DragEventHandler; 568 | return ( 569 |
Drag this
570 | ) 571 | } 572 | 573 | wrapper = createWrapper({children: }); 574 | hook = renderHook(useShortcut, { wrapper }); 575 | 576 | act(() => { 577 | hook.result.current?.registerShortcut(method, ['z'], '', ''); 578 | }); 579 | 580 | fireEvent.dragStart(screen.getByTestId('drag')); 581 | fireEvent.keyDown(node, { key: 'z' }); 582 | expect(method).toHaveBeenCalled(); 583 | }); 584 | }); 585 | 586 | describe('.registerSequenceShortcut', () => { 587 | it('is a function', () => { 588 | expect(typeof hook.result.current?.registerSequenceShortcut).toEqual('function'); 589 | }); 590 | 591 | it('creates a new listener', () => { 592 | act(() => { 593 | hook.result.current?.registerSequenceShortcut( 594 | method, 595 | ['up', 'up', 'down', 'down', 'enter'], 596 | 'Test Title', 597 | 'Some description', 598 | ); 599 | }); 600 | 601 | expect(hook.result.current?.shortcuts).toHaveLength(1); 602 | }); 603 | 604 | it('can trigger within a custom timeout duration', () => { 605 | wrapper = createWrapper({ sequenceTimeout: 100 }); 606 | hook = renderHook(useShortcut, { wrapper }); 607 | 608 | act(() => { 609 | hook.result.current?.registerSequenceShortcut( 610 | method, 611 | ['x', 'y', 'z'], 612 | 'Test Title', 613 | 'Some description', 614 | ); 615 | }); 616 | 617 | fireEvent.keyDown(node, { key: 'x' }); 618 | fireEvent.keyUp(node, { key: 'x' }); 619 | fireEvent.keyDown(node, { key: 'y' }); 620 | fireEvent.keyUp(node, { key: 'y' }); 621 | jest.advanceTimersByTime(200); 622 | fireEvent.keyDown(node, { key: 'z' }); 623 | fireEvent.keyUp(node, { key: 'z' }); 624 | 625 | expect(method).not.toHaveBeenCalled(); 626 | }); 627 | }); 628 | 629 | describe('.unregisterShortcut', () => { 630 | it('is a function', () => { 631 | expect(typeof hook.result.current?.unregisterShortcut).toEqual('function'); 632 | }); 633 | 634 | it('deletes a listener by passed keys', () => { 635 | act(() => { 636 | hook.result.current?.registerShortcut( 637 | method, 638 | ['ctrl+c', 'k'], 639 | 'Test Title', 640 | 'Some description', 641 | ); 642 | hook.result.current?.unregisterShortcut(['ctrl+c', 'k']); 643 | }); 644 | 645 | expect(hook.result.current?.shortcuts).toHaveLength(0); 646 | }); 647 | 648 | it('lowercases key bindings', () => { 649 | act(() => { 650 | hook.result.current?.registerShortcut( 651 | method, 652 | ['cTrL+C', 'K'], 653 | 'Test Title', 654 | 'Some description', 655 | ); 656 | hook.result.current?.unregisterShortcut(['cTrL+C', 'K']); 657 | }); 658 | expect(hook.result.current?.shortcuts).toHaveLength(0); 659 | }); 660 | 661 | it('deletes a hold listener by passed keys', () => { 662 | act(() => { 663 | hook.result.current?.registerShortcut( 664 | method, 665 | ['ctrl+c', 'k'], 666 | 'Test Title', 667 | 'Some description', 668 | 5000, 669 | ); 670 | hook.result.current?.unregisterShortcut(['ctrl+c', 'k']); 671 | }); 672 | 673 | expect(hook.result.current?.shortcuts).toHaveLength(0); 674 | }); 675 | 676 | it('deletes a sequence listener by passed keys', () => { 677 | const keys = ['up', 'up', 'down', 'down', 'enter']; 678 | act(() => { 679 | hook.result.current?.registerSequenceShortcut( 680 | method, 681 | keys, 682 | 'Test Title', 683 | 'Some description', 684 | ); 685 | hook.result.current?.unregisterShortcut(keys); 686 | }); 687 | 688 | expect(hook.result.current?.shortcuts).toHaveLength(0); 689 | }); 690 | 691 | it.skip('pops the last callback if multiple keys are registered', () => { 692 | const method2 = jest.fn(); 693 | act(() => { 694 | hook.result.current?.registerShortcut(method, ['x'], 'Test', 'Some description'); 695 | hook.result.current?.registerShortcut(method2, ['x'], 'Test', 'Some description'); 696 | }); 697 | 698 | expect(hook.result.current?.shortcuts).toHaveLength(2); 699 | expect(hook.result.current?.shortcuts[0].method).toEqual(method); 700 | expect(hook.result.current?.shortcuts[1].method).toEqual(method2); 701 | 702 | act(() => { 703 | hook.result.current?.unregisterShortcut(['x']); 704 | }); 705 | 706 | expect(hook.result.current?.shortcuts).toHaveLength(1); 707 | expect(hook.result.current?.shortcuts[0].method).toEqual(method); 708 | }); 709 | }); 710 | 711 | describe('.triggerShortcut', () => { 712 | it('is a function', () => { 713 | expect(typeof hook.result.current?.triggerShortcut).toEqual('function'); 714 | }); 715 | 716 | it('triggers a shortcuts callback method', () => { 717 | act(() => { 718 | hook.result.current?.registerShortcut(method, ['x'], 'Test Title', 'Some description'); 719 | hook.result.current?.triggerShortcut('x'); 720 | }); 721 | expect(method).toHaveBeenCalledTimes(1); 722 | }); 723 | 724 | it('does not trigger an invalid or missing shortcut', () => { 725 | act(() => { 726 | hook.result.current?.registerShortcut(method, ['x'], 'Test Title', 'Some description'); 727 | hook.result.current?.triggerShortcut('a'); 728 | }); 729 | 730 | expect(method).toHaveBeenCalledTimes(0); 731 | }); 732 | }); 733 | 734 | describe('.setEnabled', () => { 735 | it('prevents a shortcut from executing when set to false', () => { 736 | act(() => { 737 | hook.result.current?.registerShortcut(method, ['x'], 'Test Title', 'Some description'); 738 | hook.result.current?.setEnabled(false); 739 | }); 740 | 741 | fireEvent.keyDown(node, { key: 'x' }); 742 | expect(method).toHaveBeenCalledTimes(0); 743 | }); 744 | }); 745 | }); 746 | }); 747 | --------------------------------------------------------------------------------