diff --git a/packages/components/src/utils/keyboard.js b/packages/components/src/utils/keyboard.js index 2ca69b1ac4e21b..977b87ada21004 100644 --- a/packages/components/src/utils/keyboard.js +++ b/packages/components/src/utils/keyboard.js @@ -1,3 +1,13 @@ +/** + * WordPress dependencies + */ +import { RIGHT, UP, DOWN, LEFT } from '@wordpress/keycodes'; + +/** + * @type {number[]} + */ +const arrowKeys = [ RIGHT, UP, DOWN, LEFT ]; + /** * Normalizes the 'key' property of a KeyboardEvent in IE/Edge * @@ -11,7 +21,7 @@ export function normalizeArrowKey( event ) { const { key, keyCode } = event; - if ( keyCode >= 37 && keyCode <= 40 && key.indexOf( 'Arrow' ) !== 0 ) { + if ( arrowKeys.includes( keyCode ) && key.indexOf( 'Arrow' ) !== 0 ) { return `Arrow${ key }`; } return key; diff --git a/packages/components/src/utils/test/keyboard.js b/packages/components/src/utils/test/keyboard.js new file mode 100644 index 00000000000000..1f7e4721449afd --- /dev/null +++ b/packages/components/src/utils/test/keyboard.js @@ -0,0 +1,29 @@ +/** + * WordPress dependencies + */ +import { RIGHT, SPACE } from '@wordpress/keycodes'; + +/** + * Internal dependencies + */ +import { normalizeArrowKey } from '../keyboard'; + +describe( 'normalizeArrowKey', () => { + it( 'should return the Arrow(Key) version for the presed key', () => { + const e = new window.KeyboardEvent( 'keydown', { + key: 'Right', + keyCode: RIGHT, + } ); + + expect( normalizeArrowKey( e ) ).toEqual( 'ArrowRight' ); + } ); + + it( 'should return the non-normalized version if given a non arrow key event', () => { + const e = new window.KeyboardEvent( 'keydown', { + key: 'Space', + keyCode: SPACE, + } ); + + expect( normalizeArrowKey( e ) ).toEqual( 'Space' ); + } ); +} );