-
Notifications
You must be signed in to change notification settings - Fork 253
/
Copy pathFormField.tsx
321 lines (271 loc) · 8.02 KB
/
FormField.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import React, { useContext, useEffect, ReactNode } from 'react'
import FormControl from '@mui/material/FormControl'
import FormHelperText from '@mui/material/FormHelperText'
import FormLabel from '@mui/material/FormLabel'
import { get, isEmpty, startCase } from 'lodash'
import shrinkWorkaround from '../util/shrinkWorkaround'
import AppLink from '../util/AppLink'
import { FormContainerContext } from './context'
import { Grid } from '@mui/material'
interface Options {
label: string,
value: string,
}
interface FormFieldProps {
children: ReactNode,
component: any,
render: () => void,
mapValue: () => void,
mapOnChangeValue: () => void,
checkbox: boolean,
float: boolean,
name: string,
fieldName: string,
// min and max values specify the range to clamp a int value
// expects an ISO timestamp, if string
min: number | string,
max: number | string,
errorName: string,
label: ReactNode,
formLabel: boolean,
required: boolean,
validate: (value: any) => void,
hint: ReactNode,
noError: boolean,
step: number | string,
InputProps: Object,
disabled: boolean,
multiline: boolean,
rows: number,
autoComplete: string,
charCount: number,
fullWidth: boolean,
placeholder: string,
type: string,
select: boolean,
timeZone: string,
userID: string,
value: string | string[],
multiple: boolean,
options: Options
}
export function FormField(props: FormFieldProps) {
const {
errors,
value,
onChange,
addField,
disabled: containerDisabled,
optionalLabels,
} = useContext(FormContainerContext)
const {
errorName,
name,
noError,
component: Component,
render,
fieldName: _fieldName,
formLabel,
required,
validate = () => {},
disabled: fieldDisabled,
hint,
label: _label,
InputProps: _inputProps,
mapValue = (value: any) => value,
mapOnChangeValue = (value: any) => value,
min,
max,
checkbox,
float,
charCount,
...otherFieldProps
} = props
const fieldName = _fieldName || name
const validateField = (value: any) => {
if (
required &&
!['boolean', 'number'].includes(typeof value) &&
isEmpty(value)
) {
return new Error('Required field.')
}
return validate(value)
}
useEffect(() => {
return addField(fieldName, validateField)
}, [required])
const baseLabel = typeof _label === 'string' ? _label : startCase(name)
const label =
!required && optionalLabels ? baseLabel + ' (optional)' : baseLabel
const fieldProps = {
...otherFieldProps,
name,
required,
disabled: containerDisabled || fieldDisabled,
error: errors.find((err) => err.field === (errorName || fieldName)),
hint,
value: mapValue(get(value, fieldName), value),
min,
max,
float,
}
const InputLabelProps = {
required: required && !optionalLabels,
...shrinkWorkaround(props.value),
..._inputProps,
}
let getValueOf = (e) => (e && e.target ? e.target.value : e)
if (checkbox) {
fieldProps.checked = fieldProps.value
fieldProps.value = fieldProps.value ? 'true' : 'false'
getValueOf = (e) => e.target.checked
} else if (otherFieldProps.type === 'number') {
fieldProps.label = label
fieldProps.value = fieldProps.value.toString()
fieldProps.InputLabelProps = InputLabelProps
getValueOf = (e) =>
float ? parseFloat(e.target.value) : parseInt(e.target.value, 10)
} else {
fieldProps.label = label
fieldProps.InputLabelProps = InputLabelProps
}
fieldProps.onChange = (_value) => {
let newValue = getValueOf(_value)
if (fieldProps.type === 'number' && typeof fieldProps.min === 'number')
newValue = Math.max(fieldProps.min, newValue)
if (fieldProps.type === 'number' && typeof fieldProps.max === 'number')
newValue = Math.min(fieldProps.max, newValue)
onChange(fieldName, mapOnChangeValue(newValue, value))
}
// wraps hints/errors within a grid containing character counter to align horizontally
function charCountWrapper(component, count) {
return (
<Grid container spacing={2}>
<Grid item xs={10}>
{component}
</Grid>
<Grid item xs={2}>
<FormHelperText style={{ textAlign: 'right' }}>
{value.description.length}/{count}
</FormHelperText>
</Grid>
</Grid>
)
}
function renderFormHelperText(error, hint, count) {
// handle optional count parameter
if (count === undefined) {
count = 0
}
if (!noError) {
if (error?.helpLink) {
return (
<FormHelperText>
<AppLink to={error.helpLink} newTab data-cy='error-help-link'>
{error.message.replace(/^./, (str) => str.toUpperCase())}
</AppLink>
</FormHelperText>
)
}
if (error?.message) {
const errorText = (
<FormHelperText>
{error.message.replace(/^./, (str) => str.toUpperCase())}
</FormHelperText>
)
if (count) {
return charCountWrapper(errorText, count)
}
return errorText
}
}
if (hint) {
if (count) {
return charCountWrapper(<FormHelperText>{hint}</FormHelperText>, count)
}
return <FormHelperText>{hint}</FormHelperText>
}
return null
}
if (render) return render(fieldProps)
return (
<FormControl
fullWidth={fieldProps.fullWidth}
error={Boolean(fieldProps.error)}
>
{formLabel && (
<FormLabel style={{ paddingBottom: '0.5em' }}>{_label}</FormLabel>
)}
<Component
{...fieldProps}
error={checkbox ? undefined : Boolean(fieldProps.error)}
// NOTE: empty string label leaves gap in outlined field; fallback to undefined instead
label={(!formLabel && fieldProps.label) || undefined}
>
{fieldProps.children}
</Component>
{renderFormHelperText(fieldProps.error, fieldProps.hint, charCount)}
</FormControl>
)
}
// FormField.propTypes = {
// // pass select dropdown items as children
// children: p.node,
// // one of component or render must be provided
// component: p.any,
// render: p.func,
// // mapValue can be used to map a value before it's passed to the form component
// mapValue: p.func,
// // mapOnChangeValue can be used to map a changed value from the component, before it's
// // passed to the parent form's state.
// mapOnChangeValue: p.func,
// // Adjusts props for usage with a Checkbox component.
// checkbox: p.bool,
// // Allows entering decimal number into a numeric field.
// float: p.bool,
// // fieldName specifies the field used for
// // checking errors, change handlers, and value.
// //
// // If unset, it defaults to `name`.
// name: p.string.isRequired,
// fieldName: p.string,
// // min and max values specify the range to clamp a int value
// // expects an ISO timestamp, if string
// min: p.oneOfType([p.number, p.string]),
// max: p.oneOfType([p.number, p.string]),
// // used if name is set,
// // but the error name is different from graphql responses
// errorName: p.string,
// // label above form component
// label: p.node,
// formLabel: p.bool, // use formLabel instead of label if true
// // required indicates the field may not be left blank.
// required: p.bool,
// // validate can be used to provide client-side validation of a
// // field.
// validate: p.func,
// // a hint for the user on a form field. errors take priority
// hint: p.node,
// // disable the form helper text for errors.
// noError: p.bool,
// step: p.oneOfType([p.number, p.string]),
// InputProps: p.object,
// disabled: p.bool,
// multiline: p.bool,
// rows: p.number,
// autoComplete: p.string,
// charCount: p.number,
// fullWidth: p.bool,
// placeholder: p.string,
// type: p.string,
// select: p.bool,
// timeZone: p.string,
// userID: p.string,
// value: p.oneOfType([p.string, p.arrayOf(p.string)]),
// multiple: p.bool,
// options: p.shape({
// label: p.string,
// value: p.string,
// }),
// }