-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
index.js
72 lines (61 loc) · 2.49 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import React from 'react';
import lodashGet from 'lodash/get';
import {View} from 'react-native';
import * as formSubmitPropTypes from './formSubmitPropTypes';
import CONST from '../../CONST';
import isEnterWhileComposition from '../../libs/KeyboardShortcut/isEnterWhileComposition';
// This is a wrapper component to handle the ENTER key press, and submit the form.
class FormSubmit extends React.Component {
constructor(props) {
super(props);
this.submitForm = this.submitForm.bind(this);
}
/**
* Calls the submit callback when ENTER is pressed on a form element.
* @param {Object} event
*/
submitForm(event) {
// ENTER is pressed with modifier key or during text composition, do not submit the form
if (event.shiftKey || event.key !== CONST.KEYBOARD_SHORTCUTS.ENTER.shortcutKey || isEnterWhileComposition(event)) {
return;
}
const tagName = lodashGet(event, 'target.tagName', '');
// ENTER is pressed on INPUT or SELECT element, call the submit callback.
if (tagName === 'INPUT' || tagName === 'SELECT') {
this.props.onSubmit();
return;
}
// Pressing Enter on TEXTAREA element adds a new line. When `dataset.submitOnEnter` prop is passed, call the submit callback.
if (tagName === 'TEXTAREA' && lodashGet(event, 'target.dataset.submitOnEnter', 'false') === 'true') {
this.props.onSubmit();
return;
}
// ENTER is pressed on checkbox element, call the submit callback.
if (lodashGet(event, 'target.role') === 'checkbox') {
this.props.onSubmit();
}
}
render() {
return (
// React-native-web prevents event bubbling on TextInput for key presses
// https://github.com/necolas/react-native-web/blob/fa47f80d34ee6cde2536b2a2241e326f84b633c4/packages/react-native-web/src/exports/TextInput/index.js#L272
// Thus use capture phase.
<View
ref={this.props.innerRef}
onKeyDownCapture={this.submitForm}
style={this.props.style}
>
{this.props.children}
</View>
);
}
}
FormSubmit.propTypes = formSubmitPropTypes.propTypes;
FormSubmit.defaultProps = formSubmitPropTypes.defaultProps;
export default React.forwardRef((props, ref) => (
<FormSubmit
// eslint-disable-next-line react/jsx-props-no-spreading
{...props}
innerRef={ref}
/>
));