Skip to content

Commit

Permalink
Fixed test for scopable ref feature.
Browse files Browse the repository at this point in the history
  • Loading branch information
JohannesKlauss committed Jul 23, 2020
1 parent 00e62a5 commit f86a086
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
7 changes: 5 additions & 2 deletions src/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ const HotkeysWithRef = ({onPress}: { onPress: () => void }) => {
const ref = useHotkeys<HTMLDivElement>('a', onPress);

return (
<section ref={ref}>
<section ref={ref} tabIndex={0}>
<input type="text" data-testid={'input'}/>
</section>
);
Expand All @@ -186,7 +186,10 @@ test('useHotkeys should only fire when element is focused if a ref is set.', asy
expect(called).toBe(false);

reactAct(() => {
section!.focus()
section!.focus();
});

act(() => {
fireEvent.keyDown(section!, {key: 'a', keyCode: 65});
});

Expand Down
9 changes: 4 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,19 +21,18 @@ export function useHotkeys<T extends Element>(keys: string, callback: KeyHandler
deps = options;
options = undefined;
}

const {enableOnTags, filter} = options || {};

const ref = useRef<T | null>(null);

const memoisedCallback = useCallback((keyboardEvent: KeyboardEvent, hotkeysEvent: HotkeysEvent) => {
if (ref.current === null || document.activeElement === ReactDOM.findDOMNode(ref.current)) {
callback(keyboardEvent, hotkeysEvent);

return true;
}

return false;
}, deps && deps.concat(ref) || [ref]);
}, deps ? [ref, ...deps] : [ref]);

useEffect(() => {
if (options && (options as Options).enableOnTags) {
Expand All @@ -50,7 +49,7 @@ export function useHotkeys<T extends Element>(keys: string, callback: KeyHandler
hotkeys(keys, (options as Options) || {}, memoisedCallback);

return () => hotkeys.unbind(keys, memoisedCallback);
}, [memoisedCallback, options]);
}, [memoisedCallback, options, enableOnTags, filter, keys]);

return ref;
}
}

0 comments on commit f86a086

Please sign in to comment.