diff --git a/packages/console/src/components/hooks/test/useKeyListener.test.tsx b/packages/console/src/components/hooks/test/useKeyListener.test.tsx new file mode 100644 index 000000000..7b52c5daa --- /dev/null +++ b/packages/console/src/components/hooks/test/useKeyListener.test.tsx @@ -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
test
; + }; + + render(); + + fireEvent.keyDown(getByText(global.document.body, 'test'), { + key: 'Escape', + }); + + expect(callbackSpy).toHaveBeenCalled(); +}); diff --git a/packages/console/src/components/hooks/useKeyListener.ts b/packages/console/src/components/hooks/useKeyListener.ts new file mode 100644 index 000000000..0a181b43c --- /dev/null +++ b/packages/console/src/components/hooks/useKeyListener.ts @@ -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'); +};