forked from laravel/precognition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
182 lines (154 loc) · 5.16 KB
/
index.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
import { Config, RequestMethod, client, createValidator, toSimpleValidationErrors, ValidationConfig, resolveUrl, resolveMethod , resolveName } from 'laravel-precognition'
import { Form } from './types.js'
import { reactive, ref, toRaw } from 'vue'
import { cloneDeep, get, set } from 'lodash-es'
export { client }
export const useForm = <Data extends Record<string, unknown>>(method: RequestMethod | (() => RequestMethod), url: string | (() => string), inputs: Data | (() => Data), config: ValidationConfig = {}): Data & Form<Data> => {
/**
* The original data.
*/
const originalData = typeof inputs === 'function' ? cloneDeep(inputs()) : cloneDeep(inputs)
/**
* The original input names.
*/
const originalInputs: (keyof Data)[] = Object.keys(originalData)
/**
* Reactive valid state.
*/
const valid = ref<(keyof Data)[]>([])
/**
* Reactive touched state.
*/
const touched = ref<(keyof Partial<Data>)[]>([])
/**
* The validator instance.
*/
const validator = createValidator((client) => client[resolveMethod(method)](resolveUrl(url), form.data(), config), originalData)
.on('validatingChanged', () => {
form.validating = validator.validating()
})
.on('validatedChanged', () => {
valid.value = validator.valid()
})
.on('touchedChanged', () => {
touched.value = validator.touched()
})
.on('errorsChanged', () => {
form.hasErrors = validator.hasErrors()
// @ts-expect-error
form.errors = toSimpleValidationErrors(validator.errors())
valid.value = validator.valid()
})
/**
* Resolve the config for a form submission.
*/
const resolveSubmitConfig = (config: Config): Config => ({
...config,
precognitive: false,
onStart: () => {
form.processing = true;
(config.onStart ?? (() => null))()
},
onFinish: () => {
form.processing = false;
(config.onFinish ?? (() => null))()
},
onValidationError: (response, error) => {
validator.setErrors(response.data.errors)
return config.onValidationError
? config.onValidationError(response)
: Promise.reject(error)
},
})
/**
* Create a new form instance.
*/
let form: Data & Form<Data> = {
...cloneDeep(originalData),
data() {
const data = cloneDeep(toRaw(form))
return originalInputs.reduce<Partial<Data>>((carry, name) => ({
...carry,
[name]: data[name],
}), {}) as Data
},
setData(data: Record<string, unknown>) {
Object.keys(data).forEach((input) => {
// @ts-expect-error
form[input] = data[input]
})
return form
},
touched(name) {
// @ts-expect-error
return touched.value.includes(name)
},
touch(name) {
validator.touch(name)
return form
},
validate(name, config) {
if (typeof name === 'object' && !('target' in name)) {
config = name
name = undefined
}
if (typeof name === 'undefined') {
validator.validate(config)
} else {
// @ts-expect-error
name = resolveName(name)
validator.validate(name, get(form.data(), name), config)
}
return form
},
validating: false,
valid(name) {
// @ts-expect-error
return valid.value.includes(name)
},
invalid(name) {
return typeof form.errors[name] !== 'undefined'
},
errors: {},
hasErrors: false,
setErrors(errors) {
// @ts-expect-error
validator.setErrors(errors)
return form
},
forgetError(name) {
// @ts-expect-error
validator.forgetError(name)
return form
},
reset(...names) {
const original = typeof inputs === 'function' ? cloneDeep(inputs()) : cloneDeep(originalData)
if (names.length === 0) {
// @ts-expect-error
originalInputs.forEach((name) => (form[name] = original[name]))
} else {
names.forEach((name) => set(form, name, get(original, name)))
}
// @ts-expect-error
validator.reset(...names)
return form
},
setValidationTimeout(duration) {
validator.setTimeout(duration)
return form
},
processing: false,
async submit(config = {}) {
return client[resolveMethod(method)](resolveUrl(url), form.data(), resolveSubmitConfig(config))
},
validateFiles() {
validator.validateFiles()
return form
},
validator() {
return validator
},
}
form = reactive(form) as Data & Form<Data>
return form
}