├── .gitattributes ├── .github └── workflows │ ├── ci.yml │ └── publish.yml ├── .gitignore ├── .prettierrc ├── LICENSE ├── jest.config.js ├── package.json ├── readme.md ├── rollup.config.js ├── src ├── index.ts └── useShortcut.ts ├── tests ├── litkey.test.ts └── react.test.tsx ├── tsconfig.json └── yarn.lock /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Litkey tests 2 | 3 | on: 4 | push: 5 | branches: [ master ] 6 | pull_request: 7 | branches: [ master ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | steps: 14 | - uses: actions/checkout@v2 15 | - name: Use Node.js 12.x 16 | uses: actions/setup-node@v1 17 | with: 18 | node-version: 12.x 19 | - run: | 20 | yarn 21 | yarn test 22 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish to NPM 2 | 3 | on: 4 | release: 5 | types: [published] 6 | 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - uses: actions/setup-node@v1 13 | with: 14 | node-version: 12 15 | - run: | 16 | yarn 17 | yarn test 18 | 19 | publish-to-npm: 20 | needs: test 21 | runs-on: ubuntu-latest 22 | steps: 23 | - uses: actions/checkout@v1 24 | - uses: actions/setup-node@v1 25 | with: 26 | node-version: 12 27 | registry-url: https://registry.npmjs.org/ 28 | - run: yarn 29 | - run: yarn build 30 | - run: npm publish --access public 31 | env: 32 | NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "semi": true, 4 | "printWidth": 120, 5 | "tabWidth": 2, 6 | "trailingComma": "none", 7 | "bracketSpacing": true, 8 | "arrowParens": "avoid" 9 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Tobias Herber 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | transform: { 3 | '^.+\\.tsx?$': 'ts-jest', 4 | }, 5 | testRegex: '(/tests/.*|(\\.|/)(test|spec))\\.tsx?$', 6 | moduleFileExtensions: ['ts', 'js', 'tsx'] 7 | }; -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "litkey", 3 | "version": "0.1.2", 4 | "description": "Enjoyable keyboard shortcuts", 5 | "main": "dist/index.js", 6 | "module": "dist/index.es.js", 7 | "repository": "https://github.com/varld/litkey", 8 | "author": "Tobias Herber ", 9 | "license": "MIT", 10 | "files": [ 11 | "dist", 12 | "readme.md", 13 | "LICENSE" 14 | ], 15 | "scripts": { 16 | "test": "jest", 17 | "build": "rollup -c", 18 | "format": "prettier --write 'src/**/*.ts' --write 'tests/**/*.ts' --write 'tests/**/*.tsx'" 19 | }, 20 | "peerDependencies": { 21 | "react": "^16.6.0" 22 | }, 23 | "dependencies": { 24 | "@testing-library/dom": "^7.11.0", 25 | "is-hotkey": "^0.1.6" 26 | }, 27 | "devDependencies": { 28 | "@babel/preset-env": "^7.10.2", 29 | "@rollup/plugin-commonjs": "^13.0.0", 30 | "@rollup/plugin-node-resolve": "^8.0.1", 31 | "@testing-library/jest-dom": "^5.9.0", 32 | "@testing-library/react": "^10.2.1", 33 | "@types/is-hotkey": "^0.1.1", 34 | "@types/jest": "^25.2.3", 35 | "@types/react": "^16.9.35", 36 | "babel": "^6.23.0", 37 | "jest": "^26.0.1", 38 | "prettier": "^2.0.5", 39 | "react": "^16.13.1", 40 | "react-dom": "^16.13.1", 41 | "rollup": "^2.15.0", 42 | "rollup-plugin-babel": "^4.4.0", 43 | "rollup-plugin-peer-deps-external": "^2.2.2", 44 | "rollup-plugin-terser": "^6.1.0", 45 | "rollup-plugin-typescript2": "^0.27.1", 46 | "ts-jest": "^26.1.0", 47 | "typescript": "^3.9.5" 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 |

Litkey

2 | 3 |

🔥 Litkey makes keyboard shortcuts simple and enjoyable.

4 | 5 | ## Install 6 | 7 | ```bash 8 | # Using npm 9 | npm install litkey 10 | 11 | # Using yarn 12 | yarn add litkey 13 | ``` 14 | 15 | ## Usage 16 | 17 | ```typescript 18 | import litkey from 'litkey'; 19 | 20 | // Add a global keyboard shortcut 21 | litkey('mod+k', () => { 22 | // do something 23 | }); 24 | 25 | // Add a keyboard shortcut to a specific element 26 | litkey('mod+k', () => { 27 | // do something 28 | }, myElement); 29 | ``` 30 | 31 | ## Usage with React 32 | 33 | ```tsx 34 | import { useShortcut } from 'litkey'; 35 | 36 | let Component = () => { 37 | let [clicked, setClicked] = useState(false); 38 | 39 | useShortcut('mod+a', () => { 40 | setClicked(true); 41 | }); 42 | 43 | // You can also specify hook dependencies which will 44 | // get passed on to the underlying useEffect 45 | useShortcut('mod+k', () => { 46 | setClicked(true); 47 | }, [/* react hook dependency list */]); 48 | 49 | // Using the fourth parameter, you can specify a 50 | // specific DOM element, in which the keyboard 51 | // shortcut will be fired 52 | useShortcut('mod+k', () => { 53 | setClicked(true); 54 | }, [], myElement); 55 | 56 | return ( 57 |

{ clicked ? 'clicked' : 'not clicked' }

58 | ); 59 | }; 60 | ``` 61 | 62 | ## API 63 | 64 | ### `litkey(shortcut, handler, [context])` 65 | 66 | The `litkey` function is the default export of litkey. 67 | 68 | #### `shortcut: string | string[]` 69 | 70 | `shortcut` is a `string` or an `array of strings`, which specify the key combinations which will fire the callback. 71 | 72 | #### `handler: (event: KeyboardEvent) => any` 73 | 74 | The `handler` is a callback function which will be called if the keyboard shortcut is pressed. 75 | It receives the `KeyboardEvent` as its first parameter. 76 | 77 | #### `context?: HTMLElement` 78 | 79 | The context is optional and can be used to specify the `HTMLElement`, in which litkey will listen for keyboard shortcuts. 80 | 81 | ### `useShortcut(shortcut, handler, [dependencies, [context]])` 82 | 83 | #### `shortcut: string | string[]` 84 | 85 | `shortcut` is a `string` or an `array of strings`, which specify the key combinations which will fire the callback. 86 | 87 | #### `handler: (event: KeyboardEvent) => any` 88 | 89 | The `handler` is a callback function which will be called if the keyboard shortcut is pressed. 90 | It receives the `KeyboardEvent` as its first parameter. 91 | 92 | #### `dependencies: any[]` 93 | 94 | `dependencies` is an optional array, which will be passed on directly to `useEffect` to serve as React hook dependencies. 95 | 96 | #### `context?: HTMLElement` 97 | 98 | `context` is optional and can be used to specify the `HTMLElement`, in which litkey will listen for keyboard shortcuts. 99 | 100 | ## License 101 | 102 | MIT © [Tobias Herber](https://herber.space) 103 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import babel from 'rollup-plugin-babel'; 2 | import commonjs from '@rollup/plugin-commonjs'; 3 | import external from 'rollup-plugin-peer-deps-external'; 4 | import resolve from '@rollup/plugin-node-resolve'; 5 | import { terser } from 'rollup-plugin-terser'; 6 | import typescript from 'rollup-plugin-typescript2'; 7 | 8 | import pkg from './package.json'; 9 | 10 | export default { 11 | input: 'src/index.ts', 12 | output: [ 13 | { 14 | file: pkg.main, 15 | format: 'cjs', 16 | sourcemap: true, 17 | }, 18 | { 19 | file: pkg.module, 20 | format: 'es', 21 | sourcemap: true, 22 | }, 23 | ], 24 | plugins: [ 25 | typescript(), 26 | external({ 27 | includeDependencies: true, 28 | }), 29 | resolve(), 30 | babel({ 31 | presets: [ 32 | '@babel/preset-env' 33 | ], 34 | exclude: 'node_modules/**', 35 | runtimeHelpers: true 36 | }), 37 | commonjs(), 38 | terser(), 39 | ], 40 | }; -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { parseHotkey, compareHotkey, HotKey } from 'is-hotkey'; 2 | 3 | let addShortcut = ( 4 | keys: string | string[], 5 | handler: (event: KeyboardEvent) => any, 6 | context: Element = document.body 7 | ) => { 8 | let hotkeys: HotKey[] = []; 9 | 10 | if (Array.isArray(keys)) { 11 | for (let key of keys) { 12 | hotkeys.push(parseHotkey(key, { byKey: true })); 13 | } 14 | } else { 15 | hotkeys.push(parseHotkey(keys, { byKey: true })); 16 | } 17 | 18 | let internalHandler = (event: KeyboardEvent) => { 19 | let passed = false; 20 | 21 | for (let hotkey of hotkeys) { 22 | passed = compareHotkey(hotkey, event); 23 | 24 | if (passed) break; 25 | } 26 | 27 | if (passed) { 28 | handler(event); 29 | } 30 | }; 31 | 32 | context.addEventListener('keydown', internalHandler); 33 | 34 | return () => { 35 | context.removeEventListener('keydown', internalHandler); 36 | }; 37 | }; 38 | 39 | export default addShortcut; 40 | export * from './useShortcut'; 41 | -------------------------------------------------------------------------------- /src/useShortcut.ts: -------------------------------------------------------------------------------- 1 | import { useEffect } from 'react'; 2 | import addShortcut from './index'; 3 | 4 | export let useShortcut = ( 5 | keys: string | string[], 6 | handler: (event: KeyboardEvent) => any, 7 | dependencies: any[] = [], 8 | context?: Element 9 | ) => { 10 | useEffect(() => { 11 | return addShortcut(keys, handler, context); 12 | }, [keys, handler, context, ...dependencies]); 13 | }; 14 | -------------------------------------------------------------------------------- /tests/litkey.test.ts: -------------------------------------------------------------------------------- 1 | import { waitFor, fireEvent } from '@testing-library/dom'; 2 | import '@testing-library/jest-dom/extend-expect'; 3 | import addShortcut from '../src'; 4 | 5 | let callWhenDone = (calls: number, cb: Function) => { 6 | let currentCalls = 0; 7 | 8 | return () => { 9 | currentCalls++; 10 | 11 | if (currentCalls >= calls) { 12 | cb(); 13 | } 14 | }; 15 | }; 16 | 17 | describe('usage with dom', () => { 18 | test('fires event', cb => { 19 | expect.assertions(1); 20 | let div = document.createElement('div'); 21 | 22 | addShortcut( 23 | 'mod+a', 24 | () => { 25 | expect(true).toBeTruthy(); 26 | cb(); 27 | }, 28 | div 29 | ); 30 | 31 | fireEvent.keyDown(div, { key: 'a', ctrlKey: true }); 32 | }); 33 | 34 | test('uses body ad default context', cb => { 35 | expect.assertions(1); 36 | 37 | addShortcut('shift+b', () => { 38 | expect(true).toBeTruthy(); 39 | cb(); 40 | }); 41 | 42 | fireEvent.keyDown(document.body, { key: 'b', shiftKey: true }); 43 | }); 44 | 45 | test('accepts array of shortcuts', cb => { 46 | expect.assertions(3); 47 | 48 | let div = document.createElement('div'); 49 | let done = callWhenDone(3, cb); 50 | 51 | addShortcut( 52 | ['shift+b', 'shift+c', 'mod+9'], 53 | () => { 54 | expect(true).toBeTruthy(); 55 | done(); 56 | }, 57 | div 58 | ); 59 | 60 | fireEvent.keyDown(div, { key: 'b', shiftKey: true }); 61 | fireEvent.keyDown(div, { key: 'c', shiftKey: true }); 62 | fireEvent.keyDown(div, { key: '9', ctrlKey: true }); 63 | }); 64 | 65 | test('unregisters events', cb => { 66 | expect.assertions(1); 67 | 68 | let div = document.createElement('div'); 69 | 70 | let unregister = addShortcut( 71 | ['shift+b'], 72 | () => { 73 | expect(true).toBeTruthy(); 74 | unregister(); 75 | fireEvent.keyDown(div, { key: 'b', shiftKey: true }); 76 | }, 77 | div 78 | ); 79 | 80 | fireEvent.keyDown(div, { key: 'b', shiftKey: true }); 81 | 82 | setTimeout(cb, 200); 83 | }); 84 | 85 | test('does not call function if shortcut is not pressed', cb => { 86 | expect.assertions(1); 87 | 88 | let div = document.createElement('div'); 89 | 90 | addShortcut( 91 | ['shift+b'], 92 | () => { 93 | expect(false).toBeTruthy(); 94 | }, 95 | div 96 | ); 97 | 98 | fireEvent.keyDown(div, { key: '9', ctrlKey: true }); 99 | expect(true).toBeTruthy(); 100 | 101 | setTimeout(cb, 200); 102 | }); 103 | }); 104 | -------------------------------------------------------------------------------- /tests/react.test.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import { render, waitFor, screen, fireEvent } from '@testing-library/react'; 3 | import '@testing-library/jest-dom/extend-expect'; 4 | import { useShortcut } from '../src'; 5 | 6 | describe('usage with react', () => { 7 | test('fires event', async () => { 8 | let div = document.createElement('div'); 9 | 10 | let Component = () => { 11 | let [clicked, setClicked] = useState(false); 12 | 13 | useShortcut('mod+a', () => setClicked(true), [], div); 14 | 15 | return

clicked: {'' + clicked}

; 16 | }; 17 | 18 | render(); 19 | await waitFor(() => screen.getByText('clicked: false')); 20 | 21 | fireEvent.keyDown(div, { key: 'a', ctrlKey: true }); 22 | 23 | await waitFor(() => screen.getByText('clicked: true')); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "ES2015", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "esModuleInterop": true, 9 | "target": "es6", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./src", 13 | "incremental": true, 14 | "jsx": "react" 15 | }, 16 | "exclude": ["node_modules", "./dist", "**/*.test.ts", "**/*.test.tsx"] 17 | } --------------------------------------------------------------------------------