diff --git a/src/isHotkeyPressed.ts b/src/isHotkeyPressed.ts index 00b312e5..97d57053 100644 --- a/src/isHotkeyPressed.ts +++ b/src/isHotkeyPressed.ts @@ -56,4 +56,10 @@ export function removeFromCurrentlyPressedKeys(key: string): void { removeFromCurrentlyPressedKeys(mapKey(e.code)) }) } + + if (typeof window !== 'undefined') { + window.addEventListener('blur', () => { + currentlyPressedKeys.clear() + }) + } })() diff --git a/src/useHotkeys.ts b/src/useHotkeys.ts index 3c6a014b..8915ac77 100644 --- a/src/useHotkeys.ts +++ b/src/useHotkeys.ts @@ -45,7 +45,7 @@ export default function useHotkeys( return } - const listener = (e: KeyboardEvent) => { + const listener = (e: KeyboardEvent, isKeyUp: boolean = false) => { if (isKeyboardEventTriggeredByInput(e) && !isHotkeyEnabledOnTag(e, memoisedOptions?.enableOnFormTags)) { return } @@ -77,7 +77,9 @@ export default function useHotkeys( // Execute the user callback for that hotkey cb(e, hotkey) - hasTriggeredRef.current = true + if (!isKeyUp) { + hasTriggeredRef.current = true + } } }) } @@ -106,10 +108,8 @@ export default function useHotkeys( hasTriggeredRef.current = false if (memoisedOptions?.keyup) { - listener(event) + listener(event, true) } - - hasTriggeredRef.current = false } // @ts-ignore diff --git a/tests/isHotkeyPressed.test.tsx b/tests/isHotkeyPressed.test.tsx index ff3fe3a2..acc5dabf 100644 --- a/tests/isHotkeyPressed.test.tsx +++ b/tests/isHotkeyPressed.test.tsx @@ -1,13 +1,6 @@ import userEvent from '@testing-library/user-event' import { isHotkeyPressed } from '../src/isHotkeyPressed' -beforeEach(() => { - window.document.dispatchEvent(new Event("DOMContentLoaded", { - bubbles: true, - cancelable: true - })) -}) - test('should return true if hotkey is currently pressed down', async () => { const user = userEvent.setup() @@ -110,3 +103,18 @@ test.skip('should respect the splitKey option', async () => { expect(isHotkeyPressed('ba,', 'a')).toBe(false) expect(isHotkeyPressed(['b', ','])).toBe(false) }) + +test('Should clear pressed hotkeys when window blurs', async () => { + const user = userEvent.setup() + + await user.keyboard('{Meta>}') + + expect(isHotkeyPressed('meta')).toBe(true) + + window.document.dispatchEvent(new Event("blur", { + bubbles: true, + cancelable: true + })) + + expect(isHotkeyPressed('meta')).toBe(false) +}) diff --git a/tests/useRecordHotkeys.spec.tsx b/tests/useRecordHotkeys.test.tsx similarity index 100% rename from tests/useRecordHotkeys.spec.tsx rename to tests/useRecordHotkeys.test.tsx