{"id":20327071,"url":"https://github.com/webneat/ctrl-keys","last_synced_at":"2025-04-11T20:07:30.515Z","repository":{"id":37949074,"uuid":"441784519","full_name":"webNeat/ctrl-keys","owner":"webNeat","description":"A tiny, super fast, typescript library to handle keybindings efficiently.","archived":false,"fork":false,"pushed_at":"2024-06-23T17:41:02.000Z","size":1093,"stargazers_count":30,"open_issues_count":2,"forks_count":6,"subscribers_count":4,"default_branch":"main","last_synced_at":"2024-06-23T18:47:59.656Z","etag":null,"topics":["javascript","keybindings","keyboard-events","keyboard-shortcuts","library","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/webNeat.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-12-26T00:55:46.000Z","updated_at":"2024-06-23T17:40:34.000Z","dependencies_parsed_at":"2024-04-30T23:28:13.562Z","dependency_job_id":"3a8598ec-36c8-4b38-b6cd-08debf23c2b0","html_url":"https://github.com/webNeat/ctrl-keys","commit_stats":null,"previous_names":[],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webNeat%2Fctrl-keys","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webNeat%2Fctrl-keys/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webNeat%2Fctrl-keys/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webNeat%2Fctrl-keys/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/webNeat","download_url":"https://codeload.github.com/webNeat/ctrl-keys/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224684696,"owners_count":17352584,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["javascript","keybindings","keyboard-events","keyboard-shortcuts","library","typescript"],"created_at":"2024-11-14T19:46:28.114Z","updated_at":"2025-04-11T20:07:30.502Z","avatar_url":"https://github.com/webNeat.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ctrl-keys\n\nA tiny, super fast, typescript library to handle keybindings efficiently.\n\n[![Bundle size](https://img.shields.io/bundlephobia/minzip/ctrl-keys?style=flat-square)](https://bundlephobia.com/result?p=ctrl-keys)\n[![Tests Status](https://img.shields.io/github/actions/workflow/status/webneat/ctrl-keys/tests.yml?branch=main\u0026style=flat-square)](https://github.com/webneat/ctrl-keys/actions?query=workflow:\"Tests\")\n[![Coverage Status](https://img.shields.io/coveralls/github/webNeat/ctrl-keys/master?style=flat-square)](https://coveralls.io/github/webNeat/ctrl-keys?branch=master)\n[![Version](https://img.shields.io/npm/v/ctrl-keys?style=flat-square)](https://www.npmjs.com/package/ctrl-keys)\n[![MIT](https://img.shields.io/npm/l/ctrl-keys?style=flat-square)](LICENSE)\n\n# Contents\n- [Features](#features)\n- [Installation](#installation)\n- [Simple usage in 3 steps](#simple-usage-in-3-steps)\n- [Exploring the `ctrl-keys` API](#exploring-the-ctrl-keys-api)\n  - [Defining keybindings](#defining-keybindings)\n  - [Adding new keybindings](#adding-new-keybindings)\n  - [Removing keybindings](#removing-keybindings)\n  - [Disabling and enabling keybindings](#disabling-and-enabling-keybindings)\n  - [Handling keyboard events](#handling-keyboard-events)\n- [Comparaison with other keybindings libraries](#comparaison-with-other-keybindings-libraries)\n- [Changelog](#changelog)\n\n# Features\n- Zero code dependencies (Uses [`just-types`](https://github.com/webNeat/just-types) for types).\n- Small bundle size **\u003c 2kb**.\n- Super fast performance ([see benchmark](#performance-comparaison)).\n- Fully typed, offers autocomplete for keybindings.\n- Handles multi-keys sequences like `ctrl+k ctrl+b` (Inspired by [vscode keybindings](https://code.visualstudio.com/docs/getstarted/keybindings#_keyboard-rules)).\n- Does not add global listeners to the `window`, instead it lets you create multiple handlers and bind them to any DOM elements.\n- Dynamically add, remove, enable, and disable keybindings.\n\n# Installation\n\nYou can install it using `npm` or `yarn`\n```bash\nnpm i ctrl-keys\n// or\nyarn add ctrl-keys\n```\nOr use it directly on modern browsers\n```html\n\u003cscript type=\"module\"\u003e\n  import keys from 'https://unpkg.com/ctrl-keys/dist/index.mjs'\n  // ...\n\u003c/script\u003e\n```\n\n_if you need to use this library on an old browser that doesn't support es modules, please open an issue and I will add a CDN that works for you_\n\n# Simple usage in 3 steps\n\n```ts\nimport keys from 'ctrl-keys'\n\n// 1. Create a keybindings handler\nconst handler = keys()\n\n// 2. Add keybindings\nhandler\n  .add('ctrl+up', () =\u003e {\n    // do something\n  })\n  .add('ctrl+shift+space', 'ctrl+shift+c', () =\u003e {\n    // do something else ...\n  })\n\n// 3. Handle events\nwindow.addEventListener('keydown', handler.handle)\n```\n\nThat's it. Now:\n- Whenever the `ctrl` and `up` keys are pressed at the same time; the first function will be called.\n- Whenever `ctrl`, `shift` and `space` keys are pressed then right after `ctrl`, `shift` and `c` are pressed; the second function will be called.\n\nLet's explore what `ctrl-keys` has to offer in more details in the next section.\n\n# Exploring the `ctrl-keys` API\n\nThe default export of `ctrl-keys` is a function that takes no argument and returns a new keybindings handler:\n\n```ts\nfunction keys(): Handler\n```\n\nThe handler has the following interface\n\n```ts\ninterface HandlerInterface {\n  add(...keys: Keys, fn: Callback): this\n  remove(...keys: Keys, fn: Callback): this\n  enable(...keys: Keys): this\n  disable(...keys: Keys): this\n  handle(event: KeyboardEvent): boolean\n}\n```\n\n- `add` method binds some `keys` to a function `fn` so that whenever the keys are pressed on the keyboard, that function is called.\n- `remove` removes the binding of `keys` to the function `fn`.\n- `disable` can be used to temporary disable some keys (not trigger the functions associated to them) and `enable` is used to enable them again.\n- `handle` handles a `KeyboardEvent` (the event emitted by `keydown` for example).\n\nWe will take a deeper look to each one of these methods bellow. But first, let's see what values can we give as `keys`.\n\n## Defining keybindings\n\nThe methods `add`, `remove`, `enable` and `disable` can take **from 1 to 4** `keys`.\n\nA key is represented by a string in the following format `{modifiers}+{character}` where:\n- `modifiers` is any combination of the modifiers `ctrl`, `alt`, `shift` and `meta` separated by `+`.\n  - Examples: `ctrl+alt`, `shift`, `alt+meta`, `ctrl+alt+meta`.\n- And `character` is one of:\n  - `a`, `b`, ..., `z`\n  - `0`, `1`, ..., `9`\n  - `'`, `\"`, `~`, `!`, `@`, `#`, `$`, `%`, `^`, `\u0026`, `*`, `(`, `)`, `.`, `-`, `_`, `+`, `=`, `[`, `]`, `{`, `}`, `\u003c`, `\u003e`, `,`, `/`, `?`, `;`, `:`, `\\`, `|`\n  - `f1`, `f2`, ..., `f23`\n  - `space`, `enter`, `tab`, `down`, `left`, `right`, `up`, `end`, `capslock`, `numlock`, `home`, `pagedown`, `pageup`, `backspace`, `delete`, `insert`, `escape`\n\nif you are using Typescript, it will offer autocomplete and help you detect typos when writing keys.\n\n![Typescript Autocomplete](https://raw.githubusercontent.com/webNeat/ctrl-keys/main/screenshots/keys-autocomplete.gif)\n\n## Adding new keybindings\n\nThe `add` method lets you add new keybindings to the handler, you do that by specifying the keys that will be pressed and the function to call when they are pressed.\n\n```ts\nconst handler = keys()\n  .add('ctrl+up', fn1)  // add single key binding\n  .add('ctrl+left', 'ctrl+up', 'ctrl+right', fn2)  // add multi keys binding\n  .add('tab', event =\u003e {\n    // You can access the keyboard event inside the callbacks\n  })\n```\n\nYou can add multiple functions to the same key\n```ts\nhandler.add('ctrl+enter', fn1)\nhandler.add('ctrl+enter', fn2)\nhandler.add('ctrl+enter', fn3)\nhandler.add('ctrl+enter', fn2)\n```\nAll added functions will be called (in the same order by which they were added) when handling keyboard events that match the given keys. Adding the same function to the same keys mutiple times will only add it once (the `fn2` in the example above will only be called once when `ctrl+enter` is pressed).\n\n## Removing keybindings\n\nThe `remove` method does the opposite of `add`, it by removing keybindings from the handler.\n\n```ts\nconst handler = keys()\n  .add('ctrl+a', fn1)\n  .add('ctrl+b', fn2)\n  .add('ctrl+a', fn3)\n// 'ctrl+a' calls `fn1` and `fn3`\n// 'ctrl+b' calls `fn2`\n\nhandler.remove('ctrl+b', fn2) // now 'ctrl+b' does nothing\nhandler.remove('ctrl+a', fn1) // now 'ctrl+a' only calls `fn3`\nhandler.remove('ctrl+a', fn1) // does nothing because `fn1` is not bound to 'ctrl+a'\n```\n\n## Disabling and enabling keybindings\nThe `disable` and `enable` methods let you disable/enable keybindings.\n\n```ts\nconst handler = keys()\n  .add('ctrl+a', fn1)\n  .add('ctrl+b', fn2)\n  .add('ctrl+a', fn3)\n// 'ctrl+a' calls `fn1` and `fn3`\n// 'ctrl+b' calls `fn2`\n\nhandler.disable('ctrl+a') // now 'ctrl+a' does nothing\n// ...\nhandler.enable('ctrl+a') // now 'ctrl+a' calls `fn1` and `fn3`\n```\n\n**Example use case**\n```ts\nconst handler = keys()\n  .add('ctrl+a', fn1)\n  .add('ctrl+a', fn2)\n  .add('ctrl+a', fn3)\n\nwindow.addEventListener('keydown', handler.handle)\n```\nThis code will run `fn1`, `fn2` and `fn3` whenever `ctrl+a` is pressed. So if the user is typing into a textarea and presses `ctrl+a` to select all text the functions will be called which may not be the behavior we want. In that case, we can use `disable` to disable all `ctrl+a` bindings when the user starts focuses an input or textarea, and use `enable` to enable them again when the user removes focus from the input.\n\n## Handling keyboard events\n`ctrl-keys` does not add listeners to `window` automatically, instead it lets you decide where and when to handle keyboard events. So after creating a handler and adding keybindings to it, you need to use its `handle` method to actually handle keyboard events\n\n```ts\nwindow.addEventListener('keydown', event =\u003e {\n  handler.handle(event)\n})\n```\n\n**Note** `event.key` is used when matching events against keybindings.\n\n# Comparaison with other keybindings libraries\n\nBefore creating this library, I looked around for existing libraries and found some good ones, but none of them provided everything I wanted.\n\n## Some features comparaison\n\n|  | ctrl-keys | [tinykeys](https://github.com/jamiebuilds/tinykeys) | [hotkeys](https://github.com/jaywcjlove/hotkeys) | [shortcuts](https://github.com/fabiospampinato/shortcuts) |\n| ---                                                  | ---               | ---     | ---    | ---     | \n| Bundle size                                          | 1.23 kB           | 0.72 kB | 2.5 kB | 4.4 kB  |\n| Support for multiple keys sequences                  | ✅ (up to 4 keys) | ✅     | ❌    | ✅      |\n| Dynamically add/remove keybindings                   | ✅                | ❌     | ✅    | ✅      |\n| Gives handler instead of adding listener to `window` | ✅                | ✅     | ❌    | ❌      |\n| Typescript autocomplete for keybindings              | ✅                | ❌     | ❌    | ❌      |\n\n## Performance comparaison\n\n\u003ctable\u003e\u003ctr\u003e\u003cth\u003elibrary\u003c/th\u003e\u003cth\u003eduration\u003c/th\u003e\u003cth\u003ememory usage\u003c/th\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003ectrl-keys\u003c/td\u003e\u003ctd\u003e55 ms\u003c/td\u003e\u003ctd\u003e4711 kb\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003eshortcuts\u003c/td\u003e\u003ctd\u003e58 ms\u003c/td\u003e\u003ctd\u003e4963 kb\u003c/td\u003e\u003c/tr\u003e\u003ctr\u003e\u003ctd\u003etinykeys\u003c/td\u003e\u003ctd\u003e69 ms\u003c/td\u003e\u003ctd\u003e5056 kb\u003c/td\u003e\u003c/tr\u003e\u003c/table\u003e\n\nThe results above are of a benchmark of handling a 3 keys sequence 1000 times. [Click here for details](https://github.com/webNeat/ctrl-keys/tree/main/benchmark)\n\n# Changelog\n\n**1.0.6 (January 31th 2025)**\n\n- Add named export to avoid default export issues with CommonJS.\n- Replaced `parcel` with `tsup`.\n\n**1.0.5 (January 31th 2025)**\n\n- Fix issue of 2 defautl exports.\n\n**1.0.4 (January 30th 2025)**\n\n- Update dev dependencies.\n- Add `module.exports` to enable `require`ing the default export.\n\n**1.0.3 (June 23th 2024)**\n\n- Update dev dependencies.\n- Add `exports` to package.json to fix [issue](https://github.com/webNeat/ctrl-keys/issues/8).\n\n**1.0.2 (May 1st 2024)**\n\n- Update dev dependencies.\n- Remove `just-types` from dependencies and bundle it in the types declaration istead.\n\n**1.0.1 (June 30th 2023)**\n\n- Update dev dependencies and benchmark.\n- Fix Typescript types.\n\n**1.0.0 (March 17th 2022)**\n\n- First release.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebneat%2Fctrl-keys","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwebneat%2Fctrl-keys","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebneat%2Fctrl-keys/lists"}