-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
232 lines (213 loc) · 7.02 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
import F from 'futil'
import _ from 'lodash/fp.js'
import { extendObservable, reaction } from 'mobx'
import * as validators from './validators.js'
import {
tokenizePath,
safeJoinPaths,
gatherFormValues,
ValidationError,
} from './util.js'
import { treePath, omitByPrefixes, pickByPrefixes } from './futil.js'
import { get, set, toJS, observable } from './mobx.js'
export { validators, ValidationError }
let changed = (x, y) => !_.isEqual(x, y) && !(F.isBlank(x) && F.isBlank(y))
let Command = F.aspects.command(x => y => extendObservable(y, x))
export let jsonSchemaKeys = {
label: 'title',
fields: 'properties',
itemField: 'items',
defaultValue: 'default',
}
export let legacyKeys = {
label: 'label',
fields: 'fields',
itemField: 'itemField',
defaultValue: 'value',
}
let defaultGetPatch = form =>
_.mapValues('to', F.diff(form.saved.value, toJS(form.value)))
// Ideally we'd just do toJS(form.value) but we have to maintain backwards
// compatibility and include fields with undefined values as well
let defaultGetSnapshot = form => F.flattenObject(toJS(gatherFormValues(form)))
let defaultGetNestedSnapshot = form => F.unflattenObject(form.getSnapshot())
// Splice the form errors when a array item is removed
const spliceErrors = (errors, parentPath, nodePosition) => {
const parent = parentPath.join('.')
const parentLength = parentPath.length
const arrayErrors = pickByPrefixes([parent], errors)
const newErrors = omitByPrefixes([parent], errors)
for (const [key, value] of Object.entries(arrayErrors)) {
const keyFields = key.split('.')
const idx = parseInt(keyFields[parentLength])
if (idx > nodePosition) {
keyFields.splice(parentLength, 1, idx - 1)
const newKey = keyFields.join('.')
newErrors[newKey] = value
} else if (idx < nodePosition) {
newErrors[key] = value
}
}
return newErrors
}
export default ({
submit: configSubmit,
value = {},
afterInitField = x => x,
validate = validators.functions,
identifier = 'unknown',
keys = legacyKeys,
getPatch = defaultGetPatch,
getSnapshot = defaultGetSnapshot,
getNestedSnapshot = defaultGetNestedSnapshot,
...autoFormConfig
}) => {
let fieldPath = _.flow(F.intersperse(keys.fields), _.compact)
let flattenField = F.flattenTree(x => x[keys.fields])((...x) =>
_.join('.', treePath(...x))
)
let saved = {}
let state = observable({ value, errors: {}, disposers: {} })
let initField = (config, rootPath = []) => {
let dotPath = _.join('.', rootPath)
let valuePath = ['value', ...rootPath]
let node = observable({
...config,
field: _.last(rootPath),
[keys.label]: config[keys.label] || _.startCase(_.last(rootPath)),
'data-testid': _.snakeCase([identifier, ...rootPath]),
get value() {
return get(valuePath, state)
},
set value(x) {
set(valuePath, x, state)
},
get errors() {
return get(_.compact(['errors', dotPath]), state) || []
},
get isValid() {
return _.isEmpty(node.errors)
},
get isDirty() {
return changed(_.get(valuePath, saved), toJS(node.value))
},
reset() {
node.value = toJS(_.get(valuePath, saved))
state.errors = omitByPrefixes([dotPath], state.errors)
},
validate(paths = [dotPath]) {
let errors = validate(form, pickByPrefixes(paths, flattenField(form)))
state.errors = {
...omitByPrefixes(paths, state.errors),
...errors,
}
return errors
},
clean() {
F.setOn(valuePath, toJS(node.value), saved)
},
getField(path) {
return _.get(
safeJoinPaths(fieldPath(tokenizePath(path))),
node[keys.fields]
)
},
dispose() {
_.over(_.values(pickByPrefixes([dotPath], state.disposers)))()
state.disposers = omitByPrefixes([dotPath], state.disposers)
},
remove() {
let parent = form.getField(_.dropRight(1, rootPath)) || form
// If array field, remove the value and the reaction will take care of the rest
if (parent[keys.itemField]) {
parent.value.splice(node.field, 1)
state.errors = spliceErrors(state.errors, parent.path, node.field)
}
// Remove object field
else {
node.dispose()
F.unsetOn(node.field, parent.value)
F.unsetOn(node.field, parent[keys.fields])
// Clean errors for this field and all subfields
state.errors = omitByPrefixes([dotPath], state.errors, node.field)
}
},
})
node.path = rootPath
// config.value acts as a default value
if (_.isUndefined(node.value) && !_.isUndefined(config[keys.defaultValue]))
node.value = toJS(config[keys.defaultValue])
// Only allow adding subfields for nested object fields
if (node[keys.fields])
node.add = configs =>
extendObservable(
node[keys.fields],
F.mapValuesIndexed((x, k) => initTree(x, [...rootPath, k]), configs)
)
// Recreate all array fields on array size changes
if (node[keys.itemField]) {
node[keys.fields] = observable([])
state.disposers[dotPath] = reaction(
() => _.size(node.value),
size => {
_.each(x => x.dispose(), node[keys.fields])
node[keys.fields].replace(
_.times(
index => initTree(node[keys.itemField], [...rootPath, index]),
size
)
)
}
)
}
return afterInitField(node, { ...config, keys })
}
let initTree = (config, rootPath = []) =>
F.reduceTree(x => x[keys.fields])((tree, node, ...args) => {
let path = treePath(node, ...args)
let field = initField(node, [...rootPath, ...path])
// Set fields on node to keep recursing
if (node[keys.itemField])
node[keys.fields] = _.times(
() => toJS(node[keys.itemField]),
_.size(field.value)
)
return _.isEmpty(path)
? field
: set([keys.fields, ...fieldPath(path)], field, tree)
})({})(toJS(config))
let form = extendObservable(initTree(autoFormConfig), {
getPatch: () => getPatch(form),
getSnapshot: () => getSnapshot(form),
getNestedSnapshot: () => getNestedSnapshot(form),
get submitError() {
return F.getOrReturn('message', form.submit.state.error)
},
})
let submit = Command(async () => {
if (_.isEmpty(form.validate())) {
form.submit.state.error = null
try {
return await configSubmit(form.getSnapshot(), form)
} catch (err) {
if (err instanceof ValidationError) {
state.errors = err.cause
}
throw err
}
}
throw 'Validation Error'
})
extendObservable(form, { submit })
form.submit.state = submit.state
// This allows new and legacy code to work on the same form
form.keys = keys
form.saved = saved
form.reset = F.aspectSync({
before: () => (form.submit.state.error = null),
})(form.reset)
F.unsetOn('field', form)
F.unsetOn('remove', form)
form.clean()
return form
}