Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add KeyboardEvent.code to synthetic event #18287

Merged
merged 3 commits into from Apr 4, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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') {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we just have code: null? Why does it need special handling?

Copy link
Contributor Author

@bl00mber bl00mber Apr 2, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assumed this structure had something with react internals or KeyboardEvent specification because lower on this interface similar blocks are placed. When keypress callback is executed without react, code is equal to output of keydown and keyup events. However, if it executed with react, the output will be null.

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