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

utils.lib.ts

324 lines7.7 KB

1import type { AnyInternalFieldApi } from './FieldApi/FieldApi.lib'
2​
3// type
4import type { FieldUpdateOptions, OneOrMany, Updater } from './types.public'
5import type {
6 InternalFieldUpdateOptions,
7 ResolvedInternalFieldUpdateOptions,
8} from './types.lib'
9import type { AnyInternalFormApi } from './FormApi/FormApi.lib'
10​
11export type NameSegment = string | number
12export type NameSegments = Array<NameSegment>
13​
14/**
15 * Convert a name into an array of segments.
16 *
17 * If it already is an array, it will create a shallow copy.
18 */
19export function nameToFieldNodeSegments(
20 nameOrSegments: string | NameSegments,
21): NameSegments {
22 if (typeof nameOrSegments !== 'string') return nameOrSegments.slice()
23​
24 const result: NameSegments = []
25 let start = 0
26​
27 for (let i = 0; i < nameOrSegments.length; i++) {
28 switch (nameOrSegments.charCodeAt(i)) {
29 case 0x2e: // '.'
30 case 0x5b: // '['
31 if (i > start) {
32 result.push(nameOrSegments.slice(start, i))
33 }
34 start = i + 1
35 break
36 case 0x5d: // ']'
37 if (i > start) {
38 result.push(parseInt(nameOrSegments.slice(start, i), 10))
39 }
40 start = i + 1
41 break
42 }
43 }
44 if (start < nameOrSegments.length) {
45 result.push(nameOrSegments.slice(start))
46 }
47​
48 return result
50​
51export function resolveFieldUpdateOptions(
52 options: InternalFieldUpdateOptions | undefined,
53 event: 'change' | 'blur' | 'submit' | 'noEvent',
54): ResolvedInternalFieldUpdateOptions {
55 const baseOpts: Required<FieldUpdateOptions> = {
56 causeValidation: options?.causeValidation ?? true,
57 markAsBlurred: options?.markAsBlurred ?? event === 'blur',
58 markAsDirty: options?.markAsDirty ?? event === 'change',
59 markAsTouched:
60 options?.markAsTouched ?? (event === 'change' || event === 'submit'),
61 }
62 const noFieldCreationNeeded =
63 !baseOpts.markAsTouched && !baseOpts.markAsDirty && !baseOpts.markAsBlurred
64​
65 return {
66 ...baseOpts,
67 _skipFieldCreation: options?._skipFieldCreation ?? noFieldCreationNeeded,
68 fieldApiOverride: options?.fieldApiOverride ?? null,
69 doPropagate: options?.doPropagate ?? true,
70 }
72​
73export function getTargetField(
74 formApi: AnyInternalFormApi,
75 fieldName: string,
76 options: ResolvedInternalFieldUpdateOptions,
77) {
78 let field: AnyInternalFieldApi | null
79​
80 if (options.fieldApiOverride) {
81 field = options.fieldApiOverride
82 } else if (options._skipFieldCreation) {
83 field = formApi._tryGetFieldApi(fieldName)
84 } else {
85 field = formApi._getOrCreateFieldApi({ name: fieldName }, 'internal')
86 }
87 return field
89​
90/*
91/ credit is due to https://github.com/lukeed/uuid for this code, with current npm
92/ attacks we didn't feel comfortable installing directly from npm. But big appreciation
93/ from the TanStack Form team <3.
94*/
95​
96let IDX = 256
97const HEX: Array<string> = []
98let BUFFER: Array<number> | undefined
99​
100while (IDX--) {
101 HEX[IDX] = (IDX + 256).toString(16).substring(1)
103​
104export function uuid(): string {
105 let i = 0
106 let num: number
107 let out = ''
108​
109 if (!BUFFER || IDX + 16 > 256) {
110 BUFFER = new Array<number>(256)
111 i = 256
112 while (i--) {
113 BUFFER[i] = (256 * Math.random()) | 0
114 }
115 i = 0
116 IDX = 0
117 }
118​
119 for (; i < 16; i++) {
120 num = BUFFER[IDX + i] as number
121 if (i === 6) out += HEX[(num & 15) | 64]
122 else if (i === 8) out += HEX[(num & 63) | 128]
123 else out += HEX[num]
124​
125 if (i & 1 && i > 1 && i < 11) out += '-'
126 }
127​
128 IDX++
129 return out
131​
132export function isNotNil<T>(input: T): input is NonNullable<T> {
133 return input !== null && input !== undefined
135export function isNil<T>(input: T): input is Extract<T, undefined | null> {
136 return !isNotNil(input)
138​
139/**
140 * Get a value from an object using a path, including dot notation.
141 * @private
142 */
143export function getBy(obj: unknown, path: string | Array<string>): any {
144 const pathObj = nameToFieldNodeSegments(path)
145​
146 return pathObj.reduce((current: any, pathPart) => current?.[pathPart], obj)
148​
149/**
150 * Set a value on an object using a path, including dot notation.
151 * @private
152 */
153export function setBy(obj: any, _path: any, updater: Updater<any>) {
154 const path = nameToFieldNodeSegments(_path)
155​
156 function doSet(parent?: any): any {
157 if (!path.length) {
158 return callUpdater(updater, parent)
159 }
160​
161 const key = path.shift()
162​
163 if (
164 typeof key === 'string' ||
165 (typeof key === 'number' && !Array.isArray(parent))
166 ) {
167 if (typeof parent === 'object') {
168 if (parent === null) {
169 parent = {}
170 }
171 return {
172 ...parent,
173 [key]: doSet(parent[key]),
174 }
175 }
176 return {
177 [key]: doSet(),
178 }
179 }
180​
181 if (Array.isArray(parent) && typeof key === 'number') {
182 const prefix = parent.slice(0, key)
183 return [
184 ...(prefix.length ? prefix : new Array(key)),
185 doSet(parent[key]),
186 ...parent.slice(key + 1),
187 ]
188 }
189 return [...new Array(key), doSet()]
190 }
191​
192 return doSet(obj)
194​
195export function callUpdater<T>(updater: Updater<T>, object: T): T {
196 return typeof updater === 'function'
197 ? (updater as (...args: Array<any>) => any)(object)
198 : updater
200​
201export function normalizeToArray<T>(
202 input: null | undefined | OneOrMany<T>,
203): Array<T> {
204 if (Array.isArray(input)) return input
205 if (input === null || input === undefined) return []
206 return [input]
208​
209// TODO remove and import from store:
210// https://github.com/TanStack/store/pull/313
211export function evaluate<T>(
212 objA: T,
213 objB: T,
214 seen: WeakMap<object, WeakSet<object>> = new WeakMap(),
215): boolean {
216 if (Object.is(objA, objB)) {
217 return true
218 }
219​
220 if (
221 typeof objA !== 'object' ||
222 objA === null ||
223 typeof objB !== 'object' ||
224 objB === null
225 ) {
226 return false
227 }
228​
229 // guards against circular references
230 let seenB = seen.get(objA)
231​
232 if (seenB?.has(objB)) return true
233​
234 if (!seenB) {
235 seenB = new WeakSet()
236 seen.set(objA, seenB)
237 }
238​
239 seenB.add(objB)
240​
241 // guards against runtime cross type evaluation
242 if (Object.getPrototypeOf(objA) !== Object.getPrototypeOf(objB)) {
243 return false
244 }
245​
246 if (objA instanceof Date && objB instanceof Date) {
247 return objA.getTime() === objB.getTime()
248 }
249​
250 if (
251 typeof File !== 'undefined' &&
252 objA instanceof File &&
253 objB instanceof File
254 ) {
255 return (
256 objA.name === objB.name &&
257 objA.size === objB.size &&
258 objA.type === objB.type &&
259 objA.lastModified === objB.lastModified
260 )
261 }
262​
263 if (objA instanceof Map && objB instanceof Map) {
264 if (objA.size !== objB.size) return false
265​
266 for (const [k, v] of objA) {
267 if (!objB.has(k) || !evaluate(v, objB.get(k), seen)) return false
268 }
269​
270 return true
271 }
272​
273 if (objA instanceof Set && objB instanceof Set) {
274 if (objA.size !== objB.size) return false
275​
276 for (const v of objA) {
277 if (![...objB].some((bv) => evaluate(v, bv, seen))) return false
278 }
279​
280 return true
281 }
282​
283 const keysA = getOwnKeys(objA)
284 const keysB = getOwnKeys(objB)
285​
286 if (keysA.length !== keysB.length) {
287 return false
288 }
289​
290 for (const key of keysA) {
291 if (
292 !Object.prototype.hasOwnProperty.call(objB, key) ||
293 !evaluate(objA[key as keyof T], objB[key as keyof T], seen)
294 ) {
295 return false
296 }
297 }
298​
299 return true
301​
302function getOwnKeys(obj: object): Array<string | symbol> {
303 return (Object.keys(obj) as Array<string | symbol>).concat(
304 Object.getOwnPropertySymbols(obj),
305 )
307​
308export function concatenateFieldNames(nameA: string, nameB: string): string {
309 if (nameA.length === 0) return nameB
310 if (nameB.length === 0) return nameA
311 if (nameB.startsWith('[')) return `${nameA}${nameB}`
312 return `${nameA}.${nameB}`
314​
315export function isPromiseLike<T>(
316 value: T | PromiseLike<T>,
317): value is PromiseLike<T> {
318 return (
319 typeof value === 'object' &&
320 value !== null &&
321 'then' in value &&
322 typeof value.then === 'function'
323 )