Giter Club home page Giter Club logo

react-use-hotkeys's People

Contributors

codingdive avatar dependabot[bot] avatar github-actions[bot] avatar reecelucas 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  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

react-use-hotkeys's Issues

Incompatibility with eslint react-hooks/exhaustive-deps additionalHooks

Hi, love the library. Not sure if it's still being maintained but for posterity:

The official react-hooks/exhaustive-deps eslint rule allows you to whitelist custom hooks to automatically have their dependency lists scanned. See https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/README.md#advanced-configuration for an example.

However this only works (for me, at least) if the dependency list comes second in the argument list, matching useEffect(callback, deps).

useHotkeys does not work with this rule. As a workaround I've swapped the order of arguments:

import { useHotkeys } from "react-hotkeys-hook";

type useHotkeysParams = Parameters<typeof useHotkeys>;

// rearranges args so it matches useEffect's signature, and the react-hooks/exhaustive-deps rule picks it up
export function useHotkeysSafe(
  callback: useHotkeysParams[1],
  dependencies: useHotkeysParams[3],
  keys: useHotkeysParams[0],
  options?: useHotkeysParams[2]
) {
  return useHotkeys(keys, callback, options, dependencies);
}

And added this to my .eslintrc.json:

{
  // ...
  "rules": {
    "react-hooks/exhaustive-deps": [
      "warn",
      {
        "additionalHooks": "useHotkeysSafe|useSomeOtherCustomHook"
      }
    ]
  }
}

And we use useHotkeysSafe everywhere. This gives us a warning if our callback uses variables that aren't in the dependency array.

Perhaps the library could allow another overload of useHotkeys supporting this use case. The typings could also be improved to separate the different signatures, rather than allowing a union of each parameter at each argument:

export function useHotkeys<T extends HTMLElement>(keys: Keys, callback: HotkeyCallback, options?: Options, dependencies?: DependencyList): MutableRefObject<RefType<T>>;
export function useHotkeys<T extends HTMLElement>(keys: Keys, callback: HotkeyCallback, dependencies?: DependencyList, options?: Options): MutableRefObject<RefType<T>>;
export function useHotkeys<T extends HTMLElement>(callback: HotkeyCallback, dependencies?: DependencyList, keys: Keys, options?: Options): MutableRefObject<RefType<T>>;

Development instructions

Hey @reecelucas . I've been hunting around for a good, flexible and simple hotkeys hook. The more popular ones that I've found have all had a shortcoming in one way or another, but yours looks appropriately simple. I forked the repo because I wanted to play around with a few custom options, including adding scoping. Installing from Github works as expected, but when I try to yarn install && yarn build && yarn link, I'm getting invariant Violation: Invalid hook call errors with the linked lib. I haven't changed anything ๐Ÿคทโ€โ™‚ May be something on my system, but it might be good to add developer instructions to README anyway. Any idea about the error?

Listen to "+" being pressed not possible

I tried to listen to the plus symbol being pressed. On the numpad it works fine, but the non-numpad plus was not picked up. I tried using: useHotkeys('plus, "+", +', () =>...);.
Any ideas?

What is the correct way to do this?

In this case, if I do meta shift k, the menu opens, and the alert is not triggered.

Is this an incorrect approach?

useHotkeys("Meta+k", () => setShowCommandPalette(true));
useHotkeys("Meta+Shift+k", () => alert("link"));

Dependency on `shim-keyboard-event-key` creates SSR error

I'm using this package on a Gatsby site, which uses server-side rendering (SSR). Consequently, some issues can arise when window is reference as window is undefined on the server. I believe the same is true for self.

The issues comes from shim-keyboard-event-key/index.js:4:1:

(function() {
  "use strict"

  if (!self.document) return

ReferenceError: self is not defined


Is there a workaround for this? Since I'm utilizing the useHotKeys hook, I'm not sure there's a way to conditionally call this.

Not working with "?"

I tried to attach a hotkey on "?" using

useHotkeys("?",() => console.log("ok"))

also tried with {capture:true} but the callback isn't fired

Any idea ?

UPDATE

Can be fixed by listening on "*" and with custom check. But I don't like this approach

keys as string[] not allowed in typescript

Hi,

I'm trying to set multiple key combinations in my project, what is completely typed.
As in your example below it should be possible.

// Multiple key combinations mapped to the same callback
useHotkeys(['Control+z', 'Meta+z'], () => {
console.log('Some action');
});

But with typing it is not as you can see in useHotkeys.d.ts in line 15/16/17. (keys: string, callback: .... )
export declare function useHotkeys<T extends Element>(keys: string, callback: KeyHandler, options?: Options): React.MutableRefObject<T | null>;
I guess it should be: ...(keys: string | string[], callback: ...)

Or should I extend useHotkeys.d.ts with my own rules?

Greetings
Markus

Disable hotkeys in input fields

There should be a way to disable hotkeys when writing in input fields

Suggestion: event.currentTarget might contain the dom element

Cannot capture event

Hello,

thank you for this hook, i find it really useful.

howerver, it is not possible to add event listener on the capturing phase see https://javascript.info/bubbling-and-capturing

it would be great fi it was possible to change the signature of the hook to this:

const useHotkeys = (
  hotkeys: string | string[],
  callback: (event: KeyboardEvent) => void,
  options?: boolean | AddEventListenerOptions
) => {
    
    // business logic ...

    window.addEventListener('keydown', onKeydown, options);

    return () => {
      window.removeEventListener('keydown', onKeydown, options);
    };
}

react-use-hotkeys v1.3.2 stopped working in Safari

First: Thanks for this awesome hook!

After updating the version from 1.3.1 to 1.3.2 we noticed that the useHotkeys hook stopped working in Safari (tested with 15.4).

Cause there is a client side dependency involved, I need to use nextjs (v12.1.6) dynamic imports like this:

const DynamicHotkeys = dynamic(() => import("./PlayerHotkeys"), { ssr: false, });

The PlayerHotkeys component looks as simple as that:

  const PlayerHotkeys = ({
      requestToggleMute
    }: Props) => {

    useHotkeys("m", () => {
        requestToggleMute();
    });

   // more hotkeys below
  
    return <></>;
  };

I wasn't able to see any logs in the console. The component just returned nothing (tried to return a simple string in the fragment, and I also tried to do some logging before and after the useHotkeys hooks, but also no output). As soon as I downgraded to v1.3.1 everything worked like before. Maybe it's due to an dependency update? Any idea? Just wanted to address the issue.

Thanks for your great work!

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.