import * as React from 'react';
import { Button } from '../../components/controls/buttons';
import Modal from '../../components/controls/Modal';
+import { isInput } from '../../helpers/keyboardEventHelpers';
+import { KeyboardKeys } from '../../helpers/keycodes';
import { translate } from '../../helpers/l10n';
type Shortcuts = Array<{
const [display, setDisplay] = React.useState(false);
React.useEffect(() => {
- const handleKeyPress = (event: KeyboardEvent) => {
- const { tagName } = event.target as HTMLElement;
-
- if (['INPUT', 'SELECT', 'TEXTAREA'].includes(tagName)) {
- return; // Ignore keys when typed in an input
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (isInput(event)) {
+ return true;
}
- if (event.key === '?') {
+ if (event.key === KeyboardKeys.KeyQuestionMark) {
setDisplay(d => !d);
}
};
- window.addEventListener('keypress', handleKeyPress);
+ document.addEventListener('keydown', handleKeyDown);
return () => {
- window.removeEventListener('keypress', handleKeyPress);
+ document.removeEventListener('keydown', handleKeyDown);
};
}, [setDisplay]);
const wrapper = shallowRender();
expect(wrapper).toMatchSnapshot('hidden');
- window.dispatchEvent(new KeyboardEvent('keypress', { key: '?' }));
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: '?' }));
expect(wrapper).toMatchSnapshot('visible');
});
it('should close correctly', () => {
const wrapper = shallowRender();
- window.dispatchEvent(new KeyboardEvent('keypress', { key: '?' }));
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: '?' }));
wrapper.find(Modal).props().onRequestClose!(mockEvent());
expect(wrapper.type()).toBeNull();
});
-it('should ignore other keypresses', () => {
+it('should ignore other keydownes', () => {
const wrapper = shallowRender();
- window.dispatchEvent(new KeyboardEvent('keypress', { key: '!' }));
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: '!' }));
expect(wrapper.type()).toBeNull();
});
it.each([['input'], ['select'], ['textarea']])('should ignore events on a %s', type => {
const wrapper = shallowRender();
- const fakeEvent = new KeyboardEvent('keypress', { key: '!' });
+ const fakeEvent = new KeyboardEvent('keydown', { key: '!' });
Object.defineProperty(fakeEvent, 'target', {
value: document.createElement(type)
});
- window.dispatchEvent(fakeEvent);
+ document.dispatchEvent(fakeEvent);
expect(wrapper.type()).toBeNull();
});
};
registerKeyboardEvents() {
- window.addEventListener('keydown', this.handleKeyboardNavigation);
+ document.addEventListener('keydown', this.handleKeyboardNavigation);
}
unregisterKeyboardEvents() {
- window.removeEventListener('keydown', this.handleKeyboardNavigation);
+ document.removeEventListener('keydown', this.handleKeyboardNavigation);
}
handleSelectTabs = (tabKey: TabKeys) => {