-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
FormWrapper.tsx
191 lines (173 loc) · 7.47 KB
/
FormWrapper.tsx
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import React, {useCallback, useMemo, useRef} from 'react';
import type {RefObject} from 'react';
// eslint-disable-next-line no-restricted-imports
import type {ScrollView as RNScrollView, StyleProp, ViewStyle} from 'react-native';
import {Keyboard, View} from 'react-native';
import type {OnyxEntry} from 'react-native-onyx';
import {withOnyx} from 'react-native-onyx';
import FormAlertWithSubmitButton from '@components/FormAlertWithSubmitButton';
import FormElement from '@components/FormElement';
import SafeAreaConsumer from '@components/SafeAreaConsumer';
import type {SafeAreaChildrenProps} from '@components/SafeAreaConsumer/types';
import ScrollView from '@components/ScrollView';
import ScrollViewWithContext from '@components/ScrollViewWithContext';
import useThemeStyles from '@hooks/useThemeStyles';
import * as ErrorUtils from '@libs/ErrorUtils';
import type {Form} from '@src/types/form';
import type ChildrenProps from '@src/types/utils/ChildrenProps';
import {isEmptyObject} from '@src/types/utils/EmptyObject';
import type {FormInputErrors, FormProps, InputRefs} from './types';
type FormWrapperOnyxProps = {
/** Contains the form state that must be accessed outside the component */
formState: OnyxEntry<Form>;
};
type FormWrapperProps = ChildrenProps &
FormWrapperOnyxProps &
FormProps & {
/** Submit button styles */
submitButtonStyles?: StyleProp<ViewStyle>;
/** Whether to apply flex to the submit button */
submitFlexEnabled?: boolean;
/** Whether the form container should grow or adapt to the viewable available space */
shouldContainerGrow?: boolean;
/** Server side errors keyed by microtime */
errors: FormInputErrors;
/** Assuming refs are React refs */
inputRefs: RefObject<InputRefs>;
/** Callback to submit the form */
onSubmit: () => void;
};
function FormWrapper({
onSubmit,
children,
formState,
errors,
inputRefs,
submitButtonText,
footerContent,
isSubmitButtonVisible = true,
style,
submitButtonStyles,
submitFlexEnabled = true,
enabledWhenOffline,
isSubmitActionDangerous = false,
formID,
scrollContextEnabled = false,
shouldHideFixErrorsAlert = false,
disablePressOnEnter = true,
shouldContainerGrow = true,
}: FormWrapperProps) {
const styles = useThemeStyles();
const formRef = useRef<RNScrollView>(null);
const formContentRef = useRef<View>(null);
const errorMessage = useMemo(() => (formState ? ErrorUtils.getLatestErrorMessage(formState) : undefined), [formState]);
const onFixTheErrorsLinkPressed = useCallback(() => {
const errorFields = !isEmptyObject(errors) ? errors : formState?.errorFields ?? {};
const focusKey = Object.keys(inputRefs.current ?? {}).find((key) => Object.keys(errorFields).includes(key));
if (!focusKey) {
return;
}
const focusInput = inputRefs.current?.[focusKey]?.current;
// Dismiss the keyboard for non-text fields by checking if the component has the isFocused method, as only TextInput has this method.
if (typeof focusInput?.isFocused !== 'function') {
Keyboard.dismiss();
}
// We subtract 10 to scroll slightly above the input
if (formContentRef.current) {
// We measure relative to the content root, not the scroll view, as that gives
// consistent results across mobile and web
focusInput?.measureLayout?.(formContentRef.current, (X: number, y: number) =>
formRef.current?.scrollTo({
y: y - 10,
animated: false,
}),
);
}
// Focus the input after scrolling, as on the Web it gives a slightly better visual result
focusInput?.focus?.();
}, [errors, formState?.errorFields, inputRefs]);
const scrollViewContent = useCallback(
(safeAreaPaddingBottomStyle: SafeAreaChildrenProps['safeAreaPaddingBottomStyle']) => (
<FormElement
key={formID}
ref={formContentRef}
style={[style, safeAreaPaddingBottomStyle.paddingBottom ? safeAreaPaddingBottomStyle : styles.pb5]}
>
<View style={styles.flex1}>{children}</View>
{isSubmitButtonVisible && (
<FormAlertWithSubmitButton
buttonText={submitButtonText}
isAlertVisible={((!isEmptyObject(errors) || !isEmptyObject(formState?.errorFields)) && !shouldHideFixErrorsAlert) || !!errorMessage}
isLoading={!!formState?.isLoading}
message={isEmptyObject(formState?.errorFields) ? errorMessage : undefined}
onSubmit={onSubmit}
footerContent={footerContent}
onFixTheErrorsLinkPressed={onFixTheErrorsLinkPressed}
containerStyles={[styles.mh0, styles.mt5, submitFlexEnabled ? styles.flex1 : {}, submitButtonStyles]}
enabledWhenOffline={enabledWhenOffline}
isSubmitActionDangerous={isSubmitActionDangerous}
disablePressOnEnter={disablePressOnEnter}
enterKeyEventListenerPriority={1}
/>
)}
</FormElement>
),
[
formID,
style,
styles.pb5,
styles.mh0,
styles.mt5,
styles.flex1,
children,
isSubmitButtonVisible,
submitButtonText,
errors,
formState?.errorFields,
formState?.isLoading,
shouldHideFixErrorsAlert,
errorMessage,
onSubmit,
footerContent,
onFixTheErrorsLinkPressed,
submitFlexEnabled,
submitButtonStyles,
enabledWhenOffline,
isSubmitActionDangerous,
disablePressOnEnter,
],
);
return (
<SafeAreaConsumer>
{({safeAreaPaddingBottomStyle}) =>
scrollContextEnabled ? (
<ScrollViewWithContext
style={[styles.w100, styles.flex1]}
contentContainerStyle={shouldContainerGrow ? styles.flexGrow1 : styles.flex1}
keyboardShouldPersistTaps="handled"
ref={formRef}
>
{scrollViewContent(safeAreaPaddingBottomStyle)}
</ScrollViewWithContext>
) : (
<ScrollView
style={[styles.w100, styles.flex1]}
contentContainerStyle={shouldContainerGrow ? styles.flexGrow1 : styles.flex1}
keyboardShouldPersistTaps="handled"
ref={formRef}
>
{scrollViewContent(safeAreaPaddingBottomStyle)}
</ScrollView>
)
}
</SafeAreaConsumer>
);
}
FormWrapper.displayName = 'FormWrapper';
export default withOnyx<FormWrapperProps, FormWrapperOnyxProps>({
formState: {
// withOnyx typings are not able to handle such generic cases like this one, since it's a generic component we need to cast the keys to any
// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-explicit-any
key: (props) => props.formID as any,
},
})(FormWrapper);