-
Notifications
You must be signed in to change notification settings - Fork 624
/
Copy pathForm.vue
272 lines (245 loc) · 7 KB
/
Form.vue
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
<template>
<form @submit.prevent="onSubmit">
<slot />
</form>
</template>
<script lang="ts">
import { provide, ref, type PropType, defineComponent, onUnmounted, onMounted } from 'vue'
import { useEventBus } from '@vueuse/core'
import type { ZodSchema } from 'zod'
import type { ValidationError as JoiError, Schema as JoiSchema } from 'joi'
import type { ObjectSchema as YupObjectSchema, ValidationError as YupError } from 'yup'
import type { ObjectSchemaAsync as ValibotObjectSchema } from 'valibot'
import type { FormError, FormEvent, FormEventType, FormSubmitEvent, FormErrorEvent, Form } from '../../types/form'
import { uid } from '../../utils/uid'
class FormException extends Error {
constructor (message: string) {
super(message)
this.message = message
Object.setPrototypeOf(this, FormException.prototype)
}
}
export default defineComponent({
props: {
schema: {
type: Object as
| PropType<ZodSchema>
| PropType<YupObjectSchema<any>>
| PropType<JoiSchema>
| PropType<ValibotObjectSchema<any>>,
default: undefined
},
state: {
type: Object,
required: true
},
validate: {
type: Function as
| PropType<(state: any) => Promise<FormError[]>>
| PropType<(state: any) => FormError[]>,
default: () => []
},
validateOn: {
type: Array as PropType<FormEventType[]>,
default: () => ['blur', 'input', 'change', 'submit']
}
},
emits: ['submit', 'error'],
setup (props, { expose, emit }) {
const bus = useEventBus<FormEvent>(`form-${uid()}`)
onMounted(() => {
bus.on(async (event) => {
if (event.type !== 'submit' && props.validateOn?.includes(event.type)) {
await validate(event.path, { silent: true })
}
})
})
onUnmounted(() => {
bus.reset()
})
const errors = ref<FormError[]>([])
provide('form-errors', errors)
provide('form-events', bus)
const inputs = ref({})
provide('form-inputs', inputs)
async function getErrors (): Promise<FormError[]> {
let errs = await props.validate(props.state)
if (props.schema) {
if (isZodSchema(props.schema)) {
errs = errs.concat(await getZodErrors(props.state, props.schema))
} else if (isYupSchema(props.schema)) {
errs = errs.concat(await getYupErrors(props.state, props.schema))
} else if (isJoiSchema(props.schema)) {
errs = errs.concat(await getJoiErrors(props.state, props.schema))
} else if (isValibotSchema(props.schema)) {
errs = errs.concat(await getValibotError(props.state, props.schema))
} else {
throw new Error('Form validation failed: Unsupported form schema')
}
}
return errs
}
async function validate (path?: string | string[], opts: { silent?: boolean } = { silent: false }) {
let paths = path
if (path && !Array.isArray(path)) {
paths = [path]
}
if (paths) {
const otherErrors = errors.value.filter(
(error) => !paths.includes(error.path)
)
const pathErrors = (await getErrors()).filter(
(error) => paths.includes(error.path)
)
errors.value = otherErrors.concat(pathErrors)
} else {
errors.value = await getErrors()
}
if (!opts.silent && errors.value.length > 0) {
throw new FormException(
`Form validation failed: ${JSON.stringify(errors.value, null, 2)}`
)
}
return props.state
}
async function onSubmit (payload: Event) {
const event = payload as SubmitEvent
try {
if (props.validateOn?.includes('submit')) {
await validate()
}
const submitEvent: FormSubmitEvent<any> = {
...event,
data: props.state
}
emit('submit', submitEvent)
} catch (error) {
if (!(error instanceof FormException)) {
throw error
}
const errorEvent: FormErrorEvent = {
...event,
errors: errors.value.map((err) => ({
...err,
id: inputs.value[err.path]
}))
}
emit('error', errorEvent)
}
}
expose({
validate,
errors,
setErrors (errs: FormError[], path?: string) {
errors.value = errs
if (path) {
errors.value = errors.value.filter(
(error) => error.path !== path
).concat(errs)
} else {
errors.value = errs
}
},
async submit () {
await onSubmit(new Event('submit'))
},
getErrors (path?: string) {
if (path) {
return errors.value.filter((err) => err.path === path)
}
return errors.value
},
clear (path?: string) {
if (path) {
errors.value = errors.value.filter((err) => err.path !== path)
} else {
errors.value = []
}
}
} as Form<any>)
return {
onSubmit
}
}
})
function isYupSchema (schema: any): schema is YupObjectSchema<any> {
return schema.validate && schema.__isYupSchema__
}
function isYupError (error: any): error is YupError {
return error.inner !== undefined
}
async function getYupErrors (
state: any,
schema: YupObjectSchema<any>
): Promise<FormError[]> {
try {
await schema.validate(state, { abortEarly: false })
return []
} catch (error) {
if (isYupError(error)) {
return error.inner.map((issue) => ({
path: issue.path ?? '',
message: issue.message
}))
} else {
throw error
}
}
}
function isZodSchema (schema: any): schema is ZodSchema {
return schema.parse !== undefined
}
async function getZodErrors (
state: any,
schema: ZodSchema
): Promise<FormError[]> {
const result = await schema.safeParseAsync(state)
if (result.success === false) {
return result.error.issues.map((issue) => ({
path: issue.path.join('.'),
message: issue.message
}))
}
return []
}
function isJoiSchema (schema: any): schema is JoiSchema {
return schema.validateAsync !== undefined && schema.id !== undefined
}
function isJoiError (error: any): error is JoiError {
return error.isJoi === true
}
async function getJoiErrors (
state: any,
schema: JoiSchema
): Promise<FormError[]> {
try {
await schema.validateAsync(state, { abortEarly: false })
return []
} catch (error) {
if (isJoiError(error)) {
return error.details.map((detail) => ({
path: detail.path.join('.'),
message: detail.message
}))
} else {
throw error
}
}
}
function isValibotSchema (schema: any): schema is ValibotObjectSchema<any> {
return schema._parse !== undefined
}
async function getValibotError (
state: any,
schema: ValibotObjectSchema<any>
): Promise<FormError[]> {
const result = await schema._parse(state)
if (result.issues) {
return result.issues.map((issue) => ({
path: issue.path?.map(p => p.key).join('.') || '',
message: issue.message
}))
}
return []
}
</script>