@tanstack/react-form 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 (87) hide show
  1. package/build/lib/_virtual/_rollupPluginBabelHelpers.cjs +19 -0
  2. package/build/lib/_virtual/_rollupPluginBabelHelpers.cjs.map +1 -0
  3. package/build/{cjs → lib}/_virtual/_rollupPluginBabelHelpers.js +1 -17
  4. package/build/lib/_virtual/_rollupPluginBabelHelpers.js.map +1 -0
  5. package/build/lib/_virtual/_rollupPluginBabelHelpers.legacy.cjs +19 -0
  6. package/build/lib/_virtual/_rollupPluginBabelHelpers.legacy.cjs.map +1 -0
  7. package/build/lib/_virtual/_rollupPluginBabelHelpers.legacy.js +17 -0
  8. package/build/lib/_virtual/_rollupPluginBabelHelpers.legacy.js.map +1 -0
  9. package/build/lib/createFormFactory.cjs +20 -0
  10. package/build/lib/createFormFactory.cjs.map +1 -0
  11. package/build/{types/react-form/src → lib}/createFormFactory.d.ts +1 -0
  12. package/build/lib/createFormFactory.d.ts.map +1 -0
  13. package/build/lib/createFormFactory.js +18 -0
  14. package/build/{cjs → lib}/createFormFactory.js.map +1 -1
  15. package/build/lib/createFormFactory.legacy.cjs +20 -0
  16. package/build/lib/createFormFactory.legacy.cjs.map +1 -0
  17. package/build/lib/createFormFactory.legacy.js +18 -0
  18. package/build/lib/createFormFactory.legacy.js.map +1 -0
  19. package/build/{cjs/formContext.js → lib/formContext.cjs} +4 -19
  20. package/build/lib/formContext.cjs.map +1 -0
  21. package/build/{types/react-form/src → lib}/formContext.d.ts +1 -0
  22. package/build/lib/formContext.d.ts.map +1 -0
  23. package/build/lib/formContext.js +13 -0
  24. package/build/{cjs → lib}/formContext.js.map +1 -1
  25. package/build/lib/formContext.legacy.cjs +35 -0
  26. package/build/lib/formContext.legacy.cjs.map +1 -0
  27. package/build/lib/formContext.legacy.js +13 -0
  28. package/build/lib/formContext.legacy.js.map +1 -0
  29. package/build/{cjs/index.js → lib/index.cjs} +4 -16
  30. package/build/lib/index.cjs.map +1 -0
  31. package/build/{types/react-form/src → lib}/index.d.ts +1 -0
  32. package/build/lib/index.d.ts.map +1 -0
  33. package/build/lib/index.js +5 -0
  34. package/build/{cjs → lib}/index.js.map +1 -1
  35. package/build/lib/index.legacy.cjs +26 -0
  36. package/build/lib/index.legacy.cjs.map +1 -0
  37. package/build/lib/index.legacy.js +5 -0
  38. package/build/lib/index.legacy.js.map +1 -0
  39. package/build/lib/tests/createFormFactory.test.d.ts +2 -0
  40. package/build/lib/tests/createFormFactory.test.d.ts.map +1 -0
  41. package/build/lib/tests/useForm.test.d.ts +2 -0
  42. package/build/lib/tests/useForm.test.d.ts.map +1 -0
  43. package/build/{cjs/useField.js → lib/useField.cjs} +22 -24
  44. package/build/lib/useField.cjs.map +1 -0
  45. package/build/{types/react-form/src → lib}/useField.d.ts +1 -1
  46. package/build/lib/useField.d.ts.map +1 -0
  47. package/build/lib/useField.js +74 -0
  48. package/build/lib/useField.js.map +1 -0
  49. package/build/lib/useField.legacy.cjs +96 -0
  50. package/build/lib/useField.legacy.cjs.map +1 -0
  51. package/build/lib/useField.legacy.js +74 -0
  52. package/build/lib/useField.legacy.js.map +1 -0
  53. package/build/lib/useForm.cjs +52 -0
  54. package/build/lib/useForm.cjs.map +1 -0
  55. package/build/{types/react-form/src → lib}/useForm.d.ts +1 -0
  56. package/build/lib/useForm.d.ts.map +1 -0
  57. package/build/lib/useForm.js +50 -0
  58. package/build/lib/useForm.js.map +1 -0
  59. package/build/lib/useForm.legacy.cjs +52 -0
  60. package/build/lib/useForm.legacy.cjs.map +1 -0
  61. package/build/lib/useForm.legacy.js +50 -0
  62. package/build/lib/useForm.legacy.js.map +1 -0
  63. package/package.json +29 -11
  64. package/src/tests/createFormFactory.test.tsx +39 -0
  65. package/src/tests/useForm.test.tsx +75 -0
  66. package/src/useField.tsx +1 -1
  67. package/src/useForm.tsx +5 -1
  68. package/build/cjs/_virtual/_rollupPluginBabelHelpers.js.map +0 -1
  69. package/build/cjs/createFormFactory.js +0 -31
  70. package/build/cjs/useField.js.map +0 -1
  71. package/build/cjs/useForm.js +0 -67
  72. package/build/cjs/useForm.js.map +0 -1
  73. package/build/esm/index.js +0 -154
  74. package/build/esm/index.js.map +0 -1
  75. package/build/stats-html.html +0 -2689
  76. package/build/stats-react.json +0 -362
  77. package/build/types/form-core/src/FieldApi.d.ts +0 -85
  78. package/build/types/form-core/src/FormApi.d.ts +0 -82
  79. package/build/types/form-core/src/index.d.ts +0 -3
  80. package/build/types/form-core/src/utils.d.ts +0 -22
  81. package/build/types/index.d.ts +0 -74
  82. package/build/types/react-form/src/tests/test.test.d.ts +0 -0
  83. package/build/umd/index.development.js +0 -985
  84. package/build/umd/index.development.js.map +0 -1
  85. package/build/umd/index.production.js +0 -43
  86. package/build/umd/index.production.js.map +0 -1
  87. package/src/tests/test.test.tsx +0 -5
@@ -1,985 +0,0 @@
1
- /**
2
- * react-form
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, require('use-sync-external-store/shim/with-selector'), require('react')) :
13
- typeof define === 'function' && define.amd ? define(['exports', 'use-sync-external-store/shim/with-selector', 'react'], factory) :
14
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ReactForm = {}, global.withSelector, global.React));
15
- })(this, (function (exports, withSelector, React) { 'use strict';
16
-
17
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
18
-
19
- function _interopNamespace(e) {
20
- if (e && e.__esModule) return e;
21
- var n = Object.create(null);
22
- if (e) {
23
- Object.keys(e).forEach(function (k) {
24
- if (k !== 'default') {
25
- var d = Object.getOwnPropertyDescriptor(e, k);
26
- Object.defineProperty(n, k, d.get ? d : {
27
- enumerable: true,
28
- get: function () { return e[k]; }
29
- });
30
- }
31
- });
32
- }
33
- n["default"] = e;
34
- return Object.freeze(n);
35
- }
36
-
37
- var React__namespace = /*#__PURE__*/_interopNamespace(React);
38
- var React__default = /*#__PURE__*/_interopDefaultLegacy(React);
39
-
40
- /**
41
- * store
42
- *
43
- * Copyright (c) TanStack
44
- *
45
- * This source code is licensed under the MIT license found in the
46
- * LICENSE.md file in the root directory of this source tree.
47
- *
48
- * @license MIT
49
- */
50
- class Store {
51
- listeners = new Set();
52
- #batching = false;
53
- #flushing = 0;
54
- constructor(initialState, options) {
55
- this.state = initialState;
56
- this.options = options;
57
- if (this.options?.onUpdate) {
58
- this.subscribe(this.options?.onUpdate);
59
- }
60
- }
61
- subscribe = listener => {
62
- this.listeners.add(listener);
63
- const unsub = this.options?.onSubscribe?.(listener, this);
64
- return () => {
65
- this.listeners.delete(listener);
66
- unsub?.();
67
- };
68
- };
69
- setState = updater => {
70
- const previous = this.state;
71
- this.state = this.options?.updateFn ? this.options.updateFn(previous)(updater) : updater(previous);
72
- this.#flush();
73
- };
74
- #flush = () => {
75
- if (this.#batching) return;
76
- const flushId = ++this.#flushing;
77
- this.listeners.forEach(listener => {
78
- if (this.#flushing !== flushId) return;
79
- listener();
80
- });
81
- };
82
- batch = cb => {
83
- if (this.#batching) return cb();
84
- this.#batching = true;
85
- cb();
86
- this.#batching = false;
87
- this.#flush();
88
- };
89
- }
90
-
91
- /**
92
- * form-core
93
- *
94
- * Copyright (c) TanStack
95
- *
96
- * This source code is licensed under the MIT license found in the
97
- * LICENSE.md file in the root directory of this source tree.
98
- *
99
- * @license MIT
100
- */
101
-
102
- function _defineProperty(obj, key, value) {
103
- if (key in obj) {
104
- Object.defineProperty(obj, key, {
105
- value: value,
106
- enumerable: true,
107
- configurable: true,
108
- writable: true
109
- });
110
- } else {
111
- obj[key] = value;
112
- }
113
-
114
- return obj;
115
- }
116
-
117
- function _classPrivateFieldGet(receiver, privateMap) {
118
- var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "get");
119
-
120
- return _classApplyDescriptorGet(receiver, descriptor);
121
- }
122
-
123
- function _classPrivateFieldSet(receiver, privateMap, value) {
124
- var descriptor = _classExtractFieldDescriptor(receiver, privateMap, "set");
125
-
126
- _classApplyDescriptorSet(receiver, descriptor, value);
127
-
128
- return value;
129
- }
130
-
131
- function _classExtractFieldDescriptor(receiver, privateMap, action) {
132
- if (!privateMap.has(receiver)) {
133
- throw new TypeError("attempted to " + action + " private field on non-instance");
134
- }
135
-
136
- return privateMap.get(receiver);
137
- }
138
-
139
- function _classApplyDescriptorGet(receiver, descriptor) {
140
- if (descriptor.get) {
141
- return descriptor.get.call(receiver);
142
- }
143
-
144
- return descriptor.value;
145
- }
146
-
147
- function _classApplyDescriptorSet(receiver, descriptor, value) {
148
- if (descriptor.set) {
149
- descriptor.set.call(receiver, value);
150
- } else {
151
- if (!descriptor.writable) {
152
- throw new TypeError("attempted to set read only private field");
153
- }
154
-
155
- descriptor.value = value;
156
- }
157
- }
158
-
159
- function _checkPrivateRedeclaration(obj, privateCollection) {
160
- if (privateCollection.has(obj)) {
161
- throw new TypeError("Cannot initialize the same private elements twice on an object");
162
- }
163
- }
164
-
165
- function _classPrivateFieldInitSpec(obj, privateMap, value) {
166
- _checkPrivateRedeclaration(obj, privateMap);
167
-
168
- privateMap.set(obj, value);
169
- }
170
-
171
- function functionalUpdate(updater, input) {
172
- return typeof updater === 'function' ? updater(input) : updater;
173
- }
174
- function getBy(obj, path) {
175
- const pathArray = makePathArray(path);
176
- const pathObj = pathArray;
177
- return pathObj.reduce((current, pathPart) => {
178
- if (typeof current !== 'undefined') {
179
- return current[pathPart];
180
- }
181
-
182
- return undefined;
183
- }, obj);
184
- }
185
- function setBy(obj, _path, updater) {
186
- const path = makePathArray(_path);
187
-
188
- function doSet(parent) {
189
- if (!path.length) {
190
- return functionalUpdate(updater, parent);
191
- }
192
-
193
- const key = path.shift();
194
-
195
- if (typeof key === 'string') {
196
- if (typeof parent === 'object') {
197
- return { ...parent,
198
- [key]: doSet(parent[key])
199
- };
200
- }
201
-
202
- return {
203
- [key]: doSet()
204
- };
205
- }
206
-
207
- if (typeof key === 'number') {
208
- if (Array.isArray(parent)) {
209
- const prefix = parent.slice(0, key);
210
- return [...(prefix.length ? prefix : new Array(key)), doSet(parent[key]), ...parent.slice(key + 1)];
211
- }
212
-
213
- return [...new Array(key), doSet()];
214
- }
215
-
216
- throw new Error('Uh oh!');
217
- }
218
-
219
- return doSet(obj);
220
- }
221
- const reFindNumbers0 = /^(\d*)$/gm;
222
- const reFindNumbers1 = /\.(\d*)\./gm;
223
- const reFindNumbers2 = /^(\d*)\./gm;
224
- const reFindNumbers3 = /\.(\d*$)/gm;
225
- const reFindMultiplePeriods = /\.{2,}/gm;
226
- const intPrefix = '__int__';
227
- const intReplace = intPrefix + "$1";
228
-
229
- function makePathArray(str) {
230
- if (typeof str !== 'string') {
231
- throw new Error();
232
- }
233
-
234
- return str.replace('[', '.').replace(']', '').replace(reFindNumbers0, intReplace).replace(reFindNumbers1, "." + intReplace + ".").replace(reFindNumbers2, intReplace + ".").replace(reFindNumbers3, "." + intReplace).replace(reFindMultiplePeriods, '.').split('.').map(d => {
235
- if (d.indexOf(intPrefix) === 0) {
236
- return parseInt(d.substring(intPrefix.length), 10);
237
- }
238
-
239
- return d;
240
- });
241
- }
242
-
243
- function getDefaultFormState(defaultState) {
244
- return {
245
- values: {},
246
- fieldMeta: {},
247
- canSubmit: true,
248
- isFieldsValid: false,
249
- isFieldsValidating: false,
250
- isFormValid: false,
251
- isFormValidating: false,
252
- isSubmitted: false,
253
- isSubmitting: false,
254
- isTouched: false,
255
- isValid: false,
256
- isValidating: false,
257
- submissionAttempts: 0,
258
- formValidationCount: 0,
259
- ...defaultState
260
- };
261
- }
262
-
263
- class FormApi {
264
- // // This carries the context for nested fields
265
- // Do not use __state directly, as it is not reactive.
266
- // Please use form.useStore() utility to subscribe to state
267
- constructor(_opts) {
268
- var _opts$defaultValues, _opts$defaultState;
269
-
270
- _defineProperty(this, "options", {});
271
-
272
- _defineProperty(this, "store", void 0);
273
-
274
- _defineProperty(this, "state", void 0);
275
-
276
- _defineProperty(this, "fieldInfo", {});
277
-
278
- _defineProperty(this, "fieldName", void 0);
279
-
280
- _defineProperty(this, "validationMeta", {});
281
-
282
- _defineProperty(this, "update", options => {
283
- if (!options) return;
284
- this.store.batch(() => {
285
- if (options.defaultState && options.defaultState !== this.options.defaultState) {
286
- this.store.setState(prev => ({ ...prev,
287
- ...options.defaultState
288
- }));
289
- }
290
-
291
- if (options.defaultValues !== this.options.defaultValues) {
292
- this.store.setState(() => getDefaultFormState(options.defaultValues));
293
- }
294
- });
295
- this.options = options;
296
- });
297
-
298
- _defineProperty(this, "reset", () => this.store.setState(() => getDefaultFormState(this.options.defaultValues)));
299
-
300
- _defineProperty(this, "validateAllFields", async cause => {
301
- const fieldValidationPromises = [];
302
- this.store.batch(() => {
303
- void Object.values(this.fieldInfo).forEach(field => {
304
- Object.values(field.instances).forEach(instance => {
305
- // If any fields are not touched
306
- if (!instance.state.meta.isTouched) {
307
- // Mark them as touched
308
- instance.setMeta(prev => ({ ...prev,
309
- isTouched: true
310
- })); // Validate the field
311
-
312
- fieldValidationPromises.push(Promise.resolve().then(() => instance.validate(cause)));
313
- }
314
- });
315
- });
316
- });
317
- return Promise.all(fieldValidationPromises);
318
- });
319
-
320
- _defineProperty(this, "handleSubmit", async e => {
321
- e.preventDefault();
322
- e.stopPropagation(); // Check to see that the form and all fields have been touched
323
- // If they have not, touch them all and run validation
324
- // Run form validation
325
- // Submit the form
326
-
327
- this.store.setState(old => ({ ...old,
328
- // Submittion attempts mark the form as not submitted
329
- isSubmitted: false,
330
- // Count submission attempts
331
- submissionAttempts: old.submissionAttempts + 1
332
- })); // Don't let invalid forms submit
333
-
334
- if (!this.state.canSubmit) return;
335
- this.store.setState(d => ({ ...d,
336
- isSubmitting: true
337
- }));
338
-
339
- const done = () => {
340
- this.store.setState(prev => ({ ...prev,
341
- isSubmitting: false
342
- }));
343
- }; // Validate all fields
344
-
345
-
346
- await this.validateAllFields('submit'); // Fields are invalid, do not submit
347
-
348
- if (!this.state.isFieldsValid) {
349
- var _this$options$onSubmi, _this$options;
350
-
351
- done();
352
- (_this$options$onSubmi = (_this$options = this.options).onSubmitInvalid) == null ? void 0 : _this$options$onSubmi.call(_this$options, this.state.values, this);
353
- return;
354
- } // Run validation for the form
355
- // await this.validateForm()
356
-
357
-
358
- if (!this.state.isValid) {
359
- var _this$options$onSubmi2, _this$options2;
360
-
361
- done();
362
- (_this$options$onSubmi2 = (_this$options2 = this.options).onSubmitInvalid) == null ? void 0 : _this$options$onSubmi2.call(_this$options2, this.state.values, this);
363
- return;
364
- }
365
-
366
- try {
367
- var _this$options$onSubmi3, _this$options3;
368
-
369
- // Run the submit code
370
- await ((_this$options$onSubmi3 = (_this$options3 = this.options).onSubmit) == null ? void 0 : _this$options$onSubmi3.call(_this$options3, this.state.values, this));
371
- this.store.batch(() => {
372
- this.store.setState(prev => ({ ...prev,
373
- isSubmitted: true
374
- }));
375
- done();
376
- });
377
- } catch (err) {
378
- done();
379
- throw err;
380
- }
381
- });
382
-
383
- _defineProperty(this, "getFieldValue", field => getBy(this.state.values, field));
384
-
385
- _defineProperty(this, "getFieldMeta", field => {
386
- return this.state.fieldMeta[field];
387
- });
388
-
389
- _defineProperty(this, "getFieldInfo", field => {
390
- var _this$fieldInfo;
391
-
392
- return (_this$fieldInfo = this.fieldInfo)[field] || (_this$fieldInfo[field] = {
393
- instances: {}
394
- });
395
- });
396
-
397
- _defineProperty(this, "setFieldMeta", (field, updater) => {
398
- this.store.setState(prev => {
399
- return { ...prev,
400
- fieldMeta: { ...prev.fieldMeta,
401
- [field]: functionalUpdate(updater, prev.fieldMeta[field])
402
- }
403
- };
404
- });
405
- });
406
-
407
- _defineProperty(this, "setFieldValue", (field, updater, opts) => {
408
- const touch = opts == null ? void 0 : opts.touch;
409
- this.store.batch(() => {
410
- if (touch) {
411
- this.setFieldMeta(field, prev => ({ ...prev,
412
- isTouched: true
413
- }));
414
- }
415
-
416
- this.store.setState(prev => {
417
- return { ...prev,
418
- values: setBy(prev.values, field, updater)
419
- };
420
- });
421
- });
422
- });
423
-
424
- _defineProperty(this, "pushFieldValue", (field, value, opts) => {
425
- return this.setFieldValue(field, prev => [...(Array.isArray(prev) ? prev : []), value], opts);
426
- });
427
-
428
- _defineProperty(this, "insertFieldValue", (field, index, value, opts) => {
429
- this.setFieldValue(field, prev => {
430
- return prev.map((d, i) => i === index ? value : d);
431
- }, opts);
432
- });
433
-
434
- _defineProperty(this, "removeFieldValue", (field, index, opts) => {
435
- this.setFieldValue(field, prev => {
436
- return prev.filter((_d, i) => i !== index);
437
- }, opts);
438
- });
439
-
440
- _defineProperty(this, "swapFieldValues", (field, index1, index2) => {
441
- this.setFieldValue(field, prev => {
442
- const prev1 = prev[index1];
443
- const prev2 = prev[index2];
444
- return setBy(setBy(prev, [index1], prev2), [index2], prev1);
445
- });
446
- });
447
-
448
- this.store = new Store(getDefaultFormState({ ...(_opts == null ? void 0 : _opts.defaultState),
449
- 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,
450
- isFormValid: true
451
- }), {
452
- onUpdate: () => {
453
- let {
454
- state
455
- } = this.store; // Computed state
456
-
457
- const fieldMetaValues = Object.values(state.fieldMeta);
458
- const isFieldsValidating = fieldMetaValues.some(field => field == null ? void 0 : field.isValidating);
459
- const isFieldsValid = !fieldMetaValues.some(field => field == null ? void 0 : field.error);
460
- const isTouched = fieldMetaValues.some(field => field == null ? void 0 : field.isTouched);
461
- const isValidating = isFieldsValidating || state.isFormValidating;
462
- const isFormValid = !state.formError;
463
- const isValid = isFieldsValid && isFormValid;
464
- const canSubmit = state.submissionAttempts === 0 && !isTouched || !isValidating && !state.isSubmitting && isValid;
465
- state = { ...state,
466
- isFieldsValidating,
467
- isFieldsValid,
468
- isFormValid,
469
- isValid,
470
- canSubmit,
471
- isTouched
472
- };
473
- this.store.state = state;
474
- this.state = state;
475
- }
476
- });
477
- this.state = this.store.state;
478
- this.update(_opts || {});
479
- }
480
-
481
- }
482
-
483
- let uid = 0;
484
-
485
- var _prevState = /*#__PURE__*/new WeakMap();
486
-
487
- var _leaseValidateAsync = /*#__PURE__*/new WeakMap();
488
-
489
- class FieldApi {
490
- constructor(_opts) {
491
- var _this$getMeta;
492
-
493
- _defineProperty(this, "uid", void 0);
494
-
495
- _defineProperty(this, "form", void 0);
496
-
497
- _defineProperty(this, "name", void 0);
498
-
499
- _defineProperty(this, "store", void 0);
500
-
501
- _defineProperty(this, "state", void 0);
502
-
503
- _classPrivateFieldInitSpec(this, _prevState, {
504
- writable: true,
505
- value: void 0
506
- });
507
-
508
- _defineProperty(this, "options", {});
509
-
510
- _defineProperty(this, "mount", () => {
511
- var _this$options$onMount, _this$options;
512
-
513
- const info = this.getInfo();
514
- info.instances[this.uid] = this;
515
- const unsubscribe = this.form.store.subscribe(() => {
516
- this.store.batch(() => {
517
- const nextValue = this.getValue();
518
- const nextMeta = this.getMeta();
519
-
520
- if (nextValue !== this.state.value) {
521
- this.store.setState(prev => ({ ...prev,
522
- value: nextValue
523
- }));
524
- }
525
-
526
- if (nextMeta !== this.state.meta) {
527
- this.store.setState(prev => ({ ...prev,
528
- meta: nextMeta
529
- }));
530
- }
531
- });
532
- });
533
- (_this$options$onMount = (_this$options = this.options).onMount) == null ? void 0 : _this$options$onMount.call(_this$options, this);
534
- return () => {
535
- unsubscribe();
536
- delete info.instances[this.uid];
537
-
538
- if (!Object.keys(info.instances).length) {
539
- delete this.form.fieldInfo[this.name];
540
- }
541
- };
542
- });
543
-
544
- _defineProperty(this, "update", opts => {
545
- var _this$form$options$as, _this$form$options$on, _this$form$options$on2;
546
-
547
- this.options = {
548
- asyncDebounceMs: (_this$form$options$as = this.form.options.asyncDebounceMs) != null ? _this$form$options$as : 0,
549
- onChangeAsyncDebounceMs: (_this$form$options$on = this.form.options.onChangeAsyncDebounceMs) != null ? _this$form$options$on : 0,
550
- onBlurAsyncDebounceMs: (_this$form$options$on2 = this.form.options.onBlurAsyncDebounceMs) != null ? _this$form$options$on2 : 0,
551
- ...opts
552
- }; // Default Value
553
-
554
- if (this.state.value === undefined && this.options.defaultValue !== undefined) {
555
- this.setValue(this.options.defaultValue);
556
- } // Default Meta
557
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
558
-
559
-
560
- if (this.getMeta() === undefined) {
561
- this.setMeta(this.state.meta);
562
- }
563
- });
564
-
565
- _defineProperty(this, "getValue", () => {
566
- return this.form.getFieldValue(this.name);
567
- });
568
-
569
- _defineProperty(this, "setValue", (updater, options) => this.form.setFieldValue(this.name, updater, options));
570
-
571
- _defineProperty(this, "getMeta", () => this.form.getFieldMeta(this.name));
572
-
573
- _defineProperty(this, "setMeta", updater => this.form.setFieldMeta(this.name, updater));
574
-
575
- _defineProperty(this, "getInfo", () => this.form.getFieldInfo(this.name));
576
-
577
- _defineProperty(this, "pushValue", value => this.form.pushFieldValue(this.name, value));
578
-
579
- _defineProperty(this, "insertValue", (index, value) => this.form.insertFieldValue(this.name, index, value));
580
-
581
- _defineProperty(this, "removeValue", index => this.form.removeFieldValue(this.name, index));
582
-
583
- _defineProperty(this, "swapValues", (aIndex, bIndex) => this.form.swapFieldValues(this.name, aIndex, bIndex));
584
-
585
- _defineProperty(this, "getSubField", name => new FieldApi({
586
- name: this.name + "." + name,
587
- form: this.form
588
- }));
589
-
590
- _defineProperty(this, "validateSync", async (value = this.state.value, cause) => {
591
- const {
592
- onChange,
593
- onBlur
594
- } = this.options;
595
- const validate = cause === 'submit' ? undefined : cause === 'change' ? onChange : onBlur;
596
- if (!validate) return; // Use the validationCount for all field instances to
597
- // track freshness of the validation
598
-
599
- const validationCount = (this.getInfo().validationCount || 0) + 1;
600
- this.getInfo().validationCount = validationCount;
601
- const error = normalizeError(validate(value, this));
602
-
603
- if (this.state.meta.error !== error) {
604
- this.setMeta(prev => ({ ...prev,
605
- error
606
- }));
607
- } // If a sync error is encountered, cancel any async validation
608
-
609
-
610
- if (this.state.meta.error) {
611
- this.cancelValidateAsync();
612
- }
613
- });
614
-
615
- _classPrivateFieldInitSpec(this, _leaseValidateAsync, {
616
- writable: true,
617
- value: () => {
618
- const count = (this.getInfo().validationAsyncCount || 0) + 1;
619
- this.getInfo().validationAsyncCount = count;
620
- return count;
621
- }
622
- });
623
-
624
- _defineProperty(this, "cancelValidateAsync", () => {
625
- // Lease a new validation count to ignore any pending validations
626
- _classPrivateFieldGet(this, _leaseValidateAsync).call(this); // Cancel any pending validation state
627
-
628
-
629
- this.setMeta(prev => ({ ...prev,
630
- isValidating: false
631
- }));
632
- });
633
-
634
- _defineProperty(this, "validateAsync", async (value = this.state.value, cause) => {
635
- var _ref, _ref2;
636
-
637
- const {
638
- onChangeAsync,
639
- onBlurAsync,
640
- onSubmitAsync,
641
- asyncDebounceMs,
642
- onBlurAsyncDebounceMs,
643
- onChangeAsyncDebounceMs
644
- } = this.options;
645
- const validate = cause === 'change' ? onChangeAsync : cause === 'submit' ? onSubmitAsync : onBlurAsync;
646
- if (!validate) return;
647
- const debounceMs = cause === 'submit' ? 0 : (_ref = (_ref2 = cause === 'change' ? onChangeAsyncDebounceMs : onBlurAsyncDebounceMs) != null ? _ref2 : asyncDebounceMs) != null ? _ref : 500;
648
- if (this.state.meta.isValidating !== true) this.setMeta(prev => ({ ...prev,
649
- isValidating: true
650
- })); // Use the validationCount for all field instances to
651
- // track freshness of the validation
652
-
653
- const validationAsyncCount = _classPrivateFieldGet(this, _leaseValidateAsync).call(this);
654
-
655
- const checkLatest = () => validationAsyncCount === this.getInfo().validationAsyncCount;
656
-
657
- if (!this.getInfo().validationPromise) {
658
- this.getInfo().validationPromise = new Promise((resolve, reject) => {
659
- this.getInfo().validationResolve = resolve;
660
- this.getInfo().validationReject = reject;
661
- });
662
- }
663
-
664
- if (debounceMs > 0) {
665
- await new Promise(r => setTimeout(r, debounceMs));
666
- } // Only kick off validation if this validation is the latest attempt
667
-
668
-
669
- if (checkLatest()) {
670
- try {
671
- const rawError = await validate(value, this);
672
-
673
- if (checkLatest()) {
674
- var _this$getInfo$validat, _this$getInfo;
675
-
676
- const error = normalizeError(rawError);
677
- this.setMeta(prev => ({ ...prev,
678
- isValidating: false,
679
- error
680
- }));
681
- (_this$getInfo$validat = (_this$getInfo = this.getInfo()).validationResolve) == null ? void 0 : _this$getInfo$validat.call(_this$getInfo, error);
682
- }
683
- } catch (error) {
684
- if (checkLatest()) {
685
- var _this$getInfo$validat2, _this$getInfo2;
686
-
687
- (_this$getInfo$validat2 = (_this$getInfo2 = this.getInfo()).validationReject) == null ? void 0 : _this$getInfo$validat2.call(_this$getInfo2, error);
688
- throw error;
689
- }
690
- } finally {
691
- if (checkLatest()) {
692
- this.setMeta(prev => ({ ...prev,
693
- isValidating: false
694
- }));
695
- delete this.getInfo().validationPromise;
696
- }
697
- }
698
- } // Always return the latest validation promise to the caller
699
-
700
-
701
- return this.getInfo().validationPromise;
702
- });
703
-
704
- _defineProperty(this, "validate", (cause, value) => {
705
- // If the field is pristine and validatePristine is false, do not validate
706
- if (!this.state.meta.isTouched) return; // Attempt to sync validate first
707
-
708
- this.validateSync(value, cause); // If there is an error, return it, do not attempt async validation
709
-
710
- if (this.state.meta.error) {
711
- if (!this.options.asyncAlways) {
712
- return this.state.meta.error;
713
- }
714
- } // No error? Attempt async validation
715
-
716
-
717
- return this.validateAsync(value, cause);
718
- });
719
-
720
- _defineProperty(this, "getChangeProps", (props = {}) => {
721
- return { ...props,
722
- value: this.state.value,
723
- onChange: value => {
724
- this.setValue(value);
725
- props.onChange == null ? void 0 : props.onChange(value);
726
- },
727
- onBlur: e => {
728
- const prevTouched = this.state.meta.isTouched;
729
- this.setMeta(prev => ({ ...prev,
730
- isTouched: true
731
- }));
732
-
733
- if (!prevTouched) {
734
- this.validate('change');
735
- }
736
-
737
- this.validate('blur');
738
- }
739
- };
740
- });
741
-
742
- _defineProperty(this, "getInputProps", (props = {}) => {
743
- return { ...props,
744
- value: String(this.state.value),
745
- onChange: e => {
746
- this.setValue(e.target.value);
747
- props.onChange == null ? void 0 : props.onChange(e.target.value);
748
- },
749
- onBlur: this.getChangeProps(props).onBlur
750
- };
751
- });
752
-
753
- this.form = _opts.form;
754
- this.uid = uid++; // Support field prefixing from FieldScope
755
- // let fieldPrefix = ''
756
- // if (this.form.fieldName) {
757
- // fieldPrefix = `${this.form.fieldName}.`
758
- // }
759
-
760
- this.name = _opts.name;
761
- this.store = new Store({
762
- value: this.getValue(),
763
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
764
- meta: (_this$getMeta = this.getMeta()) != null ? _this$getMeta : {
765
- isValidating: false,
766
- isTouched: false,
767
- ...this.options.defaultMeta
768
- }
769
- }, {
770
- onUpdate: () => {
771
- const state = this.store.state;
772
- state.meta.touchedError = state.meta.isTouched ? state.meta.error : undefined;
773
-
774
- if (state.value !== _classPrivateFieldGet(this, _prevState).value) {
775
- this.validate('change', state.value);
776
- }
777
-
778
- _classPrivateFieldSet(this, _prevState, state);
779
-
780
- this.state = state;
781
- }
782
- });
783
- this.state = this.store.state;
784
-
785
- _classPrivateFieldSet(this, _prevState, this.state);
786
-
787
- this.update(_opts);
788
- }
789
-
790
- }
791
-
792
- function normalizeError(rawError) {
793
- if (rawError) {
794
- if (typeof rawError !== 'string') {
795
- return 'Invalid Form Values';
796
- }
797
-
798
- return rawError;
799
- }
800
-
801
- return undefined;
802
- }
803
-
804
- function _extends() {
805
- _extends = Object.assign ? Object.assign.bind() : function (target) {
806
- for (var i = 1; i < arguments.length; i++) {
807
- var source = arguments[i];
808
-
809
- for (var key in source) {
810
- if (Object.prototype.hasOwnProperty.call(source, key)) {
811
- target[key] = source[key];
812
- }
813
- }
814
- }
815
-
816
- return target;
817
- };
818
- return _extends.apply(this, arguments);
819
- }
820
-
821
- /**
822
- * react-store
823
- *
824
- * Copyright (c) TanStack
825
- *
826
- * This source code is licensed under the MIT license found in the
827
- * LICENSE.md file in the root directory of this source tree.
828
- *
829
- * @license MIT
830
- */
831
-
832
- function useStore(store, selector = d => d) {
833
- const slice = withSelector.useSyncExternalStoreWithSelector(store.subscribe, () => store.state, () => store.state, selector, shallow);
834
- return slice;
835
- }
836
- function shallow(objA, objB) {
837
- if (Object.is(objA, objB)) {
838
- return true;
839
- }
840
- if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
841
- return false;
842
- }
843
- const keysA = Object.keys(objA);
844
- if (keysA.length !== Object.keys(objB).length) {
845
- return false;
846
- }
847
- for (let i = 0; i < keysA.length; i++) {
848
- if (!Object.prototype.hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) {
849
- return false;
850
- }
851
- }
852
- return true;
853
- }
854
-
855
- const formContext = /*#__PURE__*/React__namespace.createContext(null);
856
- function useFormContext() {
857
- const formApi = React__namespace.useContext(formContext);
858
-
859
- if (!formApi) {
860
- throw new Error("You are trying to use the form API outside of a form!");
861
- }
862
-
863
- return formApi;
864
- }
865
-
866
- function useField(opts) {
867
- // Get the form API either manually or from context
868
- const {
869
- formApi,
870
- parentFieldName
871
- } = useFormContext();
872
- const [fieldApi] = React__namespace.useState(() => {
873
- const name = (typeof opts.index === 'number' ? [parentFieldName, opts.index, opts.name] : [parentFieldName, opts.name]).filter(d => d !== undefined).join('.');
874
- const api = new FieldApi({ ...opts,
875
- form: formApi,
876
- name: name
877
- });
878
- api.Field = Field;
879
- return api;
880
- }); // Keep options up to date as they are rendered
881
-
882
- fieldApi.update({ ...opts,
883
- form: formApi
884
- });
885
- useStore(fieldApi.store, opts.mode === 'array' ? state => {
886
- return [state.meta, Object.keys(state.value || []).length];
887
- } : undefined); // Instantiates field meta and removes it when unrendered
888
-
889
- React__namespace.useEffect(() => fieldApi.mount(), [fieldApi]);
890
- return fieldApi;
891
- } // export type FieldValue<TFormData, TField> = TFormData extends any[]
892
- // ? TField extends `[${infer TIndex extends number | 'i'}].${infer TRest}`
893
- // ? DeepValue<TFormData[TIndex extends 'i' ? number : TIndex], TRest>
894
- // : TField extends `[${infer TIndex extends number | 'i'}]`
895
- // ? TFormData[TIndex extends 'i' ? number : TIndex]
896
- // : never
897
- // : TField extends `${infer TPrefix}[${infer TIndex extends
898
- // | number
899
- // | 'i'}].${infer TRest}`
900
- // ? DeepValue<
901
- // DeepValue<TFormData, TPrefix>[TIndex extends 'i' ? number : TIndex],
902
- // TRest
903
- // >
904
- // : TField extends `${infer TPrefix}[${infer TIndex extends number | 'i'}]`
905
- // ? DeepValue<TFormData, TPrefix>[TIndex extends 'i' ? number : TIndex]
906
- // : DeepValue<TFormData, TField>
907
-
908
- function Field({
909
- children,
910
- ...fieldOptions
911
- }) {
912
- const fieldApi = useField(fieldOptions);
913
- return /*#__PURE__*/React__namespace.createElement(formContext.Provider, {
914
- value: {
915
- formApi: fieldApi.form,
916
- parentFieldName: fieldApi.name
917
- },
918
- children: functionalUpdate(children, fieldApi)
919
- });
920
- }
921
-
922
- function useForm(opts) {
923
- const [formApi] = React__default["default"].useState(() => {
924
- // @ts-ignore
925
- const api = new FormApi(opts);
926
-
927
- api.Provider = props => /*#__PURE__*/React__default["default"].createElement(formContext.Provider, _extends({}, props, {
928
- value: {
929
- formApi: api
930
- }
931
- }));
932
-
933
- api.getFormProps = () => {
934
- return {
935
- onSubmit: formApi.handleSubmit,
936
- disabled: api.state.isSubmitting
937
- };
938
- };
939
-
940
- api.Field = Field;
941
- api.useField = useField;
942
-
943
- api.useStore = ( // @ts-ignore
944
- selector) => {
945
- // eslint-disable-next-line react-hooks/rules-of-hooks
946
- return useStore(api.store, selector);
947
- };
948
-
949
- api.Subscribe = ( // @ts-ignore
950
- props) => {
951
- return functionalUpdate(props.children, // eslint-disable-next-line react-hooks/rules-of-hooks
952
- useStore(api.store, props.selector));
953
- };
954
-
955
- return api;
956
- });
957
- formApi.useStore(state => state.isSubmitting);
958
- formApi.update(opts);
959
- return formApi;
960
- }
961
-
962
- function createFormFactory(defaultOpts) {
963
- return {
964
- useForm: opts => {
965
- return useForm({ ...defaultOpts,
966
- ...opts
967
- });
968
- },
969
- useField: useField,
970
- Field: Field
971
- };
972
- }
973
-
974
- exports.Field = Field;
975
- exports.FieldApi = FieldApi;
976
- exports.FormApi = FormApi;
977
- exports.createFormFactory = createFormFactory;
978
- exports.functionalUpdate = functionalUpdate;
979
- exports.useField = useField;
980
- exports.useForm = useForm;
981
-
982
- Object.defineProperty(exports, '__esModule', { value: true });
983
-
984
- }));
985
- //# sourceMappingURL=index.development.js.map