From 7a504dc30fcf0c7641528ed469835811f82bb098 Mon Sep 17 00:00:00 2001 From: Alex Grozav Date: Fri, 21 Feb 2025 17:02:30 +0200 Subject: [PATCH] fix(editor): Register/unregister keybindings on window focus/blur (#13419) --- .../src/composables/useKeybindings.test.ts | 26 +++++++++++++++++++ .../src/composables/useKeybindings.ts | 16 ++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/packages/editor-ui/src/composables/useKeybindings.test.ts b/packages/editor-ui/src/composables/useKeybindings.test.ts index 9a3965412c..15acb1d9ac 100644 --- a/packages/editor-ui/src/composables/useKeybindings.test.ts +++ b/packages/editor-ui/src/composables/useKeybindings.test.ts @@ -163,4 +163,30 @@ describe('useKeybindings', () => { document.dispatchEvent(event); expect(handler).toHaveBeenCalled(); }); + + it('should not call handler when window is blurred, until it is focused back', async () => { + const handler = vi.fn(); + const keymap = ref({ a: handler }); + + useKeybindings(keymap); + + const event = new KeyboardEvent('keydown', { key: 'a' }); + document.dispatchEvent(event); + + expect(handler).toHaveBeenCalled(); + + const blurEvent = new Event('blur'); + window.dispatchEvent(blurEvent); + + document.dispatchEvent(event); + + expect(handler).toHaveBeenCalledTimes(1); + + const focusEvent = new Event('focus'); + window.dispatchEvent(focusEvent); + + document.dispatchEvent(event); + + expect(handler).toHaveBeenCalledTimes(2); + }); }); diff --git a/packages/editor-ui/src/composables/useKeybindings.ts b/packages/editor-ui/src/composables/useKeybindings.ts index 3de381fd6c..11c8dc8ff7 100644 --- a/packages/editor-ui/src/composables/useKeybindings.ts +++ b/packages/editor-ui/src/composables/useKeybindings.ts @@ -1,7 +1,7 @@ import { useActiveElement, useEventListener } from '@vueuse/core'; import { useDeviceSupport } from '@n8n/composables/useDeviceSupport'; import type { MaybeRef, Ref } from 'vue'; -import { computed, unref } from 'vue'; +import { computed, ref, unref } from 'vue'; type KeyMap = Record void>; @@ -142,5 +142,17 @@ export const useKeybindings = ( } } - useEventListener(document, 'keydown', onKeyDown); + const unregister = ref | undefined>(); + + function registerKeybindings() { + unregister.value = useEventListener(document, 'keydown', onKeyDown); + } + + function unregisterKeybindings() { + unregister.value?.(); + } + + registerKeybindings(); + useEventListener(window, 'blur', unregisterKeybindings); + useEventListener(window, 'focus', registerKeybindings); };