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

utils.ts

310 lines7.2 KB

1import type { ValidationCause } from './types'
2import type { FormValidators } from './FormApi'
3import type { FieldValidators } from './FieldApi'
4​
5export type UpdaterFn<TInput, TOutput = TInput> = (input: TInput) => TOutput
6​
7export type Updater<TInput, TOutput = TInput> =
8 | TOutput
9 | UpdaterFn<TInput, TOutput>
10​
11/**
12 * @private
13 */
14export function functionalUpdate<TInput, TOutput = TInput>(
15 updater: Updater<TInput, TOutput>,
16 input: TInput,
17): TOutput {
18 return typeof updater === 'function'
19 ? (updater as UpdaterFn<TInput, TOutput>)(input)
20 : updater
22​
23/**
24 * Get a value from an object using a path, including dot notation.
25 * @private
26 */
27export function getBy(obj: any, path: any) {
28 const pathObj = makePathArray(path)
29 return pathObj.reduce((current: any, pathPart: any) => {
30 if (current === null) return null
31 if (typeof current !== 'undefined') {
32 return current[pathPart]
33 }
34 return undefined
35 }, obj)
37​
38/**
39 * Set a value on an object using a path, including dot notation.
40 * @private
41 */
42export function setBy(obj: any, _path: any, updater: Updater<any>) {
43 const path = makePathArray(_path)
44​
45 function doSet(parent?: any): any {
46 if (!path.length) {
47 return functionalUpdate(updater, parent)
48 }
49​
50 const key = path.shift()
51​
52 if (typeof key === 'string') {
53 if (typeof parent === 'object') {
54 if (parent === null) {
55 parent = {}
56 }
57 return {
58 ...parent,
59 [key]: doSet(parent[key]),
60 }
61 }
62 return {
63 [key]: doSet(),
64 }
65 }
66​
67 if (Array.isArray(parent) && key !== undefined) {
68 const prefix = parent.slice(0, key)
69 return [
70 ...(prefix.length ? prefix : new Array(key)),
71 doSet(parent[key]),
72 ...parent.slice(key + 1),
73 ]
74 }
75 return [...new Array(key), doSet()]
76 }
77​
78 return doSet(obj)
80​
81/**
82 * Delete a field on an object using a path, including dot notation.
83 * @private
84 */
85export function deleteBy(obj: any, _path: any) {
86 const path = makePathArray(_path)
87​
88 function doDelete(parent: any): any {
89 if (!parent) return
90 if (path.length === 1) {
91 const finalPath = path[0]!
92 if (Array.isArray(parent) && typeof finalPath === 'number') {
93 return parent.filter((_, i) => i !== finalPath)
94 }
95 const { [finalPath]: remove, ...rest } = parent
96 return rest
97 }
98​
99 const key = path.shift()
100​
101 if (typeof key === 'string') {
102 if (typeof parent === 'object') {
103 return {
104 ...parent,
105 [key]: doDelete(parent[key]),
106 }
107 }
108 }
109​
110 if (typeof key === 'number') {
111 if (Array.isArray(parent)) {
112 if (key >= parent.length) {
113 return parent
114 }
115 const prefix = parent.slice(0, key)
116 return [
117 ...(prefix.length ? prefix : new Array(key)),
118 doDelete(parent[key]),
119 ...parent.slice(key + 1),
120 ]
121 }
122 }
123​
124 throw new Error('It seems we have created an infinite loop in deleteBy. ')
125 }
126​
127 return doDelete(obj)
129​
130const reFindNumbers0 = /^(\d*)$/gm
131const reFindNumbers1 = /\.(\d*)\./gm
132const reFindNumbers2 = /^(\d*)\./gm
133const reFindNumbers3 = /\.(\d*$)/gm
134const reFindMultiplePeriods = /\.{2,}/gm
135​
136const intPrefix = '__int__'
137const intReplace = `${intPrefix}$1`
138​
139/**
140 * @private
141 */
142export function makePathArray(str: string) {
143 if (typeof str !== 'string') {
144 throw new Error('Path must be a string.')
145 }
146​
147 return str
148 .replaceAll('[', '.')
149 .replaceAll(']', '')
150 .replace(reFindNumbers0, intReplace)
151 .replace(reFindNumbers1, `.${intReplace}.`)
152 .replace(reFindNumbers2, `${intReplace}.`)
153 .replace(reFindNumbers3, `.${intReplace}`)
154 .replace(reFindMultiplePeriods, '.')
155 .split('.')
156 .map((d) => {
157 if (d.indexOf(intPrefix) === 0) {
158 return parseInt(d.substring(intPrefix.length), 10)
159 }
160 return d
161 })
163​
164/**
165 * @private
166 */
167export function isNonEmptyArray(obj: any) {
168 return !(Array.isArray(obj) && obj.length === 0)
170​
171interface AsyncValidatorArrayPartialOptions<T> {
172 validators?: T
173 asyncDebounceMs?: number
175​
176/**
177 * @private
178 */
179export interface AsyncValidator<T> {
180 cause: ValidationCause
181 validate: T
182 debounceMs: number
184​
185/**
186 * @private
187 */
188export function getAsyncValidatorArray<T>(
189 cause: ValidationCause,
190 options: AsyncValidatorArrayPartialOptions<T>,
191): T extends FieldValidators<any, any>
192 ? Array<
193 AsyncValidator<T['onChangeAsync'] | T['onBlurAsync'] | T['onSubmitAsync']>
194 >
195 : T extends FormValidators<any, any>
196 ? Array<
197 AsyncValidator<
198 T['onChangeAsync'] | T['onBlurAsync'] | T['onSubmitAsync']
199 >
200 >
201 : never {
202 const { asyncDebounceMs } = options
203 const {
204 onChangeAsync,
205 onBlurAsync,
206 onSubmitAsync,
207 onBlurAsyncDebounceMs,
208 onChangeAsyncDebounceMs,
209 } = (options.validators || {}) as
210 | FieldValidators<any, any>
211 | FormValidators<any, any>
212​
213 const defaultDebounceMs = asyncDebounceMs ?? 0
214​
215 const changeValidator = {
216 cause: 'change',
217 validate: onChangeAsync,
218 debounceMs: onChangeAsyncDebounceMs ?? defaultDebounceMs,
219 } as const
220​
221 const blurValidator = {
222 cause: 'blur',
223 validate: onBlurAsync,
224 debounceMs: onBlurAsyncDebounceMs ?? defaultDebounceMs,
225 } as const
226​
227 const submitValidator = {
228 cause: 'submit',
229 validate: onSubmitAsync,
230 debounceMs: 0,
231 } as const
232​
233 const noopValidator = (
234 validator:
235 | typeof changeValidator
236 | typeof blurValidator
237 | typeof submitValidator,
238 ) => ({ ...validator, debounceMs: 0 }) as const
239​
240 switch (cause) {
241 case 'submit':
242 return [
243 noopValidator(changeValidator),
244 noopValidator(blurValidator),
245 submitValidator,
246 ] as never
247 case 'blur':
248 return [blurValidator] as never
249 case 'change':
250 return [changeValidator] as never
251 case 'server':
252 default:
253 return [] as never
254 }
256​
257interface SyncValidatorArrayPartialOptions<T> {
258 validators?: T
260​
261/**
262 * @private
263 */
264export interface SyncValidator<T> {
265 cause: ValidationCause
266 validate: T
268​
269/**
270 * @private
271 */
272export function getSyncValidatorArray<T>(
273 cause: ValidationCause,
274 options: SyncValidatorArrayPartialOptions<T>,
275): T extends FieldValidators<any, any>
276 ? Array<SyncValidator<T['onChange'] | T['onBlur'] | T['onSubmit']>>
277 : T extends FormValidators<any, any>
278 ? Array<SyncValidator<T['onChange'] | T['onBlur'] | T['onSubmit']>>
279 : never {
280 const { onChange, onBlur, onSubmit } = (options.validators || {}) as
281 | FieldValidators<any, any>
282 | FormValidators<any, any>
283​
284 const changeValidator = { cause: 'change', validate: onChange } as const
285 const blurValidator = { cause: 'blur', validate: onBlur } as const
286 const submitValidator = { cause: 'submit', validate: onSubmit } as const
287​
288 // Allows us to clear onServer errors
289 const serverValidator = {
290 cause: 'server',
291 validate: () => undefined,
292 } as const
293​
294 switch (cause) {
295 case 'submit':
296 return [
297 changeValidator,
298 blurValidator,
299 submitValidator,
300 serverValidator,
301 ] as never
302 case 'server':
303 return [serverValidator] as never
304 case 'blur':
305 return [blurValidator, serverValidator] as never
306 case 'change':
307 default:
308 return [changeValidator, serverValidator] as never
309 }