|
| 1 | +import {Config, RequestMethod, SimpleValidationErrors, toSimpleValidationErrors, ValidationConfig} from 'laravel-precognition' |
| 2 | +import { useForm as useVueForm } from 'laravel-precognition-vue' |
| 3 | +import { useForm as useInertiaForm } from '@inertiajs/vue3' |
| 4 | + |
| 5 | +export const useForm = <Data extends Record<string, unknown>>(method: RequestMethod, url: string, inputs: Data, config: ValidationConfig = {}): any => { |
| 6 | + /** |
| 7 | + * The Inertia form. |
| 8 | + */ |
| 9 | + const inertiaForm = useInertiaForm(inputs) |
| 10 | + |
| 11 | + /** |
| 12 | + * The Vue form. |
| 13 | + */ |
| 14 | + const vueForm = useVueForm(method, url, inputs, config) |
| 15 | + |
| 16 | + /** |
| 17 | + * Setup event listeners. |
| 18 | + */ |
| 19 | + vueForm.validator().on('errorsChanged', () => inertiaForm.clearErrors().setError( |
| 20 | + // @ts-expect-error |
| 21 | + toSimpleValidationErrors(vueForm.validator().errors()) |
| 22 | + )) |
| 23 | + |
| 24 | + /** |
| 25 | + * The Inertia submit function. |
| 26 | + */ |
| 27 | + const inertiaSubmit = inertiaForm.submit.bind(inertiaForm) |
| 28 | + |
| 29 | + /** |
| 30 | + * Patch the form. |
| 31 | + */ |
| 32 | + return Object.assign(inertiaForm, { |
| 33 | + processing: vueForm.processing, |
| 34 | + validating: vueForm.validating, |
| 35 | + touched: vueForm.touched, |
| 36 | + valid: vueForm.valid, |
| 37 | + invalid: vueForm.invalid, |
| 38 | + validate: vueForm.validate, |
| 39 | + setValidationTimeout: vueForm.setValidationTimeout, |
| 40 | + submit: (submitMethod: RequestMethod|Config = {}, submitUrl?: string, submitOptions?: any): void => { |
| 41 | + const isPatchedCall = typeof submitMethod !== 'string' |
| 42 | + |
| 43 | + const options = { |
| 44 | + ...isPatchedCall |
| 45 | + ? submitMethod |
| 46 | + : submitOptions, |
| 47 | + onError: (errors: SimpleValidationErrors): any => { |
| 48 | + vueForm.validator().setErrors(errors) |
| 49 | + |
| 50 | + if (submitOptions.onError) { |
| 51 | + return submitOptions.onError(errors) |
| 52 | + } |
| 53 | + }, |
| 54 | + } |
| 55 | + |
| 56 | + inertiaSubmit( |
| 57 | + isPatchedCall ? method : submitMethod, |
| 58 | + // @ts-expect-error |
| 59 | + (isPatchedCall ? url : submitUrl), |
| 60 | + options |
| 61 | + ) |
| 62 | + } |
| 63 | + }) |
| 64 | +} |
0 commit comments