Coder Social home page Coder Social logo

shortcuts's Introduction

Shortcuts

Super performant and feature rich shortcuts management library.

This library is just a thin wrapper over ShoSho that provides a VSCode-like interface for managing shortcuts. Definitely check out ShoSho, which provides more features and it may offer a lower-level but maybe more convenient API for your use case.

Install

npm install --save shortcuts

Usage

The following interface is provided:

type Descriptor = {
  handler?: ( event?: Event ): boolean | void,
  shortcut: string
};

type Disposer = {
  (): void
};

type Options = {
  capture?: boolean,
  target?: Window | Document | HTMLElement | SVGElement | MathMLElement,
  shouldHandleEvent?: ( event: Event ) => boolean
};

class Shortcuts {
  constructor ( options: Options );
  get (): Descriptor[];
  add ( descriptor: Descriptor | Descriptor[] ): void;
  register ( descriptor: Descriptor | Descriptor[] ): Disposer;
  remove ( descriptor: Descriptor | Descriptor[] ): void;
  reset (): void;
  trigger ( shortcut: string ): boolean;
  start (): void;
  stop (): void;
}

This is how you'd use the library:

import Shortcuts from 'shortcuts';

// Let's create a new shortcuts manager instance

const shortcuts = new Shortcuts ({
  capture: true, // Handle events during the capturing phase
  target: document, // Listening for events on the document object
  shouldHandleEvent ( event ) {
    return true; // Handle all possible events
  }
});

// Let's register and unregister some shortcuts
// Handlers are filtered by shortcut and executed from bottom to top, stopping at the first handler that returns true

const onCtrlB = () => {};

shortcuts.add ([
  {
    shortcut: 'Ctrl+A',
    handler: () => {
      // Doing something...
      return true; // Returning true if we don't want other handlers for the same shortcut to be called later
    }
  },
  {
    shortcut: 'Ctrl+B',
    handler: onCtrlB
  },
  {
    shortcut: 'CmdOrCtrl+K Shift+B',
    handler: () => {
      // Doing something...
      return true; // Returning true if we don't want other handlers for the same shortcut to be called later
    }
  },
  {
    shortcut: '-Ctrl+A' // Removing all previously-registered handlers for "Ctrl+A"
  }
]);

shortcuts.remove ({ shortcut: 'Ctrl+B', handler: onCtrlB }); // Removing a specific handler bound to this shortcut
shortcuts.remove ({ shortcut: 'Ctrl+A' }); // Removing all handlers bound to this shortcut

// Let's actually start listening for shortcuts

shortcuts.start ();

// Let's stop listening for shortcuts

shortcuts.stop ();

// Let's dispose of all registered shortcuts

shortcuts.reset ();

Thanks

  • Thanks to the people at Koding for providing me the shortcuts package name on NPM! If you're looking for the previous package published under that name you can find it here (v0.x).

License

MIT © Fabio Spampinato

shortcuts's People

Contributors

fabiospampinato avatar knu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

shortcuts's Issues

When binding a shortcut to `/` , it only triggers for the dedicated `/` on the numpad

Thank you for a great library!

I noticed that when I bind a shortcut to /, it will not trigger when I press Shift+7, which is where the forward slash exists in my (Norwegian) keyboard layout. If I press the dedicated / key on the numpad (code NumpadDevide), it works as expected.

As I'm pretty sure Shift+7 isn't consistent for all keyboard layouts, is there any way to bind this shortcut in such a way that it works across the board for the different combinations that produce a /?

Webpack TypeError in Electron

Hey, I've installed and imported the package as described in the README, but I'm getting this error from webpack:

TypeError: shortcuts__WEBPACK_IMPORTED_MODULE_0__.Shortcuts.record is not a function

Here's my usage of the package:

import { Shortcuts } from 'shortcuts';

export function bindKeys(): void {
  try {
    Shortcuts.record((sequence: string[]) => console.log('pressed:', sequence));
  } catch (err) {
    console.error(err);
  }
}

I'm using ts-loader to compile my TS. Here's my webpack config:

const common: Configuration = {
  mode: isDev ? 'development' : 'production',
  resolve: {
    extensions: ['.js', '.ts', '.jsx', '.tsx', '.json'],
  },
  externals: ['fsevents'],
  output: {
    publicPath: './',
    filename: '[name].js',
    assetModuleFilename: 'images/[name][ext]',
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        exclude: /node_modules/,
        loader: 'ts-loader',
      },
      {
        test: /\.s?css$/,
        use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
      },
      {
        test: /\.png$/,
        type: 'asset/resource',
      },
    ],
  },
  stats: 'errors-only',
  watch: isDev,
  devtool: isDev ? 'source-map' : undefined,
};

And here's my tsconfig:

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "ESNext",
    "esModuleInterop": true,
    "moduleResolution": "Node",
    "lib": ["DOM", "ESNext"],
    "resolveJsonModule": true,
    "jsx": "react-jsx",
    "strict": true,
    "allowSyntheticDefaultImports": true,
    "isolatedModules": true,
    "typeRoots": [
      "./node_modules/@types",
      "./src/types"
    ],
  },
  "include": ["src/**/*"],
  "ts-node": {
    "compilerOptions": {
      "module": "CommonJS"
    }
  }
}

I'm not sure this problem is specific to this library so I'll be happy to close it if not, but can you see anything wrong my usage of Shortcuts?

Support disabling sequences when recording

for some reason, when I do shortcuts.record(), very rarely do I only get the singular key I pressed to do the record - I get a sequence of all keys pressed before that one, as well (1 1 1 1 2 instead of 2). I can obviously trim this by removing all but the last result when doing record, but it feels really hacky. How do I make it so record only ever gives me 1 key? Or maybe I can turn off sequence handling to achieve this?

shortcuts fire when focus is in input element

I can't find a way to turn off shortcut handling when various elements in my app have focus. I am using key sequences similar to the gmail "g i" goto inbox. The shortcuts are set globally for the application. They need to stop firing when an element has focus.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.