forked from redux-form/redux-form
/
ConnectedFields.js
215 lines (190 loc) · 6.82 KB
/
ConnectedFields.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
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
// @flow
import * as React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import createFieldProps from './createFieldProps'
import plain from './structure/plain'
import onChangeValue from './events/onChangeValue'
import type { Structure } from './types.js.flow'
import type { Props } from './ConnectedFields.types'
import validateComponentProp from './util/validateComponentProp'
const propsToNotUpdateFor = ['_reduxForm']
const createConnectedFields = (structure: Structure<*, *>) => {
const { deepEqual, getIn, size } = structure
const getSyncError = (syncErrors: Object, name: string) => {
// Because the error for this field might not be at a level in the error structure where
// it can be set directly, it might need to be unwrapped from the _error property
return (
plain.getIn(syncErrors, `${name}._error`) || plain.getIn(syncErrors, name)
)
}
const getSyncWarning = (syncWarnings: Object, name: string) => {
const warning = getIn(syncWarnings, name)
// Because the warning for this field might not be at a level in the warning structure where
// it can be set directly, it might need to be unwrapped from the _warning property
return warning && warning._warning ? warning._warning : warning
}
class ConnectedFields extends React.Component<Props> {
onChangeFns = {}
onFocusFns = {}
onBlurFns = {}
ref: ?React.Component<*>
constructor(props: Props) {
super(props)
this.prepareEventHandlers(props)
}
prepareEventHandlers = ({ names }: Props) =>
names.forEach(name => {
this.onChangeFns[name] = event => this.handleChange(name, event)
this.onFocusFns[name] = () => this.handleFocus(name)
this.onBlurFns[name] = event => this.handleBlur(name, event)
})
componentWillReceiveProps(nextProps: Props) {
if (
this.props.names !== nextProps.names &&
(size(this.props.names) !== size(nextProps.names) ||
nextProps.names.some(nextName => !this.props._fields[nextName]))
) {
// names has changed. The cached event handlers need to be updated
this.prepareEventHandlers(nextProps)
}
}
shouldComponentUpdate(nextProps: Props) {
const nextPropsKeys = Object.keys(nextProps)
const thisPropsKeys = Object.keys(this.props)
// if we have children, we MUST update in React 16
// https://twitter.com/erikras/status/915866544558788608
return !!(
this.props.children ||
nextProps.children ||
nextPropsKeys.length !== thisPropsKeys.length ||
nextPropsKeys.some(prop => {
return (
!~propsToNotUpdateFor.indexOf(prop) &&
!deepEqual(this.props[prop], nextProps[prop])
)
})
)
}
isDirty(): boolean {
const { _fields } = this.props
return Object.keys(_fields).some(name => _fields[name].dirty)
}
getValues(): Object {
const { _fields } = this.props
return Object.keys(_fields).reduce(
(accumulator, name) =>
plain.setIn(accumulator, name, _fields[name].value),
{}
)
}
getRenderedComponent() {
return this.ref
}
handleChange = (name: string, event: any): void => {
const { dispatch, parse, _reduxForm } = this.props
const value = onChangeValue(event, { name, parse })
dispatch(_reduxForm.change(name, value))
// call post-change callback
if (_reduxForm.asyncValidate) {
_reduxForm.asyncValidate(name, value, 'change')
}
}
handleFocus = (name: string): void => {
const { dispatch, _reduxForm } = this.props
dispatch(_reduxForm.focus(name))
}
handleBlur = (name: string, event: any): void => {
const { dispatch, parse, _reduxForm } = this.props
const value = onChangeValue(event, { name, parse })
// dispatch blur action
dispatch(_reduxForm.blur(name, value))
// call post-blur callback
if (_reduxForm.asyncValidate) {
_reduxForm.asyncValidate(name, value, 'blur')
}
}
saveRef = (ref: ?React.Component<*>) => {
this.ref = ref
}
render() {
const { component, withRef, _fields, _reduxForm, ...rest } = this.props
const { sectionPrefix, form } = _reduxForm
const { custom, ...props } = Object.keys(_fields).reduce(
(accumulator, name) => {
const connectedProps = _fields[name]
const { custom, ...fieldProps } = createFieldProps(structure, name, {
...connectedProps,
...rest,
form,
onBlur: this.onBlurFns[name],
onChange: this.onChangeFns[name],
onFocus: this.onFocusFns[name]
})
accumulator.custom = custom
const fieldName = sectionPrefix
? name.replace(`${sectionPrefix}.`, '')
: name
return plain.setIn(accumulator, fieldName, fieldProps)
},
{}
)
if (withRef) {
props.ref = this.saveRef
}
return React.createElement(component, { ...props, ...custom })
}
}
ConnectedFields.propTypes = {
component: validateComponentProp,
_fields: PropTypes.object.isRequired,
props: PropTypes.object
}
const connector = connect(
(state, ownProps) => {
const {
names,
_reduxForm: { initialValues, getFormState }
} = ownProps
const formState = getFormState(state)
return {
_fields: names.reduce((accumulator, name) => {
const initialState = getIn(formState, `initial.${name}`)
const initial =
initialState !== undefined
? initialState
: initialValues && getIn(initialValues, name)
const value = getIn(formState, `values.${name}`)
const syncError = getSyncError(getIn(formState, 'syncErrors'), name)
const syncWarning = getSyncWarning(
getIn(formState, 'syncWarnings'),
name
)
const submitting = getIn(formState, 'submitting')
const pristine = value === initial
accumulator[name] = {
asyncError: getIn(formState, `asyncErrors.${name}`),
asyncValidating: getIn(formState, 'asyncValidating') === name,
dirty: !pristine,
initial,
pristine,
state: getIn(formState, `fields.${name}`),
submitError: getIn(formState, `submitErrors.${name}`),
submitFailed: getIn(formState, 'submitFailed'),
submitting,
syncError,
syncWarning,
value,
_value: ownProps.value // save value passed in (for checkboxes)
}
return accumulator
}, {})
}
},
undefined,
undefined,
{ forwardRef: true }
)
return connector(ConnectedFields)
}
export default createConnectedFields