Skip to content

Commit

Permalink
components: Add normalizeArrowKey (#33208)
Browse files Browse the repository at this point in the history
* components: Add normalizeArrowKey

* Add tests

* Improve the test
  • Loading branch information
sarayourfriend committed Jul 15, 2021
1 parent 696d97d commit 6aa5d2b
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
28 changes: 28 additions & 0 deletions packages/components/src/utils/keyboard.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* 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
*
* Source:
* https://github.com/downshift-js/downshift/blob/a71005bd879d05d7dcb892d1e0dc5c6ca74e9d39/src/utils.js#L279
*
* @param {import('react').KeyboardEvent} event A keyboardEvent object
*
* @return {string} The keyboard key
*/
export function normalizeArrowKey( event ) {
const { key, keyCode } = event;

if ( arrowKeys.includes( keyCode ) && key.indexOf( 'Arrow' ) !== 0 ) {
return `Arrow${ key }`;
}
return key;
}
34 changes: 34 additions & 0 deletions packages/components/src/utils/test/keyboard.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* WordPress dependencies
*/
import { RIGHT, UP, DOWN, LEFT, SPACE } from '@wordpress/keycodes';

/**
* Internal dependencies
*/
import { normalizeArrowKey } from '../keyboard';

describe( 'normalizeArrowKey', () => {
it.each`
keyCode | key | normalized
${ RIGHT } | ${ 'Right' } | ${ 'ArrowRight' }
${ UP } | ${ 'Up' } | ${ 'ArrowUp' }
${ DOWN } | ${ 'Down' } | ${ 'ArrowDown' }
${ LEFT } | ${ 'Left' } | ${ 'ArrowLeft' }
${ RIGHT } | ${ 'ArrowRight' } | ${ 'ArrowRight' }
${ UP } | ${ 'ArrowUp' } | ${ 'ArrowUp' }
${ DOWN } | ${ 'ArrowDown' } | ${ 'ArrowDown' }
${ LEFT } | ${ 'ArrowLeft' } | ${ 'ArrowLeft' }
${ SPACE } | ${ 'Space' } | ${ 'Space' }
`(
'should return $normalized for $key with keycode $keyCode',
( { keyCode, key, normalized } ) => {
const e = new window.KeyboardEvent( 'keydown', {
key,
keyCode,
} );

expect( normalizeArrowKey( e ) ).toEqual( normalized );
}
);
} );

0 comments on commit 6aa5d2b

Please sign in to comment.