Skip to content

Commit

Permalink
chore: key events as hook
Browse files Browse the repository at this point in the history
Signed-off-by: Frank Flitton <[email protected]>
  • Loading branch information
FrankFlitton committed May 19, 2023
1 parent c250045 commit 9bb8de1
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
23 changes: 23 additions & 0 deletions packages/console/src/components/hooks/test/useKeyListener.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import React from 'react';
import { fireEvent, getByText, render } from '@testing-library/react';
import { useEscapeKey } from '../useKeyListener';

it('calls the callback on pressing the ESC key', () => {
const callbackSpy = jest.fn();
const callback = (_?: KeyboardEvent) => {
callbackSpy();
};

const TestComponent = () => {
useEscapeKey(callback);
return <div>test</div>;
};

render(<TestComponent />);

fireEvent.keyDown(getByText(global.document.body, 'test'), {
key: 'Escape',
});

expect(callbackSpy).toHaveBeenCalled();
});
29 changes: 29 additions & 0 deletions packages/console/src/components/hooks/useKeyListener.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useEffect } from 'react';

/**
* Safely register and unregister a key listener on the document.
* @param onKeyPress
* @param keycode
*/
export const useKeyListener = (
onKeyPress: (e: KeyboardEvent) => void,
keycode = 'Escape',
) => {
useEffect(() => {
const eventCallback = e => {
if (e.key === keycode) {
onKeyPress(e);
}
};
document.addEventListener('keydown', eventCallback);
return () => document.removeEventListener('keydown', eventCallback);
}, []);
};

/**
* Register a key listener for the Escape key.
* @param onKeyPress
*/
export const useEscapeKey = (onKeyPress: (e: KeyboardEvent) => void) => {
useKeyListener(onKeyPress, 'Escape');
};

0 comments on commit 9bb8de1

Please sign in to comment.