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 7d77c44
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
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 default 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);

Expand Down

0 comments on commit 7d77c44

Please sign in to comment.