npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-keybinds

v1.0.8

Published

A lightweight library to manage keyboard shortcuts for your React application.

Downloads

72

Readme

image

react-keybinds

A lightweight library to manage keyboard shortcuts for your React application

Install

Using npm

npm i react-keybinds

Using Yarn

yarn add react-keybinds

Using pnpm

pnpm add react-keybinds

Usage

You can take a look at the example

1. Configuring the KeyBind provider

import {KeyBindProvider} from 'react-keybinds';

const App = () => {
    return (
        <KeyBindProvider>
            hello world
        </KeyBindProvider>
    );
};

It is recommended that you place the provider at the beginning of the component tree.

By default, the provider will have a debounce on key presses events of 1000ms, you can change this value by passing the debounce prop to the provider

const App = () => {
  return (
          <KeyBindProvider debounce={500}>
            hello world
          </KeyBindProvider>
  );
}

2. Global shortcuts

You can register commands globally

import {KeyBindProvider, ShortcutType} from 'react-keybinds';

const GLOBAL_COMMANDS: ShortcutType[] = [
    {
        keys: {
            Mac: ['Control', 'Shift', 'P'],
            Windows: ['Control', 'Shift', 'P'],
        },
        label: 'Test command',
        callback: () => {
            alert('Hello world');
        },
    },
];

const App = () => {
    return (
        <KeyBindProvider shortcuts={GLOBAL_COMMANDS}>
            hello world
        </KeyBindProvider>
    );
};

3. Register shortcuts

You can register a command in a specific part of your application. This is useful when we want to execute logic from a handler that exists in a specific component.

import {KeyBindProvider, useKeyBind} from 'react-keybinds';

const RegisterShortcutButton = () => {
    const {registerShortcut} = useKeyBind();

    const handleClickRegister = () => {
        registerShortcut({
            keys: {
                Mac: ['Shift', '*', '_'],
            },
            label: 'This is a keyboard shortcut',
            callback: () => {
                alert('Hello world');
            },
        });
    };

    return (
        <div>
            <button onClick={handleClickRegister}>Register shortcut</button>
        </div>
    );
};

const App = () => {
    return (
        <KeyBindProvider>
            <RegisterShortcutButton/>
        </KeyBindProvider>
    );
};

You can also register a shortcut when a component is mounted. Like this:

When you use the useRegisterShortcut hook it is necessary to use the useMemo hook

import * as React from 'react';
import {useMemo, useState} from 'react';
import {ShortcutType, useKeyBind, useRegisterShortcut} from 'react-keybinds';
import inspire from '../data/inspire';

const RegisterOnMount = () => {
    const [text, setText] = useState(inspire[0]);

    const {getKeysByPlatform} = useKeyBind();

    const shortcut: ShortcutType = useMemo(
        () => ({
            keys: {
                Windows: ['Control', 'Enter'],
            },
            label: 'Inspired command',
            callback: () => {
                const randomIndex = Math.floor(Math.random() * inspire.length);
                setText(inspire[randomIndex]);
            },
        }),
        []
    );

    useRegisterShortcut(shortcut); // register on mount

    const keysForInspire = getKeysByPlatform(shortcut);

    return (
        <div>
            <h1>Inspire command</h1>
            <p>
                Press: <strong>{keysForInspire?.keys?.join(' + ')}</strong>{' '}
            </p>
            <blockquote>{`"${text}"`}</blockquote>
        </div>
    );
};

export default RegisterOnMount;

4. List registered shortcuts

You can list the registered shortcuts using the useKeyBind hook

import {KeyBindProvider, useKeyBind} from 'react-keybinds';

const ShowShortcuts = () => {
    const {shortcuts} = useKeyBind();
    const shortcutsList = shortcuts?.map((shortcut, index) => {
        return (
            <div key={index}>
                <span>{shortcut.label}</span>
                <ul>
                    {Object.entries(shortcut.keys).map(([key, values], i) => (
                        <li key={`${key}-${i}`}>
                            {key}: <strong>{values.join(' + ')}</strong>
                        </li>
                    ))}
                </ul>
            </div>
        );
    });
    return (
        <div>
            <h1>Registered Shortcuts</h1>
            {shortcutsList}
        </div>
    );
};
const App = () => {
    return (
        <KeyBindProvider>
            <ShowShortcuts/>
        </KeyBindProvider>
    );
};

Notes

  • If a user is using a platform for which you did not specify the keys, it will default to the keys of a platform that you have configured. If you want to see which platform the keys will be taken from, you can use the getKeysByPlatform method.
const shortcut: ShortcutType = useMemo(
    () => ({
        keys: {
            Windows: ['Control', 'Enter'],
        },
        label: 'Inspired command',
        callback: () => {
        },
    }),
    []
);

const informationForInspire = getKeysByPlatform(shortcut); // {platform: 'Windows', keys: ['Control', 'Enter']}
  • If you want to have more information about the current platform, you can use the usePlatform hook
import { usePlatform } from 'react-keybinds';

const App = () => {
    const platform = usePlatform();
    return (
        <div>
            <h1>Current platform: {platform.currentPlatform()}</h1>
            <h1>Is Windows: {platform.isWindows()}</h1>
        </div>
    );
};
  • If you want to take a look at a list of all the keys for different platforms, you can use the following link