-
Notifications
You must be signed in to change notification settings - Fork 486
/
Copy pathuseForm.ts
293 lines (270 loc) · 8.94 KB
/
useForm.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
import { FormDataConvertible, Method, Progress, router, VisitOptions } from '@inertiajs/core'
import { isEqual } from 'es-toolkit'
import { useCallback, useEffect, useRef, useState } from 'react'
import useRemember from './useRemember'
type setDataByObject<TForm> = (data: TForm) => void
type setDataByMethod<TForm> = (data: (previousData: TForm) => TForm) => void
type setDataByKeyValuePair<TForm> = <K extends keyof TForm>(key: K, value: TForm[K]) => void
type FormDataType = Record<string, FormDataConvertible>
type FormOptions = Omit<VisitOptions, 'data'>
export interface InertiaFormProps<TForm extends FormDataType> {
data: TForm
isDirty: boolean
errors: Partial<Record<keyof TForm, string>>
hasErrors: boolean
processing: boolean
progress: Progress | null
wasSuccessful: boolean
recentlySuccessful: boolean
setData: setDataByObject<TForm> & setDataByMethod<TForm> & setDataByKeyValuePair<TForm>
transform: (callback: (data: TForm) => object) => void
setDefaults(): void
setDefaults(field: keyof TForm, value: FormDataConvertible): void
setDefaults(fields: Partial<TForm>): void
reset: (...fields: (keyof TForm)[]) => void
clearErrors: (...fields: (keyof TForm)[]) => void
setError(field: keyof TForm, value: string): void
setError(errors: Record<keyof TForm, string>): void
submit: (method: Method, url: string, options?: FormOptions) => void
get: (url: string, options?: FormOptions) => void
patch: (url: string, options?: FormOptions) => void
post: (url: string, options?: FormOptions) => void
put: (url: string, options?: FormOptions) => void
delete: (url: string, options?: FormOptions) => void
cancel: () => void
}
export default function useForm<TForm extends FormDataType>(initialValues?: TForm): InertiaFormProps<TForm>
export default function useForm<TForm extends FormDataType>(
rememberKey: string,
initialValues?: TForm,
): InertiaFormProps<TForm>
export default function useForm<TForm extends FormDataType>(
rememberKeyOrInitialValues?: string | TForm,
maybeInitialValues?: TForm,
): InertiaFormProps<TForm> {
const isMounted = useRef(null)
const rememberKey = typeof rememberKeyOrInitialValues === 'string' ? rememberKeyOrInitialValues : null
const [defaults, setDefaults] = useState(
(typeof rememberKeyOrInitialValues === 'string' ? maybeInitialValues : rememberKeyOrInitialValues) || ({} as TForm),
)
const cancelToken = useRef(null)
const recentlySuccessfulTimeoutId = useRef(null)
const [data, setData] = rememberKey ? useRemember(defaults, `${rememberKey}:data`) : useState(defaults)
const [errors, setErrors] = rememberKey
? useRemember({} as Partial<Record<keyof TForm, string>>, `${rememberKey}:errors`)
: useState({} as Partial<Record<keyof TForm, string>>)
const [hasErrors, setHasErrors] = useState(false)
const [processing, setProcessing] = useState(false)
const [progress, setProgress] = useState(null)
const [wasSuccessful, setWasSuccessful] = useState(false)
const [recentlySuccessful, setRecentlySuccessful] = useState(false)
const transform = useRef((data) => data)
useEffect(() => {
isMounted.current = true
return () => {
isMounted.current = false
}
}, [])
const submit = useCallback(
(method, url, options: VisitOptions = {}) => {
const _options = {
...options,
onCancelToken: (token) => {
cancelToken.current = token
if (options.onCancelToken) {
return options.onCancelToken(token)
}
},
onBefore: (visit) => {
setWasSuccessful(false)
setRecentlySuccessful(false)
clearTimeout(recentlySuccessfulTimeoutId.current)
if (options.onBefore) {
return options.onBefore(visit)
}
},
onStart: (visit) => {
setProcessing(true)
if (options.onStart) {
return options.onStart(visit)
}
},
onProgress: (event) => {
setProgress(event)
if (options.onProgress) {
return options.onProgress(event)
}
},
onSuccess: (page) => {
if (isMounted.current) {
setProcessing(false)
setProgress(null)
setErrors({})
setHasErrors(false)
setWasSuccessful(true)
setRecentlySuccessful(true)
recentlySuccessfulTimeoutId.current = setTimeout(() => {
if (isMounted.current) {
setRecentlySuccessful(false)
}
}, 2000)
}
if (options.onSuccess) {
return options.onSuccess(page)
}
},
onError: (errors) => {
if (isMounted.current) {
setProcessing(false)
setProgress(null)
setErrors(errors)
setHasErrors(true)
}
if (options.onError) {
return options.onError(errors)
}
},
onCancel: () => {
if (isMounted.current) {
setProcessing(false)
setProgress(null)
}
if (options.onCancel) {
return options.onCancel()
}
},
onFinish: (visit) => {
if (isMounted.current) {
setProcessing(false)
setProgress(null)
}
cancelToken.current = null
if (options.onFinish) {
return options.onFinish(visit)
}
},
}
if (method === 'delete') {
router.delete(url, { ..._options, data: transform.current(data) })
} else {
router[method](url, transform.current(data), _options)
}
},
[data, setErrors, transform],
)
const setDataFunction = useCallback(
(keyOrData: keyof TForm | Function | TForm, maybeValue?: TForm[keyof TForm]) => {
if (typeof keyOrData === 'string') {
setData((data) => ({ ...data, [keyOrData]: maybeValue }))
} else if (typeof keyOrData === 'function') {
setData((data) => keyOrData(data))
} else {
setData(keyOrData as TForm)
}
},
[setData],
)
const setDefaultsFunction = useCallback(
(fieldOrFields?: keyof TForm | Partial<TForm>, maybeValue?: FormDataConvertible) => {
if (typeof fieldOrFields === 'undefined') {
setDefaults(() => data)
} else {
setDefaults((defaults) => ({
...defaults,
...(typeof fieldOrFields === 'string' ? { [fieldOrFields]: maybeValue } : (fieldOrFields as TForm)),
}))
}
},
[data, setDefaults],
)
const reset = useCallback(
(...fields) => {
if (fields.length === 0) {
setData(defaults)
} else {
setData((data) =>
(Object.keys(defaults) as Array<keyof TForm>)
.filter((key) => fields.includes(key))
.reduce(
(carry, key) => {
carry[key] = defaults[key]
return carry
},
{ ...data },
),
)
}
},
[setData, defaults],
)
const setError = useCallback(
(fieldOrFields: keyof TForm | Record<keyof TForm, string>, maybeValue?: string) => {
setErrors((errors) => {
const newErrors = {
...errors,
...(typeof fieldOrFields === 'string'
? { [fieldOrFields]: maybeValue }
: (fieldOrFields as Record<keyof TForm, string>)),
}
setHasErrors(Object.keys(newErrors).length > 0)
return newErrors
})
},
[setErrors, setHasErrors],
)
const clearErrors = useCallback(
(...fields) => {
setErrors((errors) => {
const newErrors = (Object.keys(errors) as Array<keyof TForm>).reduce(
(carry, field) => ({
...carry,
...(fields.length > 0 && !fields.includes(field) ? { [field]: errors[field] } : {}),
}),
{},
)
setHasErrors(Object.keys(newErrors).length > 0)
return newErrors
})
},
[setErrors, setHasErrors],
)
const createSubmitMethod = (method) => (url, options) => {
submit(method, url, options)
}
const get = useCallback(createSubmitMethod('get'), [submit])
const post = useCallback(createSubmitMethod('post'), [submit])
const put = useCallback(createSubmitMethod('put'), [submit])
const patch = useCallback(createSubmitMethod('patch'), [submit])
const deleteMethod = useCallback(createSubmitMethod('delete'), [submit])
const cancel = useCallback(() => {
if (cancelToken.current) {
cancelToken.current.cancel()
}
}, [])
const transformFunction = useCallback((callback) => {
transform.current = callback
}, [])
return {
data,
setData: setDataFunction,
isDirty: !isEqual(data, defaults),
errors,
hasErrors,
processing,
progress,
wasSuccessful,
recentlySuccessful,
transform: transformFunction,
setDefaults: setDefaultsFunction,
reset,
setError,
clearErrors,
submit,
get,
post,
put,
patch,
delete: deleteMethod,
cancel,
}
}