Skip to content

Commit

Permalink
Add KeyboardEvent.code to synthetic event
Browse files Browse the repository at this point in the history
  • Loading branch information
bl00mber committed Mar 14, 2020
1 parent 8b155d2 commit ee40b3f
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/react-dom/src/events/SyntheticKeyboardEvent.js
Expand Up @@ -16,6 +16,12 @@ import getEventModifierState from './getEventModifierState';
*/
const SyntheticKeyboardEvent = SyntheticUIEvent.extend({
key: getEventKey,
code: function(event) {
if (event.type === 'keydown' || event.type === 'keyup') {
return event.code;
}
return 0;
},
location: null,
ctrlKey: null,
shiftKey: null,
Expand Down
Expand Up @@ -451,6 +451,52 @@ describe('SyntheticKeyboardEvent', () => {
});
});
});

describe('code', () => {
it('returns code on `keydown`, `keyup` and 0 on `keypress`', () => {
let codeDown = null;
let codeUp = null;
let codePress = null;
const node = ReactDOM.render(
<input
onKeyDown={e => {
codeDown = e.code;
}}
onKeyUp={e => {
codeUp = e.code;
}}
onKeyPress={e => {
codePress = e.code;
}}
/>,
container,
);
node.dispatchEvent(
new KeyboardEvent('keydown', {
code: 'KeyQ',
bubbles: true,
cancelable: true,
}),
);
node.dispatchEvent(
new KeyboardEvent('keyup', {
code: 'KeyQ',
bubbles: true,
cancelable: true,
}),
);
node.dispatchEvent(
new KeyboardEvent('keypress', {
charCode: 81,
bubbles: true,
cancelable: true,
}),
);
expect(codeDown).toBe('KeyQ');
expect(codeUp).toBe('KeyQ');
expect(codePress).toBe(0);
});
});
});

describe('EventInterface', () => {
Expand Down

0 comments on commit ee40b3f

Please sign in to comment.