@tanstack/form-core 0.0.11 → 0.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/build/{cjs/FieldApi.js → lib/FieldApi.cjs} +80 -113
  2. package/build/lib/FieldApi.cjs.map +1 -0
  3. package/build/lib/FieldApi.d.ts +112 -0
  4. package/build/lib/FieldApi.d.ts.map +1 -0
  5. package/build/lib/FieldApi.js +305 -0
  6. package/build/lib/FieldApi.js.map +1 -0
  7. package/build/lib/FieldApi.legacy.cjs +307 -0
  8. package/build/lib/FieldApi.legacy.cjs.map +1 -0
  9. package/build/lib/FieldApi.legacy.js +305 -0
  10. package/build/lib/FieldApi.legacy.js.map +1 -0
  11. package/build/{cjs/FormApi.js → lib/FormApi.cjs} +66 -78
  12. package/build/lib/FormApi.cjs.map +1 -0
  13. package/build/{types → lib}/FormApi.d.ts +3 -2
  14. package/build/lib/FormApi.d.ts.map +1 -0
  15. package/build/lib/FormApi.js +246 -0
  16. package/build/lib/FormApi.js.map +1 -0
  17. package/build/lib/FormApi.legacy.cjs +248 -0
  18. package/build/lib/FormApi.legacy.cjs.map +1 -0
  19. package/build/lib/FormApi.legacy.js +246 -0
  20. package/build/lib/FormApi.legacy.js.map +1 -0
  21. package/build/{cjs/_virtual/_rollupPluginBabelHelpers.js → lib/_virtual/_rollupPluginBabelHelpers.cjs} +18 -45
  22. package/build/lib/_virtual/_rollupPluginBabelHelpers.cjs.map +1 -0
  23. package/build/lib/_virtual/_rollupPluginBabelHelpers.js +56 -0
  24. package/build/{cjs → lib}/_virtual/_rollupPluginBabelHelpers.js.map +1 -1
  25. package/build/lib/_virtual/_rollupPluginBabelHelpers.legacy.cjs +65 -0
  26. package/build/lib/_virtual/_rollupPluginBabelHelpers.legacy.cjs.map +1 -0
  27. package/build/lib/_virtual/_rollupPluginBabelHelpers.legacy.js +56 -0
  28. package/build/lib/_virtual/_rollupPluginBabelHelpers.legacy.js.map +1 -0
  29. package/build/lib/index.cjs +14 -0
  30. package/build/lib/index.cjs.map +1 -0
  31. package/build/{types → lib}/index.d.ts +1 -0
  32. package/build/lib/index.d.ts.map +1 -0
  33. package/build/lib/index.js +4 -0
  34. package/build/{cjs → lib}/index.js.map +1 -1
  35. package/build/lib/index.legacy.cjs +14 -0
  36. package/build/lib/index.legacy.cjs.map +1 -0
  37. package/build/lib/index.legacy.js +4 -0
  38. package/build/lib/index.legacy.js.map +1 -0
  39. package/build/lib/tests/FieldApi.spec.d.ts +2 -0
  40. package/build/lib/tests/FieldApi.spec.d.ts.map +1 -0
  41. package/build/lib/tests/FieldApi.test-d.d.ts +2 -0
  42. package/build/lib/tests/FieldApi.test-d.d.ts.map +1 -0
  43. package/build/lib/tests/FormApi.spec.d.ts +2 -0
  44. package/build/lib/tests/FormApi.spec.d.ts.map +1 -0
  45. package/build/{cjs/utils.js → lib/utils.cjs} +18 -27
  46. package/build/lib/utils.cjs.map +1 -0
  47. package/build/{types → lib}/utils.d.ts +10 -0
  48. package/build/lib/utils.d.ts.map +1 -0
  49. package/build/lib/utils.js +77 -0
  50. package/build/lib/utils.js.map +1 -0
  51. package/build/lib/utils.legacy.cjs +81 -0
  52. package/build/lib/utils.legacy.cjs.map +1 -0
  53. package/build/lib/utils.legacy.js +77 -0
  54. package/build/lib/utils.legacy.js.map +1 -0
  55. package/package.json +22 -9
  56. package/src/FieldApi.ts +101 -46
  57. package/src/FormApi.ts +34 -14
  58. package/src/tests/FieldApi.spec.ts +169 -0
  59. package/src/tests/FieldApi.test-d.ts +41 -0
  60. package/src/tests/FormApi.spec.ts +216 -0
  61. package/src/utils.ts +10 -1
  62. package/build/cjs/FieldApi.js.map +0 -1
  63. package/build/cjs/FormApi.js.map +0 -1
  64. package/build/cjs/index.js +0 -26
  65. package/build/cjs/utils.js.map +0 -1
  66. package/build/esm/index.js +0 -716
  67. package/build/esm/index.js.map +0 -1
  68. package/build/stats-html.html +0 -2689
  69. package/build/stats-react.json +0 -196
  70. package/build/types/FieldApi.d.ts +0 -85
  71. package/build/types/tests/test.test.d.ts +0 -0
  72. package/build/umd/index.development.js +0 -779
  73. package/build/umd/index.development.js.map +0 -1
  74. package/build/umd/index.production.js +0 -22
  75. package/build/umd/index.production.js.map +0 -1
  76. package/src/tests/test.test.tsx +0 -5
@@ -1,779 +0,0 @@
1
- /**
2
- * form-core
3
- *
4
- * Copyright (c) TanStack
5
- *
6
- * This source code is licensed under the MIT license found in the
7
- * LICENSE.md file in the root directory of this source tree.
8
- *
9
- * @license MIT
10
- */
11
- (function (global, factory) {
12
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
13
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
14
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.FormCore = {}));
15
- })(this, (function (exports) { 'use strict';
16
-
17
- function _defineProperty(obj, key, value) {
18
- if (key in obj) {
19
- Object.defineProperty(obj, key, {
20
- value: value,
21
- enumerable: true,
22
- configurable: true,
23
- writable: true
24
- });
25
- } else {
26
- obj[key] = value;
27
- }
28
-
29
- return obj;
30
- }
31
-
32
- function _classPrivateFieldGet(receiver, privateMap) {
33
- var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get");
34
-
35
- return _classApplyDescriptorGet(receiver, descriptor);
36
- }
37
-
38
- function _classPrivateFieldSet(receiver, privateMap, value) {
39
- var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set");
40
-
41
- _classApplyDescriptorSet(receiver, descriptor, value);
42
-
43
- return value;
44
- }
45
-
46
- function _classExtractFieldDescriptor(receiver, privateMap, action) {
47
- if (!privateMap.has(receiver)) {
48
- throw new TypeError("attempted to " + action + " private field on non-instance");
49
- }
50
-
51
- return privateMap.get(receiver);
52
- }
53
-
54
- function _classApplyDescriptorGet(receiver, descriptor) {
55
- if (descriptor.get) {
56
- return descriptor.get.call(receiver);
57
- }
58
-
59
- return descriptor.value;
60
- }
61
-
62
- function _classApplyDescriptorSet(receiver, descriptor, value) {
63
- if (descriptor.set) {
64
- descriptor.set.call(receiver, value);
65
- } else {
66
- if (!descriptor.writable) {
67
- throw new TypeError("attempted to set read only private field");
68
- }
69
-
70
- descriptor.value = value;
71
- }
72
- }
73
-
74
- function _checkPrivateRedeclaration(obj, privateCollection) {
75
- if (privateCollection.has(obj)) {
76
- throw new TypeError("Cannot initialize the same private elements twice on an object");
77
- }
78
- }
79
-
80
- function _classPrivateFieldInitSpec(obj, privateMap, value) {
81
- _checkPrivateRedeclaration(obj, privateMap);
82
-
83
- privateMap.set(obj, value);
84
- }
85
-
86
- /**
87
- * store
88
- *
89
- * Copyright (c) TanStack
90
- *
91
- * This source code is licensed under the MIT license found in the
92
- * LICENSE.md file in the root directory of this source tree.
93
- *
94
- * @license MIT
95
- */
96
- class Store {
97
- listeners = new Set();
98
- #batching = false;
99
- #flushing = 0;
100
- constructor(initialState, options) {
101
- this.state = initialState;
102
- this.options = options;
103
- if (this.options?.onUpdate) {
104
- this.subscribe(this.options?.onUpdate);
105
- }
106
- }
107
- subscribe = listener => {
108
- this.listeners.add(listener);
109
- const unsub = this.options?.onSubscribe?.(listener, this);
110
- return () => {
111
- this.listeners.delete(listener);
112
- unsub?.();
113
- };
114
- };
115
- setState = updater => {
116
- const previous = this.state;
117
- this.state = this.options?.updateFn ? this.options.updateFn(previous)(updater) : updater(previous);
118
- this.#flush();
119
- };
120
- #flush = () => {
121
- if (this.#batching) return;
122
- const flushId = ++this.#flushing;
123
- this.listeners.forEach(listener => {
124
- if (this.#flushing !== flushId) return;
125
- listener();
126
- });
127
- };
128
- batch = cb => {
129
- if (this.#batching) return cb();
130
- this.#batching = true;
131
- cb();
132
- this.#batching = false;
133
- this.#flush();
134
- };
135
- }
136
-
137
- function functionalUpdate(updater, input) {
138
- return typeof updater === 'function' ? updater(input) : updater;
139
- }
140
- function getBy(obj, path) {
141
- const pathArray = makePathArray(path);
142
- const pathObj = pathArray;
143
- return pathObj.reduce((current, pathPart) => {
144
- if (typeof current !== 'undefined') {
145
- return current[pathPart];
146
- }
147
-
148
- return undefined;
149
- }, obj);
150
- }
151
- function setBy(obj, _path, updater) {
152
- const path = makePathArray(_path);
153
-
154
- function doSet(parent) {
155
- if (!path.length) {
156
- return functionalUpdate(updater, parent);
157
- }
158
-
159
- const key = path.shift();
160
-
161
- if (typeof key === 'string') {
162
- if (typeof parent === 'object') {
163
- return { ...parent,
164
- [key]: doSet(parent[key])
165
- };
166
- }
167
-
168
- return {
169
- [key]: doSet()
170
- };
171
- }
172
-
173
- if (typeof key === 'number') {
174
- if (Array.isArray(parent)) {
175
- const prefix = parent.slice(0, key);
176
- return [...(prefix.length ? prefix : new Array(key)), doSet(parent[key]), ...parent.slice(key + 1)];
177
- }
178
-
179
- return [...new Array(key), doSet()];
180
- }
181
-
182
- throw new Error('Uh oh!');
183
- }
184
-
185
- return doSet(obj);
186
- }
187
- const reFindNumbers0 = /^(\d*)$/gm;
188
- const reFindNumbers1 = /\.(\d*)\./gm;
189
- const reFindNumbers2 = /^(\d*)\./gm;
190
- const reFindNumbers3 = /\.(\d*$)/gm;
191
- const reFindMultiplePeriods = /\.{2,}/gm;
192
- const intPrefix = '__int__';
193
- const intReplace = intPrefix + "$1";
194
-
195
- function makePathArray(str) {
196
- if (typeof str !== 'string') {
197
- throw new Error();
198
- }
199
-
200
- return str.replace('[', '.').replace(']', '').replace(reFindNumbers0, intReplace).replace(reFindNumbers1, "." + intReplace + ".").replace(reFindNumbers2, intReplace + ".").replace(reFindNumbers3, "." + intReplace).replace(reFindMultiplePeriods, '.').split('.').map(d => {
201
- if (d.indexOf(intPrefix) === 0) {
202
- return parseInt(d.substring(intPrefix.length), 10);
203
- }
204
-
205
- return d;
206
- });
207
- }
208
-
209
- function getDefaultFormState(defaultState) {
210
- return {
211
- values: {},
212
- fieldMeta: {},
213
- canSubmit: true,
214
- isFieldsValid: false,
215
- isFieldsValidating: false,
216
- isFormValid: false,
217
- isFormValidating: false,
218
- isSubmitted: false,
219
- isSubmitting: false,
220
- isTouched: false,
221
- isValid: false,
222
- isValidating: false,
223
- submissionAttempts: 0,
224
- formValidationCount: 0,
225
- ...defaultState
226
- };
227
- }
228
-
229
- class FormApi {
230
- // // This carries the context for nested fields
231
- // Do not use __state directly, as it is not reactive.
232
- // Please use form.useStore() utility to subscribe to state
233
- constructor(_opts) {
234
- var _opts$defaultValues, _opts$defaultState;
235
-
236
- _defineProperty(this, "options", {});
237
-
238
- _defineProperty(this, "store", void 0);
239
-
240
- _defineProperty(this, "state", void 0);
241
-
242
- _defineProperty(this, "fieldInfo", {});
243
-
244
- _defineProperty(this, "fieldName", void 0);
245
-
246
- _defineProperty(this, "validationMeta", {});
247
-
248
- _defineProperty(this, "update", options => {
249
- if (!options) return;
250
- this.store.batch(() => {
251
- if (options.defaultState && options.defaultState !== this.options.defaultState) {
252
- this.store.setState(prev => ({ ...prev,
253
- ...options.defaultState
254
- }));
255
- }
256
-
257
- if (options.defaultValues !== this.options.defaultValues) {
258
- this.store.setState(() => getDefaultFormState(options.defaultValues));
259
- }
260
- });
261
- this.options = options;
262
- });
263
-
264
- _defineProperty(this, "reset", () => this.store.setState(() => getDefaultFormState(this.options.defaultValues)));
265
-
266
- _defineProperty(this, "validateAllFields", async cause => {
267
- const fieldValidationPromises = [];
268
- this.store.batch(() => {
269
- void Object.values(this.fieldInfo).forEach(field => {
270
- Object.values(field.instances).forEach(instance => {
271
- // If any fields are not touched
272
- if (!instance.state.meta.isTouched) {
273
- // Mark them as touched
274
- instance.setMeta(prev => ({ ...prev,
275
- isTouched: true
276
- })); // Validate the field
277
-
278
- fieldValidationPromises.push(Promise.resolve().then(() => instance.validate(cause)));
279
- }
280
- });
281
- });
282
- });
283
- return Promise.all(fieldValidationPromises);
284
- });
285
-
286
- _defineProperty(this, "handleSubmit", async e => {
287
- e.preventDefault();
288
- e.stopPropagation(); // Check to see that the form and all fields have been touched
289
- // If they have not, touch them all and run validation
290
- // Run form validation
291
- // Submit the form
292
-
293
- this.store.setState(old => ({ ...old,
294
- // Submittion attempts mark the form as not submitted
295
- isSubmitted: false,
296
- // Count submission attempts
297
- submissionAttempts: old.submissionAttempts + 1
298
- })); // Don't let invalid forms submit
299
-
300
- if (!this.state.canSubmit) return;
301
- this.store.setState(d => ({ ...d,
302
- isSubmitting: true
303
- }));
304
-
305
- const done = () => {
306
- this.store.setState(prev => ({ ...prev,
307
- isSubmitting: false
308
- }));
309
- }; // Validate all fields
310
-
311
-
312
- await this.validateAllFields('submit'); // Fields are invalid, do not submit
313
-
314
- if (!this.state.isFieldsValid) {
315
- var _this$options$onSubmi, _this$options;
316
-
317
- done();
318
- (_this$options$onSubmi = (_this$options = this.options).onSubmitInvalid) == null ? void 0 : _this$options$onSubmi.call(_this$options, this.state.values, this);
319
- return;
320
- } // Run validation for the form
321
- // await this.validateForm()
322
-
323
-
324
- if (!this.state.isValid) {
325
- var _this$options$onSubmi2, _this$options2;
326
-
327
- done();
328
- (_this$options$onSubmi2 = (_this$options2 = this.options).onSubmitInvalid) == null ? void 0 : _this$options$onSubmi2.call(_this$options2, this.state.values, this);
329
- return;
330
- }
331
-
332
- try {
333
- var _this$options$onSubmi3, _this$options3;
334
-
335
- // Run the submit code
336
- await ((_this$options$onSubmi3 = (_this$options3 = this.options).onSubmit) == null ? void 0 : _this$options$onSubmi3.call(_this$options3, this.state.values, this));
337
- this.store.batch(() => {
338
- this.store.setState(prev => ({ ...prev,
339
- isSubmitted: true
340
- }));
341
- done();
342
- });
343
- } catch (err) {
344
- done();
345
- throw err;
346
- }
347
- });
348
-
349
- _defineProperty(this, "getFieldValue", field => getBy(this.state.values, field));
350
-
351
- _defineProperty(this, "getFieldMeta", field => {
352
- return this.state.fieldMeta[field];
353
- });
354
-
355
- _defineProperty(this, "getFieldInfo", field => {
356
- var _this$fieldInfo;
357
-
358
- return (_this$fieldInfo = this.fieldInfo)[field] || (_this$fieldInfo[field] = {
359
- instances: {}
360
- });
361
- });
362
-
363
- _defineProperty(this, "setFieldMeta", (field, updater) => {
364
- this.store.setState(prev => {
365
- return { ...prev,
366
- fieldMeta: { ...prev.fieldMeta,
367
- [field]: functionalUpdate(updater, prev.fieldMeta[field])
368
- }
369
- };
370
- });
371
- });
372
-
373
- _defineProperty(this, "setFieldValue", (field, updater, opts) => {
374
- const touch = opts == null ? void 0 : opts.touch;
375
- this.store.batch(() => {
376
- if (touch) {
377
- this.setFieldMeta(field, prev => ({ ...prev,
378
- isTouched: true
379
- }));
380
- }
381
-
382
- this.store.setState(prev => {
383
- return { ...prev,
384
- values: setBy(prev.values, field, updater)
385
- };
386
- });
387
- });
388
- });
389
-
390
- _defineProperty(this, "pushFieldValue", (field, value, opts) => {
391
- return this.setFieldValue(field, prev => [...(Array.isArray(prev) ? prev : []), value], opts);
392
- });
393
-
394
- _defineProperty(this, "insertFieldValue", (field, index, value, opts) => {
395
- this.setFieldValue(field, prev => {
396
- return prev.map((d, i) => i === index ? value : d);
397
- }, opts);
398
- });
399
-
400
- _defineProperty(this, "removeFieldValue", (field, index, opts) => {
401
- this.setFieldValue(field, prev => {
402
- return prev.filter((_d, i) => i !== index);
403
- }, opts);
404
- });
405
-
406
- _defineProperty(this, "swapFieldValues", (field, index1, index2) => {
407
- this.setFieldValue(field, prev => {
408
- const prev1 = prev[index1];
409
- const prev2 = prev[index2];
410
- return setBy(setBy(prev, [index1], prev2), [index2], prev1);
411
- });
412
- });
413
-
414
- this.store = new Store(getDefaultFormState({ ...(_opts == null ? void 0 : _opts.defaultState),
415
- values: (_opts$defaultValues = _opts == null ? void 0 : _opts.defaultValues) != null ? _opts$defaultValues : _opts == null ? void 0 : (_opts$defaultState = _opts.defaultState) == null ? void 0 : _opts$defaultState.values,
416
- isFormValid: true
417
- }), {
418
- onUpdate: () => {
419
- let {
420
- state
421
- } = this.store; // Computed state
422
-
423
- const fieldMetaValues = Object.values(state.fieldMeta);
424
- const isFieldsValidating = fieldMetaValues.some(field => field == null ? void 0 : field.isValidating);
425
- const isFieldsValid = !fieldMetaValues.some(field => field == null ? void 0 : field.error);
426
- const isTouched = fieldMetaValues.some(field => field == null ? void 0 : field.isTouched);
427
- const isValidating = isFieldsValidating || state.isFormValidating;
428
- const isFormValid = !state.formError;
429
- const isValid = isFieldsValid && isFormValid;
430
- const canSubmit = state.submissionAttempts === 0 && !isTouched || !isValidating && !state.isSubmitting && isValid;
431
- state = { ...state,
432
- isFieldsValidating,
433
- isFieldsValid,
434
- isFormValid,
435
- isValid,
436
- canSubmit,
437
- isTouched
438
- };
439
- this.store.state = state;
440
- this.state = state;
441
- }
442
- });
443
- this.state = this.store.state;
444
- this.update(_opts || {});
445
- }
446
-
447
- }
448
-
449
- let uid = 0;
450
-
451
- var _prevState = /*#__PURE__*/new WeakMap();
452
-
453
- var _leaseValidateAsync = /*#__PURE__*/new WeakMap();
454
-
455
- class FieldApi {
456
- constructor(_opts) {
457
- var _this$getMeta;
458
-
459
- _defineProperty(this, "uid", void 0);
460
-
461
- _defineProperty(this, "form", void 0);
462
-
463
- _defineProperty(this, "name", void 0);
464
-
465
- _defineProperty(this, "store", void 0);
466
-
467
- _defineProperty(this, "state", void 0);
468
-
469
- _classPrivateFieldInitSpec(this, _prevState, {
470
- writable: true,
471
- value: void 0
472
- });
473
-
474
- _defineProperty(this, "options", {});
475
-
476
- _defineProperty(this, "mount", () => {
477
- var _this$options$onMount, _this$options;
478
-
479
- const info = this.getInfo();
480
- info.instances[this.uid] = this;
481
- const unsubscribe = this.form.store.subscribe(() => {
482
- this.store.batch(() => {
483
- const nextValue = this.getValue();
484
- const nextMeta = this.getMeta();
485
-
486
- if (nextValue !== this.state.value) {
487
- this.store.setState(prev => ({ ...prev,
488
- value: nextValue
489
- }));
490
- }
491
-
492
- if (nextMeta !== this.state.meta) {
493
- this.store.setState(prev => ({ ...prev,
494
- meta: nextMeta
495
- }));
496
- }
497
- });
498
- });
499
- (_this$options$onMount = (_this$options = this.options).onMount) == null ? void 0 : _this$options$onMount.call(_this$options, this);
500
- return () => {
501
- unsubscribe();
502
- delete info.instances[this.uid];
503
-
504
- if (!Object.keys(info.instances).length) {
505
- delete this.form.fieldInfo[this.name];
506
- }
507
- };
508
- });
509
-
510
- _defineProperty(this, "update", opts => {
511
- var _this$form$options$as, _this$form$options$on, _this$form$options$on2;
512
-
513
- this.options = {
514
- asyncDebounceMs: (_this$form$options$as = this.form.options.asyncDebounceMs) != null ? _this$form$options$as : 0,
515
- onChangeAsyncDebounceMs: (_this$form$options$on = this.form.options.onChangeAsyncDebounceMs) != null ? _this$form$options$on : 0,
516
- onBlurAsyncDebounceMs: (_this$form$options$on2 = this.form.options.onBlurAsyncDebounceMs) != null ? _this$form$options$on2 : 0,
517
- ...opts
518
- }; // Default Value
519
-
520
- if (this.state.value === undefined && this.options.defaultValue !== undefined) {
521
- this.setValue(this.options.defaultValue);
522
- } // Default Meta
523
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
524
-
525
-
526
- if (this.getMeta() === undefined) {
527
- this.setMeta(this.state.meta);
528
- }
529
- });
530
-
531
- _defineProperty(this, "getValue", () => {
532
- return this.form.getFieldValue(this.name);
533
- });
534
-
535
- _defineProperty(this, "setValue", (updater, options) => this.form.setFieldValue(this.name, updater, options));
536
-
537
- _defineProperty(this, "getMeta", () => this.form.getFieldMeta(this.name));
538
-
539
- _defineProperty(this, "setMeta", updater => this.form.setFieldMeta(this.name, updater));
540
-
541
- _defineProperty(this, "getInfo", () => this.form.getFieldInfo(this.name));
542
-
543
- _defineProperty(this, "pushValue", value => this.form.pushFieldValue(this.name, value));
544
-
545
- _defineProperty(this, "insertValue", (index, value) => this.form.insertFieldValue(this.name, index, value));
546
-
547
- _defineProperty(this, "removeValue", index => this.form.removeFieldValue(this.name, index));
548
-
549
- _defineProperty(this, "swapValues", (aIndex, bIndex) => this.form.swapFieldValues(this.name, aIndex, bIndex));
550
-
551
- _defineProperty(this, "getSubField", name => new FieldApi({
552
- name: this.name + "." + name,
553
- form: this.form
554
- }));
555
-
556
- _defineProperty(this, "validateSync", async (value = this.state.value, cause) => {
557
- const {
558
- onChange,
559
- onBlur
560
- } = this.options;
561
- const validate = cause === 'submit' ? undefined : cause === 'change' ? onChange : onBlur;
562
- if (!validate) return; // Use the validationCount for all field instances to
563
- // track freshness of the validation
564
-
565
- const validationCount = (this.getInfo().validationCount || 0) + 1;
566
- this.getInfo().validationCount = validationCount;
567
- const error = normalizeError(validate(value, this));
568
-
569
- if (this.state.meta.error !== error) {
570
- this.setMeta(prev => ({ ...prev,
571
- error
572
- }));
573
- } // If a sync error is encountered, cancel any async validation
574
-
575
-
576
- if (this.state.meta.error) {
577
- this.cancelValidateAsync();
578
- }
579
- });
580
-
581
- _classPrivateFieldInitSpec(this, _leaseValidateAsync, {
582
- writable: true,
583
- value: () => {
584
- const count = (this.getInfo().validationAsyncCount || 0) + 1;
585
- this.getInfo().validationAsyncCount = count;
586
- return count;
587
- }
588
- });
589
-
590
- _defineProperty(this, "cancelValidateAsync", () => {
591
- // Lease a new validation count to ignore any pending validations
592
- _classPrivateFieldGet(this, _leaseValidateAsync).call(this); // Cancel any pending validation state
593
-
594
-
595
- this.setMeta(prev => ({ ...prev,
596
- isValidating: false
597
- }));
598
- });
599
-
600
- _defineProperty(this, "validateAsync", async (value = this.state.value, cause) => {
601
- var _ref, _ref2;
602
-
603
- const {
604
- onChangeAsync,
605
- onBlurAsync,
606
- onSubmitAsync,
607
- asyncDebounceMs,
608
- onBlurAsyncDebounceMs,
609
- onChangeAsyncDebounceMs
610
- } = this.options;
611
- const validate = cause === 'change' ? onChangeAsync : cause === 'submit' ? onSubmitAsync : onBlurAsync;
612
- if (!validate) return;
613
- const debounceMs = cause === 'submit' ? 0 : (_ref = (_ref2 = cause === 'change' ? onChangeAsyncDebounceMs : onBlurAsyncDebounceMs) != null ? _ref2 : asyncDebounceMs) != null ? _ref : 500;
614
- if (this.state.meta.isValidating !== true) this.setMeta(prev => ({ ...prev,
615
- isValidating: true
616
- })); // Use the validationCount for all field instances to
617
- // track freshness of the validation
618
-
619
- const validationAsyncCount = _classPrivateFieldGet(this, _leaseValidateAsync).call(this);
620
-
621
- const checkLatest = () => validationAsyncCount === this.getInfo().validationAsyncCount;
622
-
623
- if (!this.getInfo().validationPromise) {
624
- this.getInfo().validationPromise = new Promise((resolve, reject) => {
625
- this.getInfo().validationResolve = resolve;
626
- this.getInfo().validationReject = reject;
627
- });
628
- }
629
-
630
- if (debounceMs > 0) {
631
- await new Promise(r => setTimeout(r, debounceMs));
632
- } // Only kick off validation if this validation is the latest attempt
633
-
634
-
635
- if (checkLatest()) {
636
- try {
637
- const rawError = await validate(value, this);
638
-
639
- if (checkLatest()) {
640
- var _this$getInfo$validat, _this$getInfo;
641
-
642
- const error = normalizeError(rawError);
643
- this.setMeta(prev => ({ ...prev,
644
- isValidating: false,
645
- error
646
- }));
647
- (_this$getInfo$validat = (_this$getInfo = this.getInfo()).validationResolve) == null ? void 0 : _this$getInfo$validat.call(_this$getInfo, error);
648
- }
649
- } catch (error) {
650
- if (checkLatest()) {
651
- var _this$getInfo$validat2, _this$getInfo2;
652
-
653
- (_this$getInfo$validat2 = (_this$getInfo2 = this.getInfo()).validationReject) == null ? void 0 : _this$getInfo$validat2.call(_this$getInfo2, error);
654
- throw error;
655
- }
656
- } finally {
657
- if (checkLatest()) {
658
- this.setMeta(prev => ({ ...prev,
659
- isValidating: false
660
- }));
661
- delete this.getInfo().validationPromise;
662
- }
663
- }
664
- } // Always return the latest validation promise to the caller
665
-
666
-
667
- return this.getInfo().validationPromise;
668
- });
669
-
670
- _defineProperty(this, "validate", (cause, value) => {
671
- // If the field is pristine and validatePristine is false, do not validate
672
- if (!this.state.meta.isTouched) return; // Attempt to sync validate first
673
-
674
- this.validateSync(value, cause); // If there is an error, return it, do not attempt async validation
675
-
676
- if (this.state.meta.error) {
677
- if (!this.options.asyncAlways) {
678
- return this.state.meta.error;
679
- }
680
- } // No error? Attempt async validation
681
-
682
-
683
- return this.validateAsync(value, cause);
684
- });
685
-
686
- _defineProperty(this, "getChangeProps", (props = {}) => {
687
- return { ...props,
688
- value: this.state.value,
689
- onChange: value => {
690
- this.setValue(value);
691
- props.onChange == null ? void 0 : props.onChange(value);
692
- },
693
- onBlur: e => {
694
- const prevTouched = this.state.meta.isTouched;
695
- this.setMeta(prev => ({ ...prev,
696
- isTouched: true
697
- }));
698
-
699
- if (!prevTouched) {
700
- this.validate('change');
701
- }
702
-
703
- this.validate('blur');
704
- }
705
- };
706
- });
707
-
708
- _defineProperty(this, "getInputProps", (props = {}) => {
709
- return { ...props,
710
- value: String(this.state.value),
711
- onChange: e => {
712
- this.setValue(e.target.value);
713
- props.onChange == null ? void 0 : props.onChange(e.target.value);
714
- },
715
- onBlur: this.getChangeProps(props).onBlur
716
- };
717
- });
718
-
719
- this.form = _opts.form;
720
- this.uid = uid++; // Support field prefixing from FieldScope
721
- // let fieldPrefix = ''
722
- // if (this.form.fieldName) {
723
- // fieldPrefix = `${this.form.fieldName}.`
724
- // }
725
-
726
- this.name = _opts.name;
727
- this.store = new Store({
728
- value: this.getValue(),
729
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
730
- meta: (_this$getMeta = this.getMeta()) != null ? _this$getMeta : {
731
- isValidating: false,
732
- isTouched: false,
733
- ...this.options.defaultMeta
734
- }
735
- }, {
736
- onUpdate: () => {
737
- const state = this.store.state;
738
- state.meta.touchedError = state.meta.isTouched ? state.meta.error : undefined;
739
-
740
- if (state.value !== _classPrivateFieldGet(this, _prevState).value) {
741
- this.validate('change', state.value);
742
- }
743
-
744
- _classPrivateFieldSet(this, _prevState, state);
745
-
746
- this.state = state;
747
- }
748
- });
749
- this.state = this.store.state;
750
-
751
- _classPrivateFieldSet(this, _prevState, this.state);
752
-
753
- this.update(_opts);
754
- }
755
-
756
- }
757
-
758
- function normalizeError(rawError) {
759
- if (rawError) {
760
- if (typeof rawError !== 'string') {
761
- return 'Invalid Form Values';
762
- }
763
-
764
- return rawError;
765
- }
766
-
767
- return undefined;
768
- }
769
-
770
- exports.FieldApi = FieldApi;
771
- exports.FormApi = FormApi;
772
- exports.functionalUpdate = functionalUpdate;
773
- exports.getBy = getBy;
774
- exports.setBy = setBy;
775
-
776
- Object.defineProperty(exports, '__esModule', { value: true });
777
-
778
- }));
779
- //# sourceMappingURL=index.development.js.map