fix(editor): Register/unregister keybindings on window focus/blur (#13419)

This commit is contained in:
Alex Grozav 2025-02-21 17:02:30 +02:00 committed by GitHub
parent eb27465e57
commit 7a504dc30f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 40 additions and 2 deletions

View file

@ -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);
});
});

View file

@ -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<string, (event: KeyboardEvent) => void>;
@ -142,5 +142,17 @@ export const useKeybindings = (
}
}
useEventListener(document, 'keydown', onKeyDown);
const unregister = ref<ReturnType<typeof useEventListener> | undefined>();
function registerKeybindings() {
unregister.value = useEventListener(document, 'keydown', onKeyDown);
}
function unregisterKeybindings() {
unregister.value?.();
}
registerKeybindings();
useEventListener(window, 'blur', unregisterKeybindings);
useEventListener(window, 'focus', registerKeybindings);
};