-
Notifications
You must be signed in to change notification settings - Fork 11
/
utils.ts
88 lines (85 loc) · 2.67 KB
/
utils.ts
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
import { IReactFormConfig } from './types'
const dot = require('dot-prop-immutable')
const getNewState = (
callback: (val: any) => void,
store: any,
customValueResolver?: { (config: IReactFormConfig, args: any[]): any }[],
) => {
const getValue = (...agmnts: any[]) => {
const [config, event] = agmnts
switch (config.type) {
case 'color':
case 'date':
case 'email':
case 'month':
case 'text':
case 'range':
case 'tel':
case 'time':
case 'url':
case 'week':
case 'textarea':
case 'radio':
return event.currentTarget.value
case 'number':
return parseInt(event.currentTarget.value, 10)
case 'dropdown':
if (config.componentProps && config.componentProps.multiple) {
const options = event.currentTarget.options
const value = []
for (let i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
value.push(options[i].value)
}
}
return config.simpleValues
? value.join(config.separator || ',')
: value
}
return event.currentTarget.value
case 'checkbox':
const value = event.currentTarget.value
const existingValue = dot.get(store, config.resultPath) || []
const existingValueArray =
config.simpleValues && existingValue.split
? existingValue.split(config.separator || ',')
: existingValue
const valuesSet = new Set(existingValueArray)
if (valuesSet.has(value)) {
valuesSet.delete(value)
} else {
valuesSet.add(value)
}
const valueArray = [...valuesSet]
return config.simpleValues
? valueArray.join(config.separator || ',')
: valueArray
case 'toggle':
return event.currentTarget.value === 'true'
default:
if (customValueResolver) {
let value = ''
let i = 0
while (i < customValueResolver.length) {
value = customValueResolver[i].apply(null, agmnts)
if (value || typeof value === 'boolean') {
break
}
i++
}
return value
}
return ''
}
}
return (config: IReactFormConfig, ...rest: any[]) => {
const value = getValue.apply(null, [config].concat(rest))
const intermediateStore = dot.set(store, config.resultPath, value)
const newStore = config.modifyStoreBeforeChange
? config.modifyStoreBeforeChange(config, value, intermediateStore) ||
intermediateStore
: intermediateStore
return callback(newStore)
}
}
export { getNewState }