Skip to content

Commit

Permalink
Add an option to enable hotkeys for certain tags
Browse files Browse the repository at this point in the history
  • Loading branch information
gagandeepgill committed Oct 7, 2019
1 parent be71d26 commit 47e8114
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -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]);
}

0 comments on commit 47e8114

Please sign in to comment.