forked from TanStack/form
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.ts
More file actions
456 lines (401 loc) · 11.3 KB
/
utils.ts
File metadata and controls
456 lines (401 loc) · 11.3 KB
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import type { FieldValidators } from './FieldApi'
import type { FormValidators } from './FormApi'
import type {
GlobalFormValidationError,
ValidationCause,
ValidationError,
ValidationSource,
} from './types'
export type UpdaterFn<TInput, TOutput = TInput> = (input: TInput) => TOutput
export type Updater<TInput, TOutput = TInput> =
| TOutput
| UpdaterFn<TInput, TOutput>
/**
* @private
*/
export function functionalUpdate<TInput, TOutput = TInput>(
updater: Updater<TInput, TOutput>,
input: TInput,
): TOutput {
return typeof updater === 'function'
? (updater as UpdaterFn<TInput, TOutput>)(input)
: updater
}
/**
* Get a value from an object using a path, including dot notation.
* @private
*/
export function getBy(obj: any, path: any) {
const pathObj = makePathArray(path)
return pathObj.reduce((current: any, pathPart: any) => {
if (current === null) return null
if (typeof current !== 'undefined') {
return current[pathPart]
}
return undefined
}, obj)
}
/**
* Set a value on an object using a path, including dot notation.
* @private
*/
export function setBy(obj: any, _path: any, updater: Updater<any>) {
const path = makePathArray(_path)
function doSet(parent?: any): any {
if (!path.length) {
return functionalUpdate(updater, parent)
}
const key = path.shift()
if (
typeof key === 'string' ||
(typeof key === 'number' && !Array.isArray(parent))
) {
if (typeof parent === 'object') {
if (parent === null) {
parent = {}
}
return {
...parent,
[key]: doSet(parent[key]),
}
}
return {
[key]: doSet(),
}
}
if (Array.isArray(parent) && typeof key === 'number') {
const prefix = parent.slice(0, key)
return [
...(prefix.length ? prefix : new Array(key)),
doSet(parent[key]),
...parent.slice(key + 1),
]
}
return [...new Array(key), doSet()]
}
return doSet(obj)
}
/**
* Delete a field on an object using a path, including dot notation.
* @private
*/
export function deleteBy(obj: any, _path: any) {
const path = makePathArray(_path)
function doDelete(parent: any): any {
if (!parent) return
if (path.length === 1) {
const finalPath = path[0]!
if (Array.isArray(parent) && typeof finalPath === 'number') {
return parent.filter((_, i) => i !== finalPath)
}
const { [finalPath]: remove, ...rest } = parent
return rest
}
const key = path.shift()
if (typeof key === 'string') {
if (typeof parent === 'object') {
return {
...parent,
[key]: doDelete(parent[key]),
}
}
}
if (typeof key === 'number') {
if (Array.isArray(parent)) {
if (key >= parent.length) {
return parent
}
const prefix = parent.slice(0, key)
return [
...(prefix.length ? prefix : new Array(key)),
doDelete(parent[key]),
...parent.slice(key + 1),
]
}
}
throw new Error('It seems we have created an infinite loop in deleteBy. ')
}
return doDelete(obj)
}
const reLineOfOnlyDigits = /^(\d+)$/gm
// the second dot must be in a lookahead or the engine
// will skip subsequent numbers (like foo.0.1.)
const reDigitsBetweenDots = /\.(\d+)(?=\.)/gm
const reStartWithDigitThenDot = /^(\d+)\./gm
const reDotWithDigitsToEnd = /\.(\d+$)/gm
const reMultipleDots = /\.{2,}/gm
const intPrefix = '__int__'
const intReplace = `${intPrefix}$1`
/**
* @private
*/
export function makePathArray(str: string | Array<string | number>) {
if (Array.isArray(str)) {
return [...str]
}
if (typeof str !== 'string') {
throw new Error('Path must be a string.')
}
return (
str
// Leading `[` may lead to wrong parsing down the line
// (Example: '[0][1]' should be '0.1', not '.0.1')
.replace(/(^\[)|]/gm, '')
.replace(/\[/g, '.')
.replace(reLineOfOnlyDigits, intReplace)
.replace(reDigitsBetweenDots, `.${intReplace}.`)
.replace(reStartWithDigitThenDot, `${intReplace}.`)
.replace(reDotWithDigitsToEnd, `.${intReplace}`)
.replace(reMultipleDots, '.')
.split('.')
.map((d) => {
if (d.indexOf(intPrefix) === 0) {
return parseInt(d.substring(intPrefix.length), 10)
}
return d
})
)
}
/**
* @private
*/
export function isNonEmptyArray(obj: any) {
return !(Array.isArray(obj) && obj.length === 0)
}
interface AsyncValidatorArrayPartialOptions<T> {
validators?: T
asyncDebounceMs?: number
}
/**
* @private
*/
export interface AsyncValidator<T> {
cause: ValidationCause
validate: T
debounceMs: number
}
/**
* @private
*/
export function getAsyncValidatorArray<T>(
cause: ValidationCause,
options: AsyncValidatorArrayPartialOptions<T>,
): T extends FieldValidators<any, any, any, any, any, any, any, any, any, any>
? Array<
AsyncValidator<T['onChangeAsync'] | T['onBlurAsync'] | T['onSubmitAsync']>
>
: T extends FormValidators<any, any, any, any, any, any, any, any>
? Array<
AsyncValidator<
T['onChangeAsync'] | T['onBlurAsync'] | T['onSubmitAsync']
>
>
: never {
const { asyncDebounceMs } = options
const {
onChangeAsync,
onBlurAsync,
onSubmitAsync,
onBlurAsyncDebounceMs,
onChangeAsyncDebounceMs,
} = (options.validators || {}) as
| FieldValidators<any, any, any, any, any, any, any, any, any, any>
| FormValidators<any, any, any, any, any, any, any, any>
const defaultDebounceMs = asyncDebounceMs ?? 0
const changeValidator = {
cause: 'change',
validate: onChangeAsync,
debounceMs: onChangeAsyncDebounceMs ?? defaultDebounceMs,
} as const
const blurValidator = {
cause: 'blur',
validate: onBlurAsync,
debounceMs: onBlurAsyncDebounceMs ?? defaultDebounceMs,
} as const
const submitValidator = {
cause: 'submit',
validate: onSubmitAsync,
debounceMs: 0,
} as const
const noopValidator = (
validator:
| typeof changeValidator
| typeof blurValidator
| typeof submitValidator,
) => ({ ...validator, debounceMs: 0 }) as const
switch (cause) {
case 'submit':
return [
noopValidator(changeValidator),
noopValidator(blurValidator),
submitValidator,
] as never
case 'blur':
return [blurValidator] as never
case 'change':
return [changeValidator] as never
case 'server':
default:
return [] as never
}
}
interface SyncValidatorArrayPartialOptions<T> {
validators?: T
}
/**
* @private
*/
export interface SyncValidator<T> {
cause: ValidationCause
validate: T
}
/**
* @private
*/
export function getSyncValidatorArray<T>(
cause: ValidationCause,
options: SyncValidatorArrayPartialOptions<T>,
): T extends FieldValidators<any, any, any, any, any, any, any, any, any, any>
? Array<
SyncValidator<T['onChange'] | T['onBlur'] | T['onSubmit'] | T['onMount']>
>
: T extends FormValidators<any, any, any, any, any, any, any, any>
? Array<
SyncValidator<
T['onChange'] | T['onBlur'] | T['onSubmit'] | T['onMount']
>
>
: never {
const { onChange, onBlur, onSubmit, onMount } = (options.validators || {}) as
| FieldValidators<any, any, any, any, any, any, any, any, any, any>
| FormValidators<any, any, any, any, any, any, any, any>
const changeValidator = { cause: 'change', validate: onChange } as const
const blurValidator = { cause: 'blur', validate: onBlur } as const
const submitValidator = { cause: 'submit', validate: onSubmit } as const
const mountValidator = { cause: 'mount', validate: onMount } as const
// Allows us to clear onServer errors
const serverValidator = {
cause: 'server',
validate: () => undefined,
} as const
switch (cause) {
case 'mount':
return [mountValidator] as never
case 'submit':
return [
changeValidator,
blurValidator,
submitValidator,
serverValidator,
] as never
case 'server':
return [serverValidator] as never
case 'blur':
return [blurValidator, serverValidator] as never
case 'change':
default:
return [changeValidator, serverValidator] as never
}
}
export const isGlobalFormValidationError = (
error: unknown,
): error is GlobalFormValidationError<unknown> => {
return !!error && typeof error === 'object' && 'fields' in error
}
export function evaluate<T>(objA: T, objB: T) {
if (Object.is(objA, objB)) {
return true
}
if (
typeof objA !== 'object' ||
objA === null ||
typeof objB !== 'object' ||
objB === null
) {
return false
}
if (objA instanceof Map && objB instanceof Map) {
if (objA.size !== objB.size) return false
for (const [k, v] of objA) {
if (!objB.has(k) || !Object.is(v, objB.get(k))) return false
}
return true
}
if (objA instanceof Set && objB instanceof Set) {
if (objA.size !== objB.size) return false
for (const v of objA) {
if (!objB.has(v)) return false
}
return true
}
const keysA = Object.keys(objA)
const keysB = Object.keys(objB)
if (keysA.length !== keysB.length) {
return false
}
for (const key of keysA) {
// performs recursive search down the object tree
if (
!keysB.includes(key) ||
!evaluate(objA[key as keyof T], objB[key as keyof T])
) {
return false
}
}
return true
}
/**
* Determines the logic for determining the error source and value to set on the field meta within the form level sync/async validation.
* @private
*/
export const determineFormLevelErrorSourceAndValue = ({
newFormValidatorError,
isPreviousErrorFromFormValidator,
previousErrorValue,
}: {
newFormValidatorError: ValidationError
isPreviousErrorFromFormValidator: boolean
previousErrorValue: ValidationError
}): {
newErrorValue: ValidationError
newSource: ValidationSource | undefined
} => {
// All falsy values are not considered errors
if (newFormValidatorError) {
return { newErrorValue: newFormValidatorError, newSource: 'form' }
}
// Clears form level error since it's now stale
if (isPreviousErrorFromFormValidator) {
return { newErrorValue: undefined, newSource: undefined }
}
// At this point, we have a preivous error which must have been set by the field validator, keep as is
if (previousErrorValue) {
return { newErrorValue: previousErrorValue, newSource: 'field' }
}
// No new or previous error, clear the error
return { newErrorValue: undefined, newSource: undefined }
}
/**
* Determines the logic for determining the error source and value to set on the field meta within the field level sync/async validation.
* @private
*/
export const determineFieldLevelErrorSourceAndValue = ({
formLevelError,
fieldLevelError,
}: {
formLevelError: ValidationError
fieldLevelError: ValidationError
}): {
newErrorValue: ValidationError
newSource: ValidationSource | undefined
} => {
// At field level, we prioritize the field level error
if (fieldLevelError) {
return { newErrorValue: fieldLevelError, newSource: 'field' }
}
// If there is no field level error, and there is a form level error, we set the form level error
if (formLevelError) {
return { newErrorValue: formLevelError, newSource: 'form' }
}
return { newErrorValue: undefined, newSource: undefined }
}