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 3cc717e
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
6 changes: 6 additions & 0 deletions packages/react-dom/src/events/SyntheticKeyboardEvent.js
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
1 change: 1 addition & 0 deletions packages/react-interactions/events/src/dom/Keyboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export type KeyboardEvent = {|
defaultPrevented: boolean,
isComposing?: boolean,
key?: string,
code?: string,
metaKey: boolean,
pointerType: 'keyboard',
shiftKey: boolean,
Expand Down

0 comments on commit 3cc717e

Please sign in to comment.