From dfea518e8cb5bd8b8c788e5a0d5a3bb8ccfb10b6 Mon Sep 17 00:00:00 2001 From: Flavio Li Volsi Date: Sun, 22 Oct 2017 19:14:59 +0200 Subject: [PATCH] Adding `code` property to `SyntheticKeyboardEvent` with test --- .../src/events/SyntheticKeyboardEvent.js | 17 +++++++++++++++++ .../__tests__/SyntheticKeyboardEvent-test.js | 16 ++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/packages/react-dom/src/events/SyntheticKeyboardEvent.js b/packages/react-dom/src/events/SyntheticKeyboardEvent.js index 6514dc809b682..d1df8e0098950 100644 --- a/packages/react-dom/src/events/SyntheticKeyboardEvent.js +++ b/packages/react-dom/src/events/SyntheticKeyboardEvent.js @@ -54,6 +54,23 @@ var KeyboardEventInterface = { } return 0; }, + code: function(event) { + // `code` represents a physical key on the keyboard, as opposed to the character + // generated by pressing the key. + + // It returns a value not altered by keyboard layout + // or the state of the modifier keys. + + // Assuming the input doesn't come from a physical keyboard, but instead from a virtual + // keyboard or accessibility device, it will be returned a value set by the browser to match + // as closely as possible to what would happen with a physical keyboard, to maximize + // compatibility between physical and virtual input devices. + if (event.type === 'keydown' || event.type === 'keyup') { + return event.code; + } + + return 0; + }, which: function(event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. diff --git a/packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js b/packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js index 4c510cc6f60af..144ae533e0127 100644 --- a/packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js +++ b/packages/react-dom/src/events/__tests__/SyntheticKeyboardEvent-test.js @@ -63,6 +63,22 @@ describe('SyntheticKeyboardEvent', () => { }); }); + describe('code', () => { + describe('when event is `keydown` or `keyup`', () => { + it('returns a passed code', () => { + var keyboardEvent = createEvent({type: 'keyup', code: 'ArrowDown'}); + expect(keyboardEvent.code).toBe('ArrowDown'); + }); + }); + + describe('when event is `keypress`', () => { + it('returns 0', () => { + var keyboardEvent = createEvent({type: 'keypress', charCode: 40}); + expect(keyboardEvent.code).toBe(0); + }); + }); + }); + describe('which', () => { describe('when event is `keypress`', () => { it('returns whatever getEventCharCode returns', () => {