-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
309 lines (271 loc) · 11.5 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
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
import { get, set } from 'object-path'
import PropTypes from 'prop-types'
import React, { Component } from 'react'
import { View, Text } from 'react-native'
import t from 'tcomb-form-native/lib'
import defaultI18n from 'tcomb-form-native/lib/i18n/en'
import defaultStylesheet from 'tcomb-form-native/lib/stylesheets/bootstrap'
import transform from 'tcomb-json-schema'
import walkObject from '@foqum/walk-object'
import { processRemoteRequests } from 'tcomb-form-native-builder-utils'
import { Modal } from 'tcomb-form-native-builder-components'
import {
jsonToTcombObjectAndUpdate,
objectArray2Object,
objectEquals,
} from './utilities'
const { Form } = t.form
Form.i18n = defaultI18n
Form.stylesheet = defaultStylesheet
const REGEX_REPLACE_PATH = /(meta\.type\.)?meta\.props/
class Builder extends Component {
/* eslint-disable */
static propTypes = {
onChangeWidgetProperty: PropTypes.func,
commentFilled: PropTypes.bool,
context: PropTypes.object,
factories: PropTypes.object,
i18n: PropTypes.object,
onChange: PropTypes.func,
options: PropTypes.object,
stylesheet: PropTypes.object,
templates: PropTypes.object.isRequired,
type: PropTypes.object,
value: PropTypes.any,
}
/* eslint-enable */
constructor(props) {
super(props)
this.state = this._getState(props)
}
componentDidMount() {
let state = this._getState(this.props)
state = {
'dependencies': this._extractDependencies(),
'submitted': false,
...state,
}
this.setState(state)
}
// TODO: Clean
componentDidUpdate(prevProps, prevState) {
const { type: { properties }, options: { stackedPlaceHolders } = {} } = this.props
const { dependencies, value } = this.state
// eslint-disable-next-line
if (prevProps !== this.props) this.setState(this._getState(this.props))
// Fields with dependencies
if ((value && prevState.value) && !objectEquals(prevState.value, value)) {
Object.entries(dependencies).forEach(([dependency, dependantFields]) => {
if (JSON.stringify(prevState.value[dependency]) !== JSON.stringify(value[dependency])) {
const requests = []
const dependentFieldsArray = []
dependantFields.forEach((dependentField) => {
// If dependant fields are in a sublist
if (typeof dependentField === 'object') {
// eslint-disable-next-line no-restricted-syntax
for (const i in value[dependency]) {
if (Object.prototype.hasOwnProperty.call(value[dependency], i)) { // eslint requeriment https://eslint.org/docs/rules/guard-for-in
// eslint-disable-next-line no-loop-func
Object.entries(dependentField).forEach(([key, fields]) => {
fields.forEach((field) => {
const previousValue = prevState.value[dependency] && prevState.value[dependency][i] && prevState.value[dependency][i][key]
const currentValue = value[dependency] && value[dependency][i] && value[dependency][i][key]
if (previousValue !== currentValue) {
const replaceString = '${' + key + '}' // eslint-disable-line
let query = properties[dependency].items.properties[field].meta.body
const objectProperties = properties[dependency].items.properties[field]
if (value[dependency][i] && value[dependency][i][key]) {
query = query.replace(replaceString, `"${value[dependency][i][key]}"`)
// First item: object properties to get the path in the response and second item: the value path.
dependentFieldsArray.push([objectProperties, `${dependency}.${i}.${field}`])
requests.push(processRemoteRequests(properties[dependency].items.properties[field].uri, stackedPlaceHolders, {}, query))
}
}
})
})
}
}
} else {
const replaceString = '${' + dependency + '}' // eslint-disable-line
let query = properties[dependentField].meta.body
query = query.replace(replaceString, `"${value[dependency]}"`)
dependentFieldsArray.push([properties[dependentField], dependentField])
requests.push(processRemoteRequests(properties[dependentField].uri, stackedPlaceHolders, {}, query))
}
})
Promise.all(requests).then((responses) => {
responses.forEach((response, i) => {
const { path } = dependentFieldsArray[i][0].meta
const key = dependentFieldsArray[i][0].meta.fieldLabel
const fieldValue = get(response, path) ? get(response, path)[key] : '' // eslint-disable-line
const date = new Date(Date.parse(fieldValue))
if (!isNaN(date) && date.toISOString() === String(fieldValue)) { // eslint-disable-line
set(value, dependentFieldsArray[i][1], date.toLocaleDateString())
} else if (Array.isArray(fieldValue)) {
const { fieldID, fieldLabelIfDependency } = properties[dependentFieldsArray[i][1]].meta
set(value, dependentFieldsArray[i][1], objectArray2Object(fieldValue, fieldID, fieldLabelIfDependency))
properties[dependentFieldsArray[i][1]].enum = objectArray2Object(fieldValue, fieldID, fieldLabelIfDependency)
} else {
set(value, dependentFieldsArray[i][1], fieldValue)
}
})
this._onChange(value)
}).catch(error => console.error(error))
}
})
}
}
_onChange = (value) => {
const { onChange } = this.props
const { options, type } = this.state
if (onChange) onChange(value)
this.setState({ options: this._updateOptions(options, type, true), value })
}
_triggerValidation = async () => {
formIsValid = (this._root.validate()).errors.length === 0
this.setState({ submitted: true, formIsValid })
return formIsValid
}
_extractDependencies() {
const { type } = this.props
const dependencies = {}
const dependency = {}
Object.entries(type.properties).forEach(([property, fields]) => {
if (fields.type === 'array') {
Object.entries(fields.items.properties).forEach(([item, value]) => {
if (value.meta && value.meta.dependencies) {
value.meta.dependencies.forEach((dep) => {
dependency[dep] = dependency[dep] || []
dependency[dep].push(item)
})
}
})
dependencies[property] = dependencies[property] || []
dependencies[property].push(dependency)
}
if (fields.meta && fields.meta.dependencies) {
fields.meta.dependencies.forEach((dep) => {
dependencies[dep] = dependencies[dep] || []
dependencies[dep].push(property)
})
}
})
return dependencies
}
// get the current value and options of the form
_getState(props) {
const {
onChangeWidgetProperty,
children,
factories,
formats = {},
onSubmit,
requestUploadUrl,
url,
types = {},
} = props
// value is the value of the whole form in an object, and will be updated with every change on the form
let { options = {}, type, value } = props
// transform is a function that transform a valid json to a tcomb object attending the registered formats and types
// Remove all the registered formats and types
transform.resetFormats()
transform.resetTypes()
// Register formats and types as props from the json
Object.entries(formats).forEach(entry => transform.registerFormat(...entry))
Object.entries(types).forEach(entry => transform.registerType(...entry))
// Pass custom variables and callbacks to the `Form` instance trhough the options field
if (onSubmit) options.onSubmit = onSubmit
if (requestUploadUrl) options.requestUploadUrl = requestUploadUrl
if (url) options.url = url
options.triggerValidation = this._triggerValidation
// Get type definition
type = type || children || {}
// If a string is passed it is first transform to JSON object
if (typeof type === 'string') type = JSON.parse(type)
if (!(typeof type === 'function')) {
[type, options, value] = jsonToTcombObjectAndUpdate(type, value, options, factories, transform, onChangeWidgetProperty)
}
// Update values ot the options like if there is a validation error, disable submit values
options = this._updateOptions(options, type)
return { options, type, value }
}
// currently it enables/disables submit button depending on required fields
// in this function we update dynamically values in the form depending onChanges
_updateOptions(options, type, validate = false) {
const { commentFilled = true } = this.props
const { _root } = this
let disabled = { '$set': true }
// Enable buttons
if (_root) {
const { submitted } = this.state
if (submitted && validate) this.setState({ formIsValid: (_root.validate()).errors.length === 0 }) // show errors
disabled = { '$set': !(_root && _root.pureValidate().isValid() && commentFilled) }
}
const patch = {}
walkObject(type, ({ location, value }) => {
if (get(value, 'meta.name') === 'submit') {
if (location.length) {
location = location.join('.').replace(REGEX_REPLACE_PATH, 'fields').split('.')
}
const path = location.concat('disabled')
set(patch, path, disabled)
}
})
options = t.update(options, patch)
if (options) {
const descriptor = { configurable: true, value: _root }
walkObject(options, ({ value }) => {
if (!value || value.constructor.name !== 'Object') return
Object.defineProperty(value, 'form', descriptor)
})
}
return options
}
renderError() {
const { submitted, formIsValid } = this.state
return (submitted && !formIsValid) ?
(
<Text style={{ color: 'red', fontWeight: 'bold' }}>
Something went wrong. Please make sure all required fields are filled
</Text>
) : null
}
render() {
const { context, i18n, stylesheet, templates, buttonColor } = this.props
const { options, type, value, modalFunction } = this.state
options.config = Object.assign({ fields: options.fields }, options.config)
/*
Show or hide the confirmation modal when submitting the form by saving
the Modal class method "showModal" in the Builder state to pass it down
to the tcomb Form components (i.e. submit.js in builder-components),
where it will be called once the form is validated.
NOTE - See Modal prop "setModalFunction" in the render() below
*/
options.showModal = modalFunction
return (
<View>
<Form
context={context}
i18n={i18n || defaultI18n}
onChange={this._onChange}
options={options}
ref={(component) => {
this._root = component
}}
stylesheet={stylesheet}
templates={templates}
type={type}
value={value}
/>
<Modal
setModalFunction={(modalFunc) => { this.setState({ modalFunction: modalFunc }) }}
buttonColor={buttonColor}
/>
{this.renderError()}
</View>
)
}
}
// Export `tcomb` types
Builder.t = t
export default Builder