This repository was archived by the owner on Jul 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.tsx
306 lines (286 loc) · 8.51 KB
/
index.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
import lensPath from 'ramda/src/lensPath'
import getPath from 'ramda/src/path'
import set from 'ramda/src/set'
import * as React from 'react'
import {CSSProperties, Component, ReactChild, ReactType, cloneElement} from 'react'
import {BrowserButton, BrowserInput} from './browser-components'
import {getValue, isValid} from './helpers'
export * from './validation'
export type FieldConfig = {
/**
* Path to control in the object passed to FormHelper
*/
path: Array<string>
/**
* Component to render, defaults to the inputComponent passed to FormHelper
*/
component?: ReactType
render?: (props: any) => ReactType
label?: ReactChild
/**
* Callback when then field is modified.
* It receives the full updatedObject for all fields and may return a new object
* that is used instead.
*
* This is useful if you need to change more fields than the specified path.
*/
onChange?: (updatedObject: any) => any
/**
* If the field is required
*/
required?: boolean|((object: any) => boolean)
/**
* Specify validation messages and possibly functions
*
* Example:
* ```
* {
* [required]: {
* text: 'The field is required',
* },
* number: {
* text: 'Only numbers are allowed',
* validation: pattern(/^[0-9]+$/),
* },
* }
* ```
*/
validations?: {
[validationError: string]: {
text: string
validation?: (value: any) => boolean
}
}
/**
* Error in validations to display. The text property of the corresponding
* field in validations will be displayed. Only set this if you handle
* errors externally.
*/
validationError?: string
/**
* Error to display, only set this if you handle errors externally
* and does not use validations.
*/
error?: string
}
export type Properties<T, I> = {
/**
* Fields to show in the form
*
* Example:
* ```
* [
* {
* path: ['username'],
* label: 'Username',
* }
* ]
* ```
*/
fields: Array<FieldConfig & I>
/**
* The object the form will manage.
*/
value: T
/**
* Callback when the form is submitted, an updated object is passed as the only prop.
* If a promise is returned the saveButton component will receive a loading prop set
* to true until the promise is resolved or rejected.
*/
onSave: (savedObject: T) => Promise<any>|void
/**
* Callback when any field in the form is modified.
* If this property is set, the form becomes a controlled component and the value
* prop must be maintained externally.
*
* This is useful if you nest multiple FormHelpers or need to restrict user input
* before it appear on the screen.
*/
onChange?: (updatedObject: T, valid: boolean) => void
/**
* A string or a renderd React component. This property will be passed as a child
* to the buttonComponent
*/
saveButton?: ReactChild
/**
* Component used for the form, defaults to a HTML form element.
*
* This is useful to set to a div if you nest multiple FormHelpers.
*/
formComponent?: ReactType
/**
* Component used for fields that has not specified a different component.
* Defaults to a HTML input element.
*
* Passed props are:
* value: The value for the field
* onChange: A function to be called with an updated value
* error: A string with an error message (if any)
* onBlur: If errorOnTouched is set, a function will be passed that should
* be called when the field looses focus.
*
* The component will also receive props from the field configuration that are not
* path, validations or validationError, for example label and required.
*/
inputComponent?: ReactType
/**
* Button component to render the saveButton, defaults to an HTML button element.
*
* Passed props are:
* disabled: If the button should be disabled
* value: The current value of the form
* loading: If the form is saving or not
*/
buttonComponent?: ReactType
/**
* Extra props that should be passed to the button component
*/
buttonProps?: Object
/**
* A style property that is passed to the formComponent
*/
style?: CSSProperties
/**
* An id property that is passed to the formComponent
*/
formId?: string
/**
* Set to true to disable the saveButton if there are no changes
*/
dirtyCheck?: boolean
/**
* Set to true to only show error messages for fields that have been touched.
* If an array is passed, only validationErrors in that array will be hidden until
* the field is touched.
*/
errorOnTouched?: boolean|Array<string>
/**
* Set to true to disable the saveButton
*/
disabled?: boolean
}
export class FormHelper extends Component<Properties<any, any>, {}> {
unmounted = false
state = {
loading: false,
updatedObject: null,
touched: {} as {[path: string]: boolean},
}
componentWillUnmount() {
this.unmounted = true
}
setLoading(loading: boolean) {
if (!this.unmounted) {
this.setState({loading})
}
}
render() {
const {
style,
fields,
value,
onSave,
onChange,
saveButton,
formComponent: Form = 'form',
inputComponent: Input = BrowserInput,
buttonComponent: Button = BrowserButton,
buttonProps,
formId,
dirtyCheck,
errorOnTouched,
disabled,
} = this.props
let {updatedObject, loading} = this.state
let changed = !!onChange || !dirtyCheck
updatedObject = onChange
? value
: updatedObject || value
const {validatedFields, valid} = isValid(fields, updatedObject)
return (
<Form id={formId} style={style} onSubmit={(e: React.MouseEvent<any>) => {
e.preventDefault()
const returnValue = onSave(updatedObject)
if (returnValue && returnValue.then && returnValue.catch) {
this.setLoading(true)
returnValue
.catch(error => {
this.setLoading(false)
throw error
})
.then(() => this.setLoading(false))
}
}}>
{validatedFields.map((field: any, i: any) => {
if (!field) return null
if (field.props) return cloneElement(field, {key: i})
const {render, component, path, validations, validationError, ...inputProps} = field
if (getPath(path, updatedObject) !== getPath(field.path, value)) {
changed = true
}
const fieldValue = getValue(field.path, updatedObject)
if (validationError) {
const validation = validations && validations[field.validationError]
inputProps.error = (validation && validation.text) || ''
}
if (errorOnTouched) {
let hideError = !this.state.touched[path.join('.')]
if (hideError && Array.isArray(errorOnTouched)) {
hideError = errorOnTouched.includes(validationError)
}
if (hideError) {
const oldBlur = inputProps.onBlur
inputProps.onBlur = (e: React.FormEvent<any>) => {
this.setState({
touched: {
...this.state.touched,
[path.join('.')]: true,
},
})
if (oldBlur) return oldBlur(e)
}
inputProps.error = undefined
}
}
const props = {
key: i,
value: fieldValue,
disabled,
...inputProps,
onChange: (value: any) => {
let newUpdatedObject = set(lensPath(path), value, updatedObject)
if (field.onChange) {
const modifiedObject = field.onChange(newUpdatedObject)
if (modifiedObject) {
newUpdatedObject = modifiedObject
}
}
if (onChange) {
onChange(newUpdatedObject, isValid(fields, newUpdatedObject).valid)
} else {
this.setState({updatedObject: newUpdatedObject})
}
},
}
if (render) {
return render(props)
} else {
const Field = component || Input
return <Field {...props} />
}
})}
{saveButton &&
<Button
type='submit'
value={updatedObject}
loading={loading}
disabled={!changed || !valid || disabled}
{...buttonProps}
>
{saveButton}
</Button>
}
</Form>
)
}
}