From be71d26eb1f1e1161337b41ddcd67088fd25a1fb Mon Sep 17 00:00:00 2001 From: Gagandeep Gill Date: Mon, 26 Aug 2019 15:59:42 -0400 Subject: [PATCH 1/2] Enable hotkey on INPUT/SELECT/TEXTAREA elements --- src/index.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/index.ts b/src/index.ts index 8d53db23..4707ef94 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,6 +7,10 @@ export function useHotkeys(keys: string, callback: CallbackFn, deps: any[] = []) const memoisedCallback = useCallback(callback, deps); useEffect(() => { + // Enable hotkeys for INPUT/SELECT/TEXTAREA elements + hotkeys.filter = () => { + return true; + }; hotkeys(keys, memoisedCallback); return () => hotkeys.unbind(keys); From 47e81148bc6207d40e06915e8a5b8f47eafff082 Mon Sep 17 00:00:00 2001 From: Gagandeep Gill Date: Mon, 7 Oct 2019 11:14:03 -0400 Subject: [PATCH 2/2] Add an option to enable hotkeys for certain tags --- src/index.ts | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index 4707ef94..dac8d831 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,18 +1,29 @@ -import hotkeys, {HotkeysEvent} from 'hotkeys-js'; -import {useCallback, useEffect} from "react"; +import hotkeys, { HotkeysEvent } from 'hotkeys-js'; +import { useCallback, useEffect } from 'react'; type CallbackFn = (event: KeyboardEvent, handler: HotkeysEvent) => void; +type TagNames = 'INPUT' | 'TEXTAREA' | 'SELECT'; -export function useHotkeys(keys: string, callback: CallbackFn, deps: any[] = []) { +export function useHotkeys( + keys: string, + callback: CallbackFn, + deps: any[] = [], + tagNames?: TagNames[], +) { const memoisedCallback = useCallback(callback, deps); useEffect(() => { // Enable hotkeys for INPUT/SELECT/TEXTAREA elements - hotkeys.filter = () => { - return true; + // https://github.com/jaywcjlove/hotkeys#filter + hotkeys.filter = ({ target, srcElement }) => { + if (tagNames) { + const targetTagName = (target && target.tagName) || (srcElement && srcElement.tagName); + return Boolean(targetTagName && tagNames.includes(targetTagName as TagNames)); + } + return false; }; hotkeys(keys, memoisedCallback); - return () => hotkeys.unbind(keys); + return () => hotkeys.unbind(keys, memoisedCallback); }, [memoisedCallback]); }