-
Notifications
You must be signed in to change notification settings - Fork 263
/
useform.taro.ts
249 lines (224 loc) · 5.95 KB
/
useform.taro.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
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
import { useRef } from 'react'
import Schema from 'async-validator'
import {
Store,
Callbacks,
FormInstance,
FormFieldEntity,
NamePath,
} from './types'
export const SECRET = 'NUT_FORM_INTERNAL'
type UpdateItem = { entity: FormFieldEntity; condition: any }
/**
* 用于存储表单的数据
*/
class FormStore {
// 初始化数据
private initialValues: Store = {}
private updateList: UpdateItem[] = []
// 存放表单中所有的数据 eg. {password: "ddd",username: "123"}
private store: Store = {}
// 所有的组件实例
private fieldEntities: FormFieldEntity[] = []
// 校验成功或失败的回调,onFinish、onFinishFailed
private callbacks: Callbacks = {}
private errors: { [key: NamePath]: any } = {}
constructor() {
this.callbacks = {
onFinish: () => {},
onFinishFailed: () => {},
}
}
/**
* 注册组件实例
* @param field
*/
registerField = (field: any) => {
this.fieldEntities.push(field)
return () => {
this.fieldEntities = this.fieldEntities.filter((item) => item !== field)
if (this.store) {
delete this.store[field.props.name]
}
}
}
/**
* 获取 formItem 的值
* @param name
*/
getFieldValue = (name: NamePath) => {
return this.store?.[name]
}
/**
* 获取全部字段
*/
getFieldsValue = (nameList: NamePath[] | true): { [key: NamePath]: any } => {
if (typeof nameList === 'boolean') {
return JSON.parse(JSON.stringify(this.store))
}
const fieldsValue: { [key: NamePath]: any } = {}
nameList.forEach((field) => {
fieldsValue[field] = this.getFieldValue(field)
})
return fieldsValue
}
/**
* 设置 form 的初始值,之后在 reset 的时候使用
* @param values
* @param init
*/
setInitialValues = (values: Store, init: boolean) => {
if (init) {
this.initialValues = values
this.store = values
}
}
/**
* 存储组件数据
* @param newStore { [name]: newValue }
*/
setFieldsValue = (newStore: any, needValidate = true) => {
this.store = {
...this.store,
...newStore,
}
this.fieldEntities.forEach((entity: FormFieldEntity) => {
const { name } = entity.props
Object.keys(newStore).forEach((key) => {
if (key === name) {
entity.onStoreChange('update')
}
})
})
this.updateList.forEach((item: UpdateItem) => {
let shouldUpdate = item.condition
if (typeof item.condition === 'function') {
shouldUpdate = item.condition()
}
if (shouldUpdate) {
item.entity.onStoreChange('update')
}
})
needValidate && this.validateFields()
}
setCallback = (callback: Callbacks) => {
this.callbacks = {
...this.callbacks,
...callback,
}
}
validateEntities = async (entity: FormFieldEntity, errs: any[]) => {
const { name, rules = [] } = entity.props
const descriptor: any = {}
if (rules.length) {
// 多条校验规则
if (rules.length > 1) {
descriptor[name] = []
rules.forEach((v: any) => {
descriptor[name].push(v)
})
} else {
descriptor[name] = rules[0]
}
}
const validator = new Schema(descriptor)
// 此处合并无值message 没有意义?
// validator.messages()
try {
await validator.validate({ [name]: this.store?.[name] })
} catch ({ errors }: any) {
if (errors) {
errs.push(...(errors as any[]))
this.errors[name] = errors
}
} finally {
if (!errs || errs.length === 0) {
this.errors[name] = []
}
}
entity.onStoreChange('validate')
}
validateFields = async (nameList?: NamePath[]) => {
let filterEntities = []
this.errors.length = 0
if (!nameList || nameList.length === 0) {
filterEntities = this.fieldEntities
} else {
filterEntities = this.fieldEntities.filter(({ props: { name } }) =>
nameList.includes(name)
)
}
const errs: any[] = []
await Promise.all(
filterEntities.map(async (entity) => {
await this.validateEntities(entity, errs)
})
)
return errs
}
submit = async () => {
const errors = await this.validateFields()
if (errors.length === 0) {
this.callbacks.onFinish?.(this.store)
} else if (errors.length > 0) {
this.callbacks.onFinishFailed?.(this.store, errors)
}
}
resetFields = () => {
this.errors.length = 0
this.store = this.initialValues
this.fieldEntities.forEach((entity: FormFieldEntity) => {
entity.onStoreChange('reset')
})
}
// 监听事件
registerUpdate = (field: FormFieldEntity, shouldUpdate: any) => {
this.updateList.push({
entity: field,
condition: shouldUpdate,
})
return () => {
this.updateList = this.updateList.filter((i) => i.entity !== field)
}
}
dispatch = ({ name }: { name: string }) => {
this.validateFields([name])
}
getInternal = (key: string) => {
if (key === SECRET) {
return {
registerField: this.registerField,
setCallback: this.setCallback,
setInitialValues: this.setInitialValues,
dispatch: this.dispatch,
store: this.store,
fieldEntities: this.fieldEntities,
registerUpdate: this.registerUpdate,
}
}
}
getForm = () => {
return {
getFieldValue: this.getFieldValue,
getFieldsValue: this.getFieldsValue,
setFieldsValue: this.setFieldsValue,
resetFields: this.resetFields,
validateFields: this.validateFields,
submit: this.submit,
errors: this.errors,
getInternal: this.getInternal,
}
}
}
export const useForm = (form?: FormInstance): [FormInstance] => {
const formRef = useRef<FormInstance>()
if (!formRef.current) {
if (form) {
formRef.current = form
} else {
const formStore = new FormStore()
formRef.current = formStore.getForm() as FormInstance
}
}
return [formRef.current]
}