|
| 1 | +import type { |
| 2 | + ActiveVisit, |
| 3 | + Errors, |
| 4 | + FormDataConvertible, |
| 5 | + Method, |
| 6 | + Page, |
| 7 | + PendingVisit, |
| 8 | + Progress, |
| 9 | + RequestPayload, |
| 10 | + VisitOptions, |
| 11 | +} from '@inertiajs/core' |
| 12 | +import { router } from '@inertiajs/core' |
| 13 | +import type { AxiosProgressEvent } from 'axios' |
| 14 | +import cloneDeep from 'lodash.clonedeep' |
| 15 | +import isEqual from 'lodash.isequal' |
| 16 | +import { writable, type Writable } from 'svelte/store' |
| 17 | + |
| 18 | +type FormDataType = Record<string, FormDataConvertible> |
| 19 | + |
| 20 | +interface InertiaFormProps<TForm extends FormDataType> { |
| 21 | + isDirty: boolean |
| 22 | + errors: Partial<Record<keyof TForm, string>> |
| 23 | + hasErrors: boolean |
| 24 | + progress: Progress | null |
| 25 | + wasSuccessful: boolean |
| 26 | + recentlySuccessful: boolean |
| 27 | + processing: boolean |
| 28 | + setStore(data: TForm): void |
| 29 | + setStore(key: keyof TForm, value?: FormDataConvertible): void |
| 30 | + data(): TForm |
| 31 | + transform(callback: (data: TForm) => object): this |
| 32 | + defaults(): this |
| 33 | + defaults(fields: Partial<TForm>): this |
| 34 | + defaults(field?: keyof TForm, value?: FormDataConvertible): this |
| 35 | + reset(...fields: (keyof TForm)[]): this |
| 36 | + clearErrors(...fields: (keyof TForm)[]): this |
| 37 | + setError(field: keyof TForm, value: string): this |
| 38 | + setError(errors: Errors): this |
| 39 | + submit(method: Method, url: string, options?: Partial<VisitOptions>): void |
| 40 | + get(url: string, options?: Partial<VisitOptions>): void |
| 41 | + post(url: string, options?: Partial<VisitOptions>): void |
| 42 | + put(url: string, options?: Partial<VisitOptions>): void |
| 43 | + patch(url: string, options?: Partial<VisitOptions>): void |
| 44 | + delete(url: string, options?: Partial<VisitOptions>): void |
| 45 | + cancel(): void |
| 46 | +} |
| 47 | + |
| 48 | +export type InertiaForm<TForm extends FormDataType> = InertiaFormProps<TForm> & TForm |
| 49 | + |
| 50 | +export default function useForm<TForm extends FormDataType>(data: TForm | (() => TForm)): Writable<InertiaForm<TForm>> |
| 51 | +export default function useForm<TForm extends FormDataType>( |
| 52 | + rememberKey: string, |
| 53 | + data: TForm | (() => TForm), |
| 54 | +): Writable<InertiaForm<TForm>> |
| 55 | +export default function useForm<TForm extends FormDataType>( |
| 56 | + rememberKeyOrData: string | TForm | (() => TForm), |
| 57 | + maybeData?: TForm | (() => TForm), |
| 58 | +): Writable<InertiaForm<TForm>> { |
| 59 | + const rememberKey = typeof rememberKeyOrData === 'string' ? rememberKeyOrData : null |
| 60 | + const data = typeof rememberKeyOrData === 'string' ? maybeData : rememberKeyOrData |
| 61 | + const restored = rememberKey |
| 62 | + ? (router.restore(rememberKey) as { data: TForm; errors: Record<keyof TForm, string> }) |
| 63 | + : null |
| 64 | + let defaults = typeof data === 'function' ? cloneDeep(data()) : cloneDeep(data) |
| 65 | + let cancelToken: { cancel: () => void } | null = null |
| 66 | + let recentlySuccessfulTimeoutId: ReturnType<typeof setTimeout> | null = null |
| 67 | + let transform = (data: TForm) => data as object |
| 68 | + |
| 69 | + const store = writable<InertiaForm<TForm>>({ |
| 70 | + ...(restored ? restored.data : data), |
| 71 | + isDirty: false, |
| 72 | + errors: restored ? restored.errors : {}, |
| 73 | + hasErrors: false, |
| 74 | + progress: null, |
| 75 | + wasSuccessful: false, |
| 76 | + recentlySuccessful: false, |
| 77 | + processing: false, |
| 78 | + setStore(keyOrData, maybeData = undefined) { |
| 79 | + store.update((store) => { |
| 80 | + return Object.assign(store, typeof keyOrData === 'string' ? { [keyOrData]: maybeData } : keyOrData) |
| 81 | + }) |
| 82 | + }, |
| 83 | + data() { |
| 84 | + return Object.keys((typeof data === 'function' ? data() : data) as FormDataType).reduce((carry, key) => { |
| 85 | + carry[key] = this[key] |
| 86 | + return carry |
| 87 | + }, {} as FormDataType) as TForm |
| 88 | + }, |
| 89 | + transform(callback) { |
| 90 | + transform = callback |
| 91 | + |
| 92 | + return this |
| 93 | + }, |
| 94 | + defaults(fieldOrFields?: keyof TForm | Record<keyof TForm, string>, maybeValue?: string) { |
| 95 | + if (typeof fieldOrFields === 'undefined') { |
| 96 | + defaults = Object.assign(defaults, cloneDeep(this.data())) |
| 97 | + |
| 98 | + return this |
| 99 | + } |
| 100 | + |
| 101 | + defaults = Object.assign( |
| 102 | + cloneDeep(defaults), |
| 103 | + cloneDeep(typeof fieldOrFields === 'string' ? { [fieldOrFields]: maybeValue } : fieldOrFields), |
| 104 | + ) |
| 105 | + |
| 106 | + return this |
| 107 | + }, |
| 108 | + reset(...fields) { |
| 109 | + const resolvedData = typeof data === 'object' ? cloneDeep(defaults) : cloneDeep(data!()) |
| 110 | + const clonedData = cloneDeep(resolvedData) |
| 111 | + if (fields.length === 0) { |
| 112 | + this.setStore(clonedData) |
| 113 | + } else { |
| 114 | + this.setStore( |
| 115 | + Object.keys(clonedData) |
| 116 | + .filter((key) => fields.includes(key)) |
| 117 | + .reduce((carry, key) => { |
| 118 | + carry[key] = clonedData[key] |
| 119 | + return carry |
| 120 | + }, {} as FormDataType) as TForm, |
| 121 | + ) |
| 122 | + } |
| 123 | + |
| 124 | + return this |
| 125 | + }, |
| 126 | + setError(fieldOrFields: keyof TForm | Errors, maybeValue?: string) { |
| 127 | + this.setStore('errors', { |
| 128 | + ...this.errors, |
| 129 | + ...((typeof fieldOrFields === 'string' ? { [fieldOrFields]: maybeValue } : fieldOrFields) as any), |
| 130 | + }) |
| 131 | + |
| 132 | + return this |
| 133 | + }, |
| 134 | + clearErrors(...fields) { |
| 135 | + this.setStore( |
| 136 | + 'errors', |
| 137 | + Object.keys(this.errors).reduce( |
| 138 | + (carry, field) => ({ |
| 139 | + ...carry, |
| 140 | + ...(fields.length > 0 && !fields.includes(field) ? { [field]: this.errors[field] } : {}), |
| 141 | + }), |
| 142 | + {}, |
| 143 | + ), |
| 144 | + ) |
| 145 | + |
| 146 | + return this |
| 147 | + }, |
| 148 | + submit(method, url, options = {}) { |
| 149 | + const data = transform(this.data()) as RequestPayload |
| 150 | + const _options: Omit<VisitOptions, 'method'> = { |
| 151 | + ...options, |
| 152 | + onCancelToken: (token: { cancel: () => void }) => { |
| 153 | + cancelToken = token |
| 154 | + |
| 155 | + if (options.onCancelToken) { |
| 156 | + return options.onCancelToken(token) |
| 157 | + } |
| 158 | + }, |
| 159 | + onBefore: (visit: PendingVisit) => { |
| 160 | + this.setStore('wasSuccessful', false) |
| 161 | + this.setStore('recentlySuccessful', false) |
| 162 | + if (recentlySuccessfulTimeoutId) { |
| 163 | + clearTimeout(recentlySuccessfulTimeoutId) |
| 164 | + } |
| 165 | + |
| 166 | + if (options.onBefore) { |
| 167 | + return options.onBefore(visit) |
| 168 | + } |
| 169 | + }, |
| 170 | + onStart: (visit: PendingVisit) => { |
| 171 | + this.setStore('processing', true) |
| 172 | + |
| 173 | + if (options.onStart) { |
| 174 | + return options.onStart(visit) |
| 175 | + } |
| 176 | + }, |
| 177 | + onProgress: (event?: AxiosProgressEvent) => { |
| 178 | + this.setStore('progress', event as any) |
| 179 | + |
| 180 | + if (options.onProgress) { |
| 181 | + return options.onProgress(event) |
| 182 | + } |
| 183 | + }, |
| 184 | + onSuccess: async (page: Page) => { |
| 185 | + this.setStore('processing', false) |
| 186 | + this.setStore('progress', null) |
| 187 | + this.clearErrors() |
| 188 | + this.setStore('wasSuccessful', true) |
| 189 | + this.setStore('recentlySuccessful', true) |
| 190 | + recentlySuccessfulTimeoutId = setTimeout(() => this.setStore('recentlySuccessful', false), 2000) |
| 191 | + |
| 192 | + if (options.onSuccess) { |
| 193 | + return options.onSuccess(page) |
| 194 | + } |
| 195 | + }, |
| 196 | + onError: (errors: Errors) => { |
| 197 | + this.setStore('processing', false) |
| 198 | + this.setStore('progress', null) |
| 199 | + this.clearErrors().setError(errors) |
| 200 | + |
| 201 | + if (options.onError) { |
| 202 | + return options.onError(errors) |
| 203 | + } |
| 204 | + }, |
| 205 | + onCancel: () => { |
| 206 | + this.setStore('processing', false) |
| 207 | + this.setStore('progress', null) |
| 208 | + |
| 209 | + if (options.onCancel) { |
| 210 | + return options.onCancel() |
| 211 | + } |
| 212 | + }, |
| 213 | + onFinish: (visit: ActiveVisit) => { |
| 214 | + this.setStore('processing', false) |
| 215 | + this.setStore('progress', null) |
| 216 | + cancelToken = null |
| 217 | + |
| 218 | + if (options.onFinish) { |
| 219 | + return options.onFinish(visit) |
| 220 | + } |
| 221 | + }, |
| 222 | + } |
| 223 | + |
| 224 | + if (method === 'delete') { |
| 225 | + router.delete(url, { ..._options, data }) |
| 226 | + } else { |
| 227 | + router[method](url, data, _options) |
| 228 | + } |
| 229 | + }, |
| 230 | + get(url, options) { |
| 231 | + this.submit('get', url, options) |
| 232 | + }, |
| 233 | + post(url, options) { |
| 234 | + this.submit('post', url, options) |
| 235 | + }, |
| 236 | + put(url, options) { |
| 237 | + this.submit('put', url, options) |
| 238 | + }, |
| 239 | + patch(url, options) { |
| 240 | + this.submit('patch', url, options) |
| 241 | + }, |
| 242 | + delete(url, options) { |
| 243 | + this.submit('delete', url, options) |
| 244 | + }, |
| 245 | + cancel() { |
| 246 | + cancelToken?.cancel() |
| 247 | + }, |
| 248 | + } as InertiaForm<TForm>) |
| 249 | + |
| 250 | + store.subscribe((form) => { |
| 251 | + if (form.isDirty === isEqual(form.data(), defaults)) { |
| 252 | + form.setStore('isDirty', !form.isDirty) |
| 253 | + } |
| 254 | + |
| 255 | + const hasErrors = Object.keys(form.errors).length > 0 |
| 256 | + if (form.hasErrors !== hasErrors) { |
| 257 | + form.setStore('hasErrors', !form.hasErrors) |
| 258 | + } |
| 259 | + |
| 260 | + if (rememberKey) { |
| 261 | + router.remember({ data: form.data(), errors: form.errors }, rememberKey) |
| 262 | + } |
| 263 | + }) |
| 264 | + |
| 265 | + return store as Writable<InertiaForm<TForm>> |
| 266 | +} |
0 commit comments