Skip to content
Source
Sign inSign up
TanStack/form
Open History to see the last commit

utils.ts

635 lines14.0 KB

1import { liteThrottle } from '@tanstack/pacer-lite'
2import { formEventClient } from './EventClient'
3import type { ValidationLogicProps } from './ValidationLogic'
4import type { FieldValidators } from './FieldApi'
5import type { AnyFormApi, FormValidators } from './FormApi'
6import type {
7 GlobalFormValidationError,
8 ValidationCause,
9 ValidationError,
10 ValidationSource,
11} from './types'
12​
13export type UpdaterFn<TInput, TOutput = TInput> = (input: TInput) => TOutput
14​
15export type Updater<TInput, TOutput = TInput> =
16 | TOutput
17 | UpdaterFn<TInput, TOutput>
18​
19/**
20 * @private
21 */
22export function functionalUpdate<TInput, TOutput = TInput>(
23 updater: Updater<TInput, TOutput>,
24 input: TInput,
25): TOutput {
26 return typeof updater === 'function'
27 ? (updater as UpdaterFn<TInput, TOutput>)(input)
28 : updater
30​
31/**
32 * Get a value from an object using a path, including dot notation.
33 * @private
34 */
35export function getBy(obj: unknown, path: string | (string | number)[]): any {
36 const pathObj = makePathArray(path)
37 return pathObj.reduce((current: any, pathPart) => {
38 if (current === null) return null
39 if (typeof current !== 'undefined') {
40 return current[pathPart]
41 }
42 return undefined
43 }, obj)
45​
46/**
47 * Set a value on an object using a path, including dot notation.
48 * @private
49 */
50export function setBy(obj: any, _path: any, updater: Updater<any>) {
51 const path = makePathArray(_path)
52​
53 function doSet(parent?: any): any {
54 if (!path.length) {
55 return functionalUpdate(updater, parent)
56 }
57​
58 const key = path.shift()
59​
60 if (
61 typeof key === 'string' ||
62 (typeof key === 'number' && !Array.isArray(parent))
63 ) {
64 if (typeof parent === 'object') {
65 if (parent === null) {
66 parent = {}
67 }
68 return {
69 ...parent,
70 [key]: doSet(parent[key]),
71 }
72 }
73 return {
74 [key]: doSet(),
75 }
76 }
77​
78 if (Array.isArray(parent) && typeof key === 'number') {
79 const prefix = parent.slice(0, key)
80 return [
81 ...(prefix.length ? prefix : new Array(key)),
82 doSet(parent[key]),
83 ...parent.slice(key + 1),
84 ]
85 }
86 return [...new Array(key), doSet()]
87 }
88​
89 return doSet(obj)
91​
92/**
93 * Delete a field on an object using a path, including dot notation.
94 * @private
95 */
96export function deleteBy(obj: any, _path: any) {
97 const path = makePathArray(_path)
98​
99 function doDelete(parent: any): any {
100 if (!parent) return
101 if (path.length === 1) {
102 const finalPath = path[0]!
103 if (Array.isArray(parent) && typeof finalPath === 'number') {
104 return parent.filter((_, i) => i !== finalPath)
105 }
106 const { [finalPath]: remove, ...rest } = parent
107 return rest
108 }
109​
110 const key = path.shift()
111​
112 if (
113 typeof key === 'string' ||
114 (typeof key === 'number' && !Array.isArray(parent))
115 ) {
116 if (typeof parent === 'object') {
117 return {
118 ...parent,
119 [key]: doDelete(parent[key]),
120 }
121 }
122 }
123​
124 if (typeof key === 'number') {
125 if (Array.isArray(parent)) {
126 if (key >= parent.length) {
127 return parent
128 }
129 const prefix = parent.slice(0, key)
130 return [
131 ...(prefix.length ? prefix : new Array(key)),
132 doDelete(parent[key]),
133 ...parent.slice(key + 1),
134 ]
135 }
136 }
137​
138 throw new Error('It seems we have created an infinite loop in deleteBy. ')
139 }
140​
141 return doDelete(obj)
143​
144/**
145 * @private
146 */
147export function makePathArray(str: string | Array<string | number>) {
148 if (Array.isArray(str)) {
149 return [...str]
150 }
151​
152 if (typeof str !== 'string') {
153 throw new Error('Path must be a string.')
154 }
155​
156 // Leading `[` may lead to wrong parsing (e.g. '[0][1]' β†’ '0.1', not '.0.1')
157 return str
158 .replace(/(^\[)|]/g, '')
159 .replace(/\[/g, '.')
160 .replace(/\.{2,}/g, '.')
161 .split('.')
162 .map((segment) => {
163 const num = parseInt(segment, 10)
164 return String(num) === segment ? num : segment
165 })
167​
168/**
169 * @private
170 */
171export function concatenatePaths(path1: string, path2: string): string {
172 if (path1.length === 0) return path2
173 if (path2.length === 0) return path1
174​
175 if (path2.startsWith('[')) {
176 return path1 + path2
177 }
178​
179 // In cases where parent and child withFieldGroup forms are both nested
180 if (path2.startsWith('.')) {
181 return path1 + path2
182 }
183​
184 return `${path1}.${path2}`
186​
187/**
188 * @private
189 */
190export function isNonEmptyArray(obj: any) {
191 return !(Array.isArray(obj) && obj.length === 0)
193​
194interface AsyncValidatorArrayPartialOptions<T> {
195 validators?: T
196 asyncDebounceMs?: number
198​
199/**
200 * @private
201 */
202export interface AsyncValidator<T> {
203 cause: ValidationCause
204 validate: T
205 debounceMs: number
207​
208interface SyncValidatorArrayPartialOptions<T> {
209 validators?: T
211​
212/**
213 * @private
214 */
215export interface SyncValidator<T> {
216 cause: ValidationCause
217 validate: T
219​
220/**
221 * @private
222 */
223export function getSyncValidatorArray<T>(
224 cause: ValidationCause,
225 options: SyncValidatorArrayPartialOptions<T> & {
226 validationLogic?: any
227 form?: any
228 },
229): T extends FieldValidators<
230 any,
231 any,
232 any,
233 any,
234 any,
235 any,
236 any,
237 any,
238 any,
239 any,
240 any,
241 any
243 ? Array<
244 SyncValidator<
245 | T['onChange']
246 | T['onBlur']
247 | T['onSubmit']
248 | T['onMount']
249 | T['onDynamic']
250 >
251 >
252 : T extends FormValidators<any, any, any, any, any, any, any, any, any, any>
253 ? Array<
254 SyncValidator<
255 | T['onChange']
256 | T['onBlur']
257 | T['onSubmit']
258 | T['onMount']
259 | T['onDynamic']
260 >
261 >
262 : never {
263 const runValidation = (
264 props: Parameters<ValidationLogicProps['runValidation']>[0],
265 ) => {
266 return props.validators.filter(Boolean).map((validator) => {
267 return {
268 cause: validator!.cause,
269 validate: validator!.fn,
270 }
271 })
272 }
273​
274 return options.validationLogic({
275 form: options.form,
276 validators: options.validators,
277 event: { type: cause, async: false },
278 runValidation,
279 })
281​
282/**
283 * @private
284 */
285export function getAsyncValidatorArray<T>(
286 cause: ValidationCause,
287 options: AsyncValidatorArrayPartialOptions<T> & {
288 validationLogic?: any
289 form?: any
290 },
291): T extends FieldValidators<
292 any,
293 any,
294 any,
295 any,
296 any,
297 any,
298 any,
299 any,
300 any,
301 any,
302 any,
303 any
305 ? Array<
306 AsyncValidator<
307 | T['onChangeAsync']
308 | T['onBlurAsync']
309 | T['onSubmitAsync']
310 | T['onDynamicAsync']
311 >
312 >
313 : T extends FormValidators<any, any, any, any, any, any, any, any, any, any>
314 ? Array<
315 AsyncValidator<
316 | T['onChangeAsync']
317 | T['onBlurAsync']
318 | T['onSubmitAsync']
319 | T['onDynamicAsync']
320 >
321 >
322 : never {
323 const { asyncDebounceMs } = options
324 const {
325 onBlurAsyncDebounceMs,
326 onChangeAsyncDebounceMs,
327 onDynamicAsyncDebounceMs,
328 } = (options.validators || {}) as
329 | FieldValidators<
330 any,
331 any,
332 any,
333 any,
334 any,
335 any,
336 any,
337 any,
338 any,
339 any,
340 any,
341 any
342 >
343 | FormValidators<any, any, any, any, any, any, any, any, any, any>
344​
345 const defaultDebounceMs = asyncDebounceMs ?? 0
346​
347 const runValidation = (
348 props: Parameters<ValidationLogicProps['runValidation']>[0],
349 ) => {
350 return props.validators.filter(Boolean).map((validator) => {
351 const validatorCause = validator?.cause || cause
352​
353 let debounceMs = defaultDebounceMs
354​
355 switch (validatorCause) {
356 case 'change':
357 debounceMs = onChangeAsyncDebounceMs ?? defaultDebounceMs
358 break
359 case 'blur':
360 debounceMs = onBlurAsyncDebounceMs ?? defaultDebounceMs
361 break
362 case 'dynamic':
363 debounceMs = onDynamicAsyncDebounceMs ?? defaultDebounceMs
364 break
365 case 'submit':
366 debounceMs = 0 // submit validators are always run immediately
367 break
368 default:
369 break
370 }
371​
372 if (cause === 'submit') {
373 debounceMs = 0
374 }
375​
376 return {
377 cause: validatorCause,
378 validate: validator!.fn,
379 debounceMs: debounceMs,
380 }
381 })
382 }
383​
384 return options.validationLogic({
385 form: options.form,
386 validators: options.validators,
387 event: { type: cause, async: true },
388 runValidation,
389 })
391​
392export const isGlobalFormValidationError = (
393 error: unknown,
394): error is GlobalFormValidationError<unknown> => {
395 return !!error && typeof error === 'object' && 'fields' in error
397​
398export function evaluate<T>(objA: T, objB: T) {
399 if (Object.is(objA, objB)) {
400 return true
401 }
402​
403 if (
404 typeof objA !== 'object' ||
405 objA === null ||
406 typeof objB !== 'object' ||
407 objB === null
408 ) {
409 return false
410 }
411​
412 if (objA instanceof Date && objB instanceof Date) {
413 return objA.getTime() === objB.getTime()
414 }
415​
416 if (objA instanceof Map && objB instanceof Map) {
417 if (objA.size !== objB.size) return false
418 for (const [k, v] of objA) {
419 if (!objB.has(k) || !Object.is(v, objB.get(k))) return false
420 }
421 return true
422 }
423​
424 if (objA instanceof Set && objB instanceof Set) {
425 if (objA.size !== objB.size) return false
426 for (const v of objA) {
427 if (!objB.has(v)) return false
428 }
429 return true
430 }
431​
432 const keysA = Object.keys(objA)
433 const keysB = Object.keys(objB)
434​
435 if (keysA.length !== keysB.length) {
436 return false
437 }
438​
439 for (const key of keysA) {
440 // performs recursive search down the object tree
441​
442 if (
443 !keysB.includes(key) ||
444 !evaluate(objA[key as keyof T], objB[key as keyof T])
445 ) {
446 return false
447 }
448 }
449​
450 return true
452​
453/**
454 * Determines the logic for determining the error source and value to set on the field meta within the form level sync/async validation.
455 * @private
456 */
457export const determineFormLevelErrorSourceAndValue = ({
458 newFormValidatorError,
459 isPreviousErrorFromFormValidator,
460 previousErrorValue,
461}: {
462 newFormValidatorError: ValidationError
463 isPreviousErrorFromFormValidator: boolean
464 previousErrorValue: ValidationError
465}): {
466 newErrorValue: ValidationError
467 newSource: ValidationSource | undefined
468} => {
469 // All falsy values are not considered errors
470 if (newFormValidatorError) {
471 return { newErrorValue: newFormValidatorError, newSource: 'form' }
472 }
473​
474 // Clears form level error since it's now stale
475 if (isPreviousErrorFromFormValidator) {
476 return { newErrorValue: undefined, newSource: undefined }
477 }
478​
479 // At this point, we have a preivous error which must have been set by the field validator, keep as is
480 if (previousErrorValue) {
481 return { newErrorValue: previousErrorValue, newSource: 'field' }
482 }
483​
484 // No new or previous error, clear the error
485 return { newErrorValue: undefined, newSource: undefined }
487​
488/**
489 * Determines the logic for determining the error source and value to set on the field meta within the field level sync/async validation.
490 * @private
491 */
492export const determineFieldLevelErrorSourceAndValue = ({
493 formLevelError,
494 fieldLevelError,
495}: {
496 formLevelError: ValidationError
497 fieldLevelError: ValidationError
498}): {
499 newErrorValue: ValidationError
500 newSource: ValidationSource | undefined
501} => {
502 // At field level, we prioritize the field level error
503 if (fieldLevelError) {
504 return { newErrorValue: fieldLevelError, newSource: 'field' }
505 }
506​
507 // If there is no field level error, and there is a form level error, we set the form level error
508 if (formLevelError) {
509 return { newErrorValue: formLevelError, newSource: 'form' }
510 }
511​
512 return { newErrorValue: undefined, newSource: undefined }
514​
515export function createFieldMap<T>(values: Readonly<T>): { [K in keyof T]: K } {
516 const output: { [K in keyof T]: K } = {} as any
517​
518 for (const key in values) {
519 output[key] = key
520 }
521​
522 return output
524​
525/**
526 * Merge the first parameter with the given overrides.
527 * @private
528 */
529export function mergeOpts<T>(
530 originalOpts: T | undefined | null,
531 overrides: T,
532): T {
533 if (originalOpts === undefined || originalOpts === null) {
534 return overrides
535 }
536​
537 return { ...originalOpts, ...overrides }
539​
540/*
541/ credit is due to https://github.com/lukeed/uuid for this code, with current npm
542/ attacks we didn't feel comfortable installing directly from npm. But big appreciation
543/ from the TanStack Form team <3.
544*/
545​
546let IDX = 256
547const HEX: string[] = []
548let BUFFER: number[] | undefined
549​
550while (IDX--) {
551 HEX[IDX] = (IDX + 256).toString(16).substring(1)
553​
554export function uuid(): string {
555 let i = 0
556 let num: number
557 let out = ''
558​
559 if (!BUFFER || IDX + 16 > 256) {
560 BUFFER = new Array<number>(256)
561 i = 256
562 while (i--) {
563 BUFFER[i] = (256 * Math.random()) | 0
564 }
565 i = 0
566 IDX = 0
567 }
568​
569 for (; i < 16; i++) {
570 num = BUFFER[IDX + i] as number
571 if (i === 6) out += HEX[(num & 15) | 64]
572 else if (i === 8) out += HEX[(num & 63) | 128]
573 else out += HEX[num]
574​
575 if (i & 1 && i > 1 && i < 11) out += '-'
576 }
577​
578 IDX++
579 return out
581​
582export const throttleFormState = liteThrottle(
583 (form: AnyFormApi) =>
584 formEventClient.emit('form-state', {
585 id: form.formId,
586 state: form.store.state,
587 }),
588 {
589 wait: 300,
590 },
592​
593// Do not use a serialize and deserialize method like JSON.stringify/parse
594// as that will drop functions, dates, undefined, Infinity, NaN, etc.
595export function deepCopy<T>(obj: T): T {
596 if (obj === null || typeof obj !== 'object') {
597 return obj
598 }
599​
600 if (obj instanceof Date) {
601 return new Date(obj.getTime()) as any
602 }
603​
604 if (Array.isArray(obj)) {
605 const arrCopy = [] as any[]
606 for (let i = 0; i < obj.length; i++) {
607 arrCopy[i] = deepCopy(obj[i])
608 }
609 return arrCopy as any
610 }
611​
612 if (obj instanceof Map) {
613 const mapCopy = new Map()
614 obj.forEach((value, key) => {
615 mapCopy.set(key, deepCopy(value))
616 })
617 return mapCopy as any
618 }
619​
620 if (obj instanceof Set) {
621 const setCopy = new Set()
622 obj.forEach((value) => {
623 setCopy.add(deepCopy(value))
624 })
625 return setCopy as any
626 }
627​
628 const copy: { [key: string]: any } = {}
629 for (const key in obj) {
630 if (Object.prototype.hasOwnProperty.call(obj, key)) {
631 copy[key] = deepCopy((obj as any)[key])
632 }
633 }
634 return copy as T