Skip to content

Commit

Permalink
Merge pull request #488 from ggascoigne/ggp/add-enable
Browse files Browse the repository at this point in the history
Add enable option
  • Loading branch information
JohannesKlauss authored Mar 6, 2021
2 parents 91d8698 + 2a15ede commit 0edab0b
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 2 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ to do this anymore by yourself.
to listen to the `+` character, you can set `splitKey` to i.e. `-` and listen for `ctrl-+`
- `keyup: boolean` Determine if you want to listen on the keyup event
- `keydown: boolean` Determine if want to listen on the keydown event
- `enabled: boolean` is used to prevent installation of the hotkey when set to false (default value: `true`)
- `deps: any[] = []`: The dependency array that gets appended to the memoisation of the callback. Here you define the inner
dependencies of your callback. If for example your callback actions depend on a referentially unstable value or a value
that will change over time, you should add this value to your deps array. Since most of the time your callback won't
Expand Down
9 changes: 7 additions & 2 deletions src/useHotkeys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const isKeyboardEventTriggeredByInput = (ev: KeyboardEvent) => {
};

export type Options = {
enabled?: boolean;
filter?: typeof hotkeys.filter;
filterPreventDefault?: boolean;
enableOnTags?: AvailableTags[];
Expand All @@ -36,7 +37,7 @@ export function useHotkeys<T extends Element>(keys: string, callback: KeyHandler
options = undefined;
}

const { enableOnTags, filter, keyup, keydown, filterPreventDefault = true } = options || {};
const { enableOnTags, filter, keyup, keydown, filterPreventDefault = true, enabled = true } = options as Options || {};
const ref = useRef<T | null>(null);

const memoisedCallback = useCallback((keyboardEvent: KeyboardEvent, hotkeysEvent: HotkeysEvent) => {
Expand All @@ -57,6 +58,10 @@ export function useHotkeys<T extends Element>(keys: string, callback: KeyHandler
}, deps ? [ref, enableOnTags, filter, ...deps] : [ref, enableOnTags, filter]);

useEffect(() => {
if(!enabled) {
return
}

if (keyup && keydown !== true) {
(options as Options).keydown = false;
}
Expand All @@ -67,4 +72,4 @@ export function useHotkeys<T extends Element>(keys: string, callback: KeyHandler
}, [memoisedCallback, options, keys]);

return ref;
}
}

0 comments on commit 0edab0b

Please sign in to comment.