@tanstack/form-core 0.11.0 → 0.13.0

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 (101) hide show
  1. package/dist/cjs/FieldApi.d.ts +94 -0
  2. package/dist/cjs/FormApi.d.ts +118 -0
  3. package/dist/cjs/index.cjs +926 -0
  4. package/dist/cjs/index.cjs.map +1 -0
  5. package/dist/cjs/index.d.cts +5 -0
  6. package/dist/cjs/index.d.ts +5 -0
  7. package/dist/cjs/index.js +926 -0
  8. package/dist/cjs/mergeForm.d.ts +4 -0
  9. package/dist/cjs/tests/FieldApi.spec.d.ts +1 -0
  10. package/dist/cjs/tests/FieldApi.test-d.d.ts +1 -0
  11. package/dist/cjs/tests/FormApi.spec.d.ts +1 -0
  12. package/dist/cjs/tests/mutateMergeDeep.spec.d.ts +1 -0
  13. package/dist/cjs/tests/utils.d.ts +1 -0
  14. package/dist/cjs/tests/utils.spec.d.ts +1 -0
  15. package/dist/cjs/types.d.ts +14 -0
  16. package/dist/cjs/utils.d.ts +57 -0
  17. package/dist/mjs/FieldApi.d.ts +94 -0
  18. package/dist/mjs/FormApi.d.ts +118 -0
  19. package/dist/mjs/index.d.mts +5 -0
  20. package/dist/mjs/index.d.ts +5 -0
  21. package/dist/mjs/index.js +926 -0
  22. package/dist/mjs/index.mjs +926 -0
  23. package/dist/mjs/index.mjs.map +1 -0
  24. package/dist/mjs/mergeForm.d.ts +4 -0
  25. package/dist/mjs/tests/FieldApi.spec.d.ts +1 -0
  26. package/dist/mjs/tests/FieldApi.test-d.d.ts +1 -0
  27. package/dist/mjs/tests/FormApi.spec.d.ts +1 -0
  28. package/dist/mjs/tests/mutateMergeDeep.spec.d.ts +1 -0
  29. package/dist/mjs/tests/utils.d.ts +1 -0
  30. package/dist/mjs/tests/utils.spec.d.ts +1 -0
  31. package/dist/mjs/types.d.ts +14 -0
  32. package/dist/mjs/utils.d.ts +57 -0
  33. package/package.json +16 -21
  34. package/src/FieldApi.ts +53 -38
  35. package/src/FormApi.ts +59 -23
  36. package/src/index.ts +1 -0
  37. package/src/mergeForm.ts +42 -0
  38. package/src/tests/FormApi.spec.ts +1 -0
  39. package/src/tests/mutateMergeDeep.spec.ts +32 -0
  40. package/src/types.ts +2 -1
  41. package/src/utils.ts +40 -23
  42. package/build/legacy/FieldApi.cjs +0 -313
  43. package/build/legacy/FieldApi.cjs.map +0 -1
  44. package/build/legacy/FieldApi.d.cts +0 -3
  45. package/build/legacy/FieldApi.d.ts +0 -3
  46. package/build/legacy/FieldApi.js +0 -288
  47. package/build/legacy/FieldApi.js.map +0 -1
  48. package/build/legacy/FormApi.cjs +0 -445
  49. package/build/legacy/FormApi.cjs.map +0 -1
  50. package/build/legacy/FormApi.d.cts +0 -3
  51. package/build/legacy/FormApi.d.ts +0 -3
  52. package/build/legacy/FormApi.js +0 -428
  53. package/build/legacy/FormApi.js.map +0 -1
  54. package/build/legacy/index.cjs +0 -31
  55. package/build/legacy/index.cjs.map +0 -1
  56. package/build/legacy/index.d.cts +0 -257
  57. package/build/legacy/index.d.ts +0 -257
  58. package/build/legacy/index.js +0 -6
  59. package/build/legacy/index.js.map +0 -1
  60. package/build/legacy/types.cjs +0 -19
  61. package/build/legacy/types.cjs.map +0 -1
  62. package/build/legacy/types.d.cts +0 -16
  63. package/build/legacy/types.d.ts +0 -16
  64. package/build/legacy/types.js +0 -1
  65. package/build/legacy/types.js.map +0 -1
  66. package/build/legacy/utils.cjs +0 -187
  67. package/build/legacy/utils.cjs.map +0 -1
  68. package/build/legacy/utils.d.cts +0 -3
  69. package/build/legacy/utils.d.ts +0 -3
  70. package/build/legacy/utils.js +0 -156
  71. package/build/legacy/utils.js.map +0 -1
  72. package/build/modern/FieldApi.cjs +0 -312
  73. package/build/modern/FieldApi.cjs.map +0 -1
  74. package/build/modern/FieldApi.d.cts +0 -3
  75. package/build/modern/FieldApi.d.ts +0 -3
  76. package/build/modern/FieldApi.js +0 -287
  77. package/build/modern/FieldApi.js.map +0 -1
  78. package/build/modern/FormApi.cjs +0 -439
  79. package/build/modern/FormApi.cjs.map +0 -1
  80. package/build/modern/FormApi.d.cts +0 -3
  81. package/build/modern/FormApi.d.ts +0 -3
  82. package/build/modern/FormApi.js +0 -422
  83. package/build/modern/FormApi.js.map +0 -1
  84. package/build/modern/index.cjs +0 -31
  85. package/build/modern/index.cjs.map +0 -1
  86. package/build/modern/index.d.cts +0 -257
  87. package/build/modern/index.d.ts +0 -257
  88. package/build/modern/index.js +0 -6
  89. package/build/modern/index.js.map +0 -1
  90. package/build/modern/types.cjs +0 -19
  91. package/build/modern/types.cjs.map +0 -1
  92. package/build/modern/types.d.cts +0 -16
  93. package/build/modern/types.d.ts +0 -16
  94. package/build/modern/types.js +0 -1
  95. package/build/modern/types.js.map +0 -1
  96. package/build/modern/utils.cjs +0 -187
  97. package/build/modern/utils.cjs.map +0 -1
  98. package/build/modern/utils.d.cts +0 -3
  99. package/build/modern/utils.d.ts +0 -3
  100. package/build/modern/utils.js +0 -156
  101. package/build/modern/utils.js.map +0 -1
@@ -1,312 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/FieldApi.ts
21
- var FieldApi_exports = {};
22
- __export(FieldApi_exports, {
23
- FieldApi: () => FieldApi
24
- });
25
- module.exports = __toCommonJS(FieldApi_exports);
26
- var import_store = require("@tanstack/store");
27
- var import_utils = require("./utils.cjs");
28
- var uid = 0;
29
- var FieldApi = class _FieldApi {
30
- constructor(opts) {
31
- this.options = {};
32
- this.mount = () => {
33
- const info = this.getInfo();
34
- info.instances[this.uid] = this;
35
- const unsubscribe = this.form.store.subscribe(() => {
36
- this.store.batch(() => {
37
- const nextValue = this.getValue();
38
- const nextMeta = this.getMeta();
39
- if (nextValue !== this.state.value) {
40
- this.store.setState((prev) => ({ ...prev, value: nextValue }));
41
- }
42
- if (nextMeta !== this.state.meta) {
43
- this.store.setState((prev) => ({ ...prev, meta: nextMeta }));
44
- }
45
- });
46
- });
47
- this.update(this.options);
48
- const { onMount } = this.options.validators || {};
49
- if (onMount) {
50
- const error = this.runValidator({
51
- validate: onMount,
52
- value: {
53
- value: this.state.value,
54
- fieldApi: this
55
- },
56
- type: "validate"
57
- });
58
- if (error) {
59
- this.setMeta((prev) => ({
60
- ...prev,
61
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
62
- errorMap: { ...prev?.errorMap, onMount: error }
63
- }));
64
- }
65
- }
66
- return () => {
67
- const preserveValue = this.options.preserveValue;
68
- unsubscribe();
69
- if (!preserveValue) {
70
- delete info.instances[this.uid];
71
- this.form.deleteField(this.name);
72
- }
73
- if (!Object.keys(info.instances).length && !preserveValue) {
74
- delete this.form.fieldInfo[this.name];
75
- }
76
- };
77
- };
78
- this.update = (opts) => {
79
- if (this.state.value === void 0) {
80
- const formDefault = opts.form.options.defaultValues?.[opts.name];
81
- if (opts.defaultValue !== void 0) {
82
- this.setValue(opts.defaultValue);
83
- } else if (formDefault !== void 0) {
84
- this.setValue(formDefault);
85
- }
86
- }
87
- if (this._getMeta() === void 0) {
88
- this.setMeta(this.state.meta);
89
- }
90
- this.options = opts;
91
- };
92
- this.getValue = () => {
93
- return this.form.getFieldValue(this.name);
94
- };
95
- this.setValue = (updater, options) => {
96
- this.form.setFieldValue(this.name, updater, options);
97
- this.validate("change", this.state.value);
98
- };
99
- this._getMeta = () => this.form.getFieldMeta(this.name);
100
- this.getMeta = () => this._getMeta() ?? {
101
- isValidating: false,
102
- isTouched: false,
103
- touchedErrors: [],
104
- errors: [],
105
- errorMap: {},
106
- ...this.options.defaultMeta
107
- };
108
- this.setMeta = (updater) => this.form.setFieldMeta(this.name, updater);
109
- this.getInfo = () => this.form.getFieldInfo(this.name);
110
- this.pushValue = (value) => this.form.pushFieldValue(this.name, value);
111
- this.insertValue = (index, value) => this.form.insertFieldValue(this.name, index, value);
112
- this.removeValue = (index) => this.form.removeFieldValue(this.name, index);
113
- this.swapValues = (aIndex, bIndex) => this.form.swapFieldValues(this.name, aIndex, bIndex);
114
- this.getSubField = (name) => new _FieldApi({
115
- name: `${this.name}.${name}`,
116
- form: this.form
117
- });
118
- this.validateSync = (value = this.state.value, cause) => {
119
- const validates = (0, import_utils.getSyncValidatorArray)(cause, this.options);
120
- let hasErrored = false;
121
- this.form.store.batch(() => {
122
- for (const validateObj of validates) {
123
- if (!validateObj.validate)
124
- continue;
125
- const error = normalizeError(
126
- this.runValidator({
127
- validate: validateObj.validate,
128
- value: { value, fieldApi: this },
129
- type: "validate"
130
- })
131
- );
132
- const errorMapKey = getErrorMapKey(validateObj.cause);
133
- if (this.state.meta.errorMap[errorMapKey] !== error) {
134
- this.setMeta((prev) => ({
135
- ...prev,
136
- errorMap: {
137
- ...prev.errorMap,
138
- [getErrorMapKey(validateObj.cause)]: error
139
- }
140
- }));
141
- }
142
- if (error) {
143
- hasErrored = true;
144
- }
145
- }
146
- });
147
- const submitErrKey = getErrorMapKey("submit");
148
- if (this.state.meta.errorMap[submitErrKey] && cause !== "submit" && !hasErrored) {
149
- this.setMeta((prev) => ({
150
- ...prev,
151
- errorMap: {
152
- ...prev.errorMap,
153
- [submitErrKey]: void 0
154
- }
155
- }));
156
- }
157
- return { hasErrored };
158
- };
159
- this.validateAsync = async (value = this.state.value, cause) => {
160
- const validates = (0, import_utils.getAsyncValidatorArray)(cause, this.options);
161
- if (!this.state.meta.isValidating) {
162
- this.setMeta((prev) => ({ ...prev, isValidating: true }));
163
- }
164
- const promises = [];
165
- for (const validateObj of validates) {
166
- if (!validateObj.validate)
167
- continue;
168
- const key = getErrorMapKey(validateObj.cause);
169
- const fieldValidatorMeta = this.getInfo().validationMetaMap[key];
170
- fieldValidatorMeta?.lastAbortController.abort();
171
- const controller = new AbortController();
172
- this.getInfo().validationMetaMap[key] = {
173
- lastAbortController: controller
174
- };
175
- promises.push(
176
- new Promise(async (resolve) => {
177
- let rawError;
178
- try {
179
- rawError = await new Promise((rawResolve, rawReject) => {
180
- setTimeout(() => {
181
- if (controller.signal.aborted)
182
- return rawResolve(void 0);
183
- this.runValidator({
184
- validate: validateObj.validate,
185
- value: { value, fieldApi: this, signal: controller.signal },
186
- type: "validateAsync"
187
- }).then(rawResolve).catch(rawReject);
188
- }, validateObj.debounceMs);
189
- });
190
- } catch (e) {
191
- rawError = e;
192
- }
193
- const error = normalizeError(rawError);
194
- this.setMeta((prev) => {
195
- return {
196
- ...prev,
197
- errorMap: {
198
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
199
- ...prev?.errorMap,
200
- [getErrorMapKey(cause)]: error
201
- }
202
- };
203
- });
204
- resolve(error);
205
- })
206
- );
207
- }
208
- let results = [];
209
- if (promises.length) {
210
- results = await Promise.all(promises);
211
- }
212
- this.setMeta((prev) => ({ ...prev, isValidating: false }));
213
- return results.filter(Boolean);
214
- };
215
- this.validate = (cause, value) => {
216
- if (!this.state.meta.isTouched)
217
- return [];
218
- try {
219
- this.form.validate(cause);
220
- } catch (_) {
221
- }
222
- const { hasErrored } = this.validateSync(value, cause);
223
- if (hasErrored && !this.options.asyncAlways) {
224
- return this.state.meta.errors;
225
- }
226
- return this.validateAsync(value, cause);
227
- };
228
- this.handleChange = (updater) => {
229
- this.setValue(updater, { touch: true });
230
- };
231
- this.handleBlur = () => {
232
- const prevTouched = this.state.meta.isTouched;
233
- if (!prevTouched) {
234
- this.setMeta((prev) => ({ ...prev, isTouched: true }));
235
- this.validate("change");
236
- }
237
- this.validate("blur");
238
- };
239
- this.form = opts.form;
240
- this.uid = uid++;
241
- this.name = opts.name;
242
- if (opts.defaultValue !== void 0) {
243
- this.form.setFieldValue(this.name, opts.defaultValue);
244
- }
245
- this.store = new import_store.Store(
246
- {
247
- value: this.getValue(),
248
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
249
- meta: this._getMeta() ?? {
250
- isValidating: false,
251
- isTouched: false,
252
- touchedErrors: [],
253
- errors: [],
254
- errorMap: {},
255
- ...opts.defaultMeta
256
- }
257
- },
258
- {
259
- onUpdate: () => {
260
- const state = this.store.state;
261
- state.meta.errors = Object.values(state.meta.errorMap).filter(
262
- (val) => val !== void 0
263
- );
264
- state.meta.touchedErrors = state.meta.isTouched ? state.meta.errors : [];
265
- this.prevState = state;
266
- this.state = state;
267
- }
268
- }
269
- );
270
- this.state = this.store.state;
271
- this.prevState = this.state;
272
- this.options = opts;
273
- }
274
- runValidator(props) {
275
- const adapters = [
276
- this.form.options.validatorAdapter,
277
- this.options.validatorAdapter
278
- ];
279
- for (const adapter of adapters) {
280
- if (adapter && typeof props.validate !== "function") {
281
- return adapter()[props.type](props.value, props.validate);
282
- }
283
- }
284
- return props.validate(props.value);
285
- }
286
- };
287
- function normalizeError(rawError) {
288
- if (rawError) {
289
- if (typeof rawError !== "string") {
290
- return "Invalid Form Values";
291
- }
292
- return rawError;
293
- }
294
- return void 0;
295
- }
296
- function getErrorMapKey(cause) {
297
- switch (cause) {
298
- case "submit":
299
- return "onSubmit";
300
- case "change":
301
- return "onChange";
302
- case "blur":
303
- return "onBlur";
304
- case "mount":
305
- return "onMount";
306
- }
307
- }
308
- // Annotate the CommonJS export names for ESM import in node:
309
- 0 && (module.exports = {
310
- FieldApi
311
- });
312
- //# sourceMappingURL=FieldApi.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/FieldApi.ts"],"sourcesContent":["import { Store } from '@tanstack/store'\nimport type { FormApi } from './FormApi'\nimport type {\n ValidationCause,\n ValidationError,\n ValidationErrorMap,\n Validator,\n} from './types'\nimport type { DeepKeys, DeepValue, Updater } from './utils'\nimport { getAsyncValidatorArray, getSyncValidatorArray } from './utils'\n\nexport type FieldValidateFn<\n TParentData,\n TName extends DeepKeys<TParentData>,\n TFieldValidator extends\n | Validator<DeepValue<TParentData, TName>, unknown>\n | undefined = undefined,\n TFormValidator extends\n | Validator<TParentData, unknown>\n | undefined = undefined,\n TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,\n> = (props: {\n value: TData\n fieldApi: FieldApi<TParentData, TName, TFieldValidator, TFormValidator, TData>\n}) => ValidationError\n\nexport type FieldValidateOrFn<\n TParentData,\n TName extends DeepKeys<TParentData>,\n TFieldValidator extends\n | Validator<DeepValue<TParentData, TName>, unknown>\n | undefined = undefined,\n TFormValidator extends\n | Validator<TParentData, unknown>\n | undefined = undefined,\n TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,\n> = TFieldValidator extends Validator<TData, infer TFN>\n ?\n | TFN\n | FieldValidateFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n : TFormValidator extends Validator<TParentData, infer FFN>\n ?\n | FFN\n | FieldValidateFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n : FieldValidateFn<TParentData, TName, TFieldValidator, TFormValidator, TData>\n\nexport type FieldValidateAsyncFn<\n TParentData,\n TName extends DeepKeys<TParentData>,\n TFieldValidator extends\n | Validator<DeepValue<TParentData, TName>, unknown>\n | undefined = undefined,\n TFormValidator extends\n | Validator<TParentData, unknown>\n | undefined = undefined,\n TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,\n> = (options: {\n value: TData\n fieldApi: FieldApi<TParentData, TName, TFieldValidator, TFormValidator, TData>\n signal: AbortSignal\n}) => ValidationError | Promise<ValidationError>\n\nexport type FieldAsyncValidateOrFn<\n TParentData,\n TName extends DeepKeys<TParentData>,\n TFieldValidator extends\n | Validator<DeepValue<TParentData, TName>, unknown>\n | undefined = undefined,\n TFormValidator extends\n | Validator<TParentData, unknown>\n | undefined = undefined,\n TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,\n> = TFieldValidator extends Validator<TData, infer TFN>\n ?\n | TFN\n | FieldValidateAsyncFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n : TFormValidator extends Validator<TParentData, infer FFN>\n ?\n | FFN\n | FieldValidateAsyncFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n : FieldValidateAsyncFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n\nexport interface FieldValidators<\n TParentData,\n TName extends DeepKeys<TParentData>,\n TFieldValidator extends\n | Validator<DeepValue<TParentData, TName>, unknown>\n | undefined = undefined,\n TFormValidator extends\n | Validator<TParentData, unknown>\n | undefined = undefined,\n TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,\n> {\n onMount?: FieldValidateOrFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n onChange?: FieldValidateOrFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n onChangeAsync?: FieldAsyncValidateOrFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n onChangeAsyncDebounceMs?: number\n onBlur?: FieldValidateOrFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n onBlurAsync?: FieldAsyncValidateOrFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n onBlurAsyncDebounceMs?: number\n onSubmit?: FieldValidateOrFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n onSubmitAsync?: FieldAsyncValidateOrFn<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n onSubmitAsyncDebounceMs?: number\n}\n\nexport interface FieldOptions<\n TParentData,\n TName extends DeepKeys<TParentData>,\n TFieldValidator extends\n | Validator<DeepValue<TParentData, TName>, unknown>\n | undefined = undefined,\n TFormValidator extends\n | Validator<TParentData, unknown>\n | undefined = undefined,\n TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,\n> {\n name: TName\n index?: TData extends any[] ? number : never\n defaultValue?: TData\n asyncDebounceMs?: number\n asyncAlways?: boolean\n preserveValue?: boolean\n validatorAdapter?: TFieldValidator\n validators?: FieldValidators<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >\n defaultMeta?: Partial<FieldMeta>\n}\n\nexport interface FieldApiOptions<\n TParentData,\n TName extends DeepKeys<TParentData>,\n TFieldValidator extends\n | Validator<DeepValue<TParentData, TName>, unknown>\n | undefined = undefined,\n TFormValidator extends\n | Validator<TParentData, unknown>\n | undefined = undefined,\n TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,\n> extends FieldOptions<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n > {\n form: FormApi<TParentData, TFormValidator>\n}\n\nexport type FieldMeta = {\n isTouched: boolean\n touchedErrors: ValidationError[]\n errors: ValidationError[]\n errorMap: ValidationErrorMap\n isValidating: boolean\n}\n\nlet uid = 0\n\nexport type FieldState<TData> = {\n value: TData\n meta: FieldMeta\n}\n\nexport type ResolveName<TParentData> = unknown extends TParentData\n ? string\n : DeepKeys<TParentData>\n\nexport class FieldApi<\n TParentData,\n TName extends DeepKeys<TParentData>,\n TFieldValidator extends\n | Validator<DeepValue<TParentData, TName>, unknown>\n | undefined = undefined,\n TFormValidator extends\n | Validator<TParentData, unknown>\n | undefined = undefined,\n TData extends DeepValue<TParentData, TName> = DeepValue<TParentData, TName>,\n> {\n uid: number\n form: FieldApiOptions<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >['form']\n name!: DeepKeys<TParentData>\n options: FieldApiOptions<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n > = {} as any\n store!: Store<FieldState<TData>>\n state!: FieldState<TData>\n prevState!: FieldState<TData>\n\n constructor(\n opts: FieldApiOptions<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >,\n ) {\n this.form = opts.form as never\n this.uid = uid++\n // Support field prefixing from FieldScope\n // let fieldPrefix = ''\n // if (this.form.fieldName) {\n // fieldPrefix = `${this.form.fieldName}.`\n // }\n\n this.name = opts.name as never\n\n if (opts.defaultValue !== undefined) {\n this.form.setFieldValue(this.name, opts.defaultValue as never)\n }\n\n this.store = new Store<FieldState<TData>>(\n {\n value: this.getValue(),\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n meta: this._getMeta() ?? {\n isValidating: false,\n isTouched: false,\n touchedErrors: [],\n errors: [],\n errorMap: {},\n ...opts.defaultMeta,\n },\n },\n {\n onUpdate: () => {\n const state = this.store.state\n\n state.meta.errors = Object.values(state.meta.errorMap).filter(\n (val: unknown) => val !== undefined,\n )\n\n state.meta.touchedErrors = state.meta.isTouched\n ? state.meta.errors\n : []\n\n this.prevState = state\n this.state = state\n },\n },\n )\n\n this.state = this.store.state\n this.prevState = this.state\n this.options = opts as never\n }\n\n runValidator<\n TValue extends { value: TData; fieldApi: FieldApi<any, any, any, any> },\n TType extends 'validate' | 'validateAsync',\n >(props: {\n validate: TType extends 'validate'\n ? FieldValidateOrFn<any, any, any, any>\n : FieldAsyncValidateOrFn<any, any, any, any>\n value: TValue\n type: TType\n }): ReturnType<ReturnType<Validator<any>>[TType]> {\n const adapters = [\n this.form.options.validatorAdapter,\n this.options.validatorAdapter,\n ] as const\n for (const adapter of adapters) {\n if (adapter && typeof props.validate !== 'function') {\n return adapter()[props.type](props.value, props.validate) as never\n }\n }\n\n return (props.validate as FieldValidateFn<any, any>)(props.value) as never\n }\n\n mount = () => {\n const info = this.getInfo()\n info.instances[this.uid] = this as never\n const unsubscribe = this.form.store.subscribe(() => {\n this.store.batch(() => {\n const nextValue = this.getValue()\n const nextMeta = this.getMeta()\n\n if (nextValue !== this.state.value) {\n this.store.setState((prev) => ({ ...prev, value: nextValue }))\n }\n\n if (nextMeta !== this.state.meta) {\n this.store.setState((prev) => ({ ...prev, meta: nextMeta }))\n }\n })\n })\n\n this.update(this.options as never)\n const { onMount } = this.options.validators || {}\n\n if (onMount) {\n const error = this.runValidator({\n validate: onMount,\n value: {\n value: this.state.value,\n fieldApi: this,\n },\n type: 'validate',\n })\n if (error) {\n this.setMeta((prev) => ({\n ...prev,\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n errorMap: { ...prev?.errorMap, onMount: error },\n }))\n }\n }\n\n return () => {\n const preserveValue = this.options.preserveValue\n unsubscribe()\n if (!preserveValue) {\n delete info.instances[this.uid]\n this.form.deleteField(this.name)\n }\n\n if (!Object.keys(info.instances).length && !preserveValue) {\n delete this.form.fieldInfo[this.name]\n }\n }\n }\n\n update = (\n opts: FieldApiOptions<\n TParentData,\n TName,\n TFieldValidator,\n TFormValidator,\n TData\n >,\n ) => {\n // Default Value\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (this.state.value === undefined) {\n const formDefault =\n opts.form.options.defaultValues?.[opts.name as keyof TParentData]\n\n if (opts.defaultValue !== undefined) {\n this.setValue(opts.defaultValue as never)\n } else if (formDefault !== undefined) {\n this.setValue(formDefault as never)\n }\n }\n\n // Default Meta\n if (this._getMeta() === undefined) {\n this.setMeta(this.state.meta)\n }\n\n this.options = opts as never\n }\n\n getValue = (): TData => {\n return this.form.getFieldValue(this.name) as any\n }\n\n setValue = (\n updater: Updater<TData>,\n options?: { touch?: boolean; notify?: boolean },\n ) => {\n this.form.setFieldValue(this.name, updater as never, options)\n this.validate('change', this.state.value)\n }\n\n _getMeta = () => this.form.getFieldMeta(this.name)\n getMeta = () =>\n this._getMeta() ??\n ({\n isValidating: false,\n isTouched: false,\n touchedErrors: [],\n errors: [],\n errorMap: {},\n ...this.options.defaultMeta,\n } as FieldMeta)\n\n setMeta = (updater: Updater<FieldMeta>) =>\n this.form.setFieldMeta(this.name, updater)\n\n getInfo = () => this.form.getFieldInfo(this.name)\n\n pushValue = (value: TData extends any[] ? TData[number] : never) =>\n this.form.pushFieldValue(this.name, value as any)\n\n insertValue = (\n index: number,\n value: TData extends any[] ? TData[number] : never,\n ) => this.form.insertFieldValue(this.name, index, value as any)\n\n removeValue = (index: number) => this.form.removeFieldValue(this.name, index)\n\n swapValues = (aIndex: number, bIndex: number) =>\n this.form.swapFieldValues(this.name, aIndex, bIndex)\n\n getSubField = <\n TSubName extends DeepKeys<TData>,\n TSubData extends DeepValue<TData, TSubName> = DeepValue<TData, TSubName>,\n >(\n name: TSubName,\n ): FieldApi<\n TData,\n TSubName,\n Validator<TSubData, unknown> | undefined,\n Validator<TData, unknown> | undefined,\n TSubData\n > =>\n new FieldApi({\n name: `${this.name}.${name}` as never,\n form: this.form,\n }) as any\n\n validateSync = (value = this.state.value, cause: ValidationCause) => {\n const validates = getSyncValidatorArray(cause, this.options)\n\n // Needs type cast as eslint errantly believes this is always falsy\n let hasErrored = false as boolean\n\n this.form.store.batch(() => {\n for (const validateObj of validates) {\n if (!validateObj.validate) continue\n const error = normalizeError(\n this.runValidator({\n validate: validateObj.validate,\n value: { value, fieldApi: this },\n type: 'validate',\n }),\n )\n const errorMapKey = getErrorMapKey(validateObj.cause)\n if (this.state.meta.errorMap[errorMapKey] !== error) {\n this.setMeta((prev) => ({\n ...prev,\n errorMap: {\n ...prev.errorMap,\n [getErrorMapKey(validateObj.cause)]: error,\n },\n }))\n }\n if (error) {\n hasErrored = true\n }\n }\n })\n\n /**\n * when we have an error for onSubmit in the state, we want\n * to clear the error as soon as the user enters a valid value in the field\n */\n const submitErrKey = getErrorMapKey('submit')\n if (\n this.state.meta.errorMap[submitErrKey] &&\n cause !== 'submit' &&\n !hasErrored\n ) {\n this.setMeta((prev) => ({\n ...prev,\n errorMap: {\n ...prev.errorMap,\n [submitErrKey]: undefined,\n },\n }))\n }\n\n return { hasErrored }\n }\n\n validateAsync = async (value = this.state.value, cause: ValidationCause) => {\n const validates = getAsyncValidatorArray(cause, this.options)\n\n if (!this.state.meta.isValidating) {\n this.setMeta((prev) => ({ ...prev, isValidating: true }))\n }\n\n /**\n * We have to use a for loop and generate our promises this way, otherwise it won't be sync\n * when there are no validators needed to be run\n */\n const promises: Promise<ValidationError | undefined>[] = []\n\n for (const validateObj of validates) {\n if (!validateObj.validate) continue\n const key = getErrorMapKey(validateObj.cause)\n const fieldValidatorMeta = this.getInfo().validationMetaMap[key]\n\n fieldValidatorMeta?.lastAbortController.abort()\n // Sorry Safari 12\n // eslint-disable-next-line compat/compat\n const controller = new AbortController()\n\n this.getInfo().validationMetaMap[key] = {\n lastAbortController: controller,\n }\n\n promises.push(\n new Promise<ValidationError | undefined>(async (resolve) => {\n let rawError!: ValidationError | undefined\n try {\n rawError = await new Promise((rawResolve, rawReject) => {\n setTimeout(() => {\n if (controller.signal.aborted) return rawResolve(undefined)\n this.runValidator({\n validate: validateObj.validate,\n value: { value, fieldApi: this, signal: controller.signal },\n type: 'validateAsync',\n })\n .then(rawResolve)\n .catch(rawReject)\n }, validateObj.debounceMs)\n })\n } catch (e: unknown) {\n rawError = e as ValidationError\n }\n const error = normalizeError(rawError)\n this.setMeta((prev) => {\n return {\n ...prev,\n errorMap: {\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n ...prev?.errorMap,\n [getErrorMapKey(cause)]: error,\n },\n }\n })\n\n resolve(error)\n }),\n )\n }\n\n let results: ValidationError[] = []\n if (promises.length) {\n results = await Promise.all(promises)\n }\n\n this.setMeta((prev) => ({ ...prev, isValidating: false }))\n\n return results.filter(Boolean)\n }\n\n validate = (\n cause: ValidationCause,\n value?: TData,\n ): ValidationError[] | Promise<ValidationError[]> => {\n // If the field is pristine and validatePristine is false, do not validate\n if (!this.state.meta.isTouched) return []\n\n try {\n this.form.validate(cause)\n } catch (_) {}\n\n // Attempt to sync validate first\n const { hasErrored } = this.validateSync(value, cause)\n\n if (hasErrored && !this.options.asyncAlways) {\n return this.state.meta.errors\n }\n // No error? Attempt async validation\n return this.validateAsync(value, cause)\n }\n\n handleChange = (updater: Updater<TData>) => {\n this.setValue(updater, { touch: true })\n }\n\n handleBlur = () => {\n const prevTouched = this.state.meta.isTouched\n if (!prevTouched) {\n this.setMeta((prev) => ({ ...prev, isTouched: true }))\n this.validate('change')\n }\n this.validate('blur')\n }\n}\n\nfunction normalizeError(rawError?: ValidationError) {\n if (rawError) {\n if (typeof rawError !== 'string') {\n return 'Invalid Form Values'\n }\n\n return rawError\n }\n\n return undefined\n}\n\nfunction getErrorMapKey(cause: ValidationCause) {\n switch (cause) {\n case 'submit':\n return 'onSubmit'\n case 'change':\n return 'onChange'\n case 'blur':\n return 'onBlur'\n case 'mount':\n return 'onMount'\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAsB;AAStB,mBAA8D;AAgO9D,IAAI,MAAM;AAWH,IAAM,WAAN,MAAM,UAUX;AAAA,EAqBA,YACE,MAOA;AAnBF,mBAMI,CAAC;AAuFL,iBAAQ,MAAM;AACZ,YAAM,OAAO,KAAK,QAAQ;AAC1B,WAAK,UAAU,KAAK,GAAG,IAAI;AAC3B,YAAM,cAAc,KAAK,KAAK,MAAM,UAAU,MAAM;AAClD,aAAK,MAAM,MAAM,MAAM;AACrB,gBAAM,YAAY,KAAK,SAAS;AAChC,gBAAM,WAAW,KAAK,QAAQ;AAE9B,cAAI,cAAc,KAAK,MAAM,OAAO;AAClC,iBAAK,MAAM,SAAS,CAAC,UAAU,EAAE,GAAG,MAAM,OAAO,UAAU,EAAE;AAAA,UAC/D;AAEA,cAAI,aAAa,KAAK,MAAM,MAAM;AAChC,iBAAK,MAAM,SAAS,CAAC,UAAU,EAAE,GAAG,MAAM,MAAM,SAAS,EAAE;AAAA,UAC7D;AAAA,QACF,CAAC;AAAA,MACH,CAAC;AAED,WAAK,OA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,QAAQ;AAAA,IACf;AACA,eAAW,WAAW,UAAU;AAC9B,UAAI,WAAW,OAAO,MAAM,aAAa,YAAY;AACnD,eAAO,QAAQ,EAAE,MAAM,IAAI,EAAE,MAAM,OAAO,MAAM,QAAQ;AAAA,MAC1D;AAAA,IACF;AAEA,WAAQ,MAAM,SAAuC,MAAM,KAAK;AAAA,EAClE;AAgTF;AAEA,SAAS,eAAe,UAA4B;AAClD,MAAI,UAAU;AACZ,QAAI,OAAO,aAAa,UAAU;AAChC,aAAO;AAAA,IACT;AAEA,WAAO;AAAA,EACT;AAEA,SAAO;AACT;AAEA,SAAS,eAAe,OAAwB;AAC9C,UAAQ,OAAO;AAAA,IACb,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,EACX;AACF;","names":[]}
@@ -1,3 +0,0 @@
1
- export { FieldApi, FieldApiOptions, FieldAsyncValidateOrFn, FieldMeta, FieldOptions, FieldState, FieldValidateAsyncFn, FieldValidateFn, FieldValidateOrFn, FieldValidators, ResolveName } from './index.cjs';
2
- import '@tanstack/store';
3
- import './types.cjs';
@@ -1,3 +0,0 @@
1
- export { FieldApi, FieldApiOptions, FieldAsyncValidateOrFn, FieldMeta, FieldOptions, FieldState, FieldValidateAsyncFn, FieldValidateFn, FieldValidateOrFn, FieldValidators, ResolveName } from './index.js';
2
- import '@tanstack/store';
3
- import './types.js';
@@ -1,287 +0,0 @@
1
- // src/FieldApi.ts
2
- import { Store } from "@tanstack/store";
3
- import { getAsyncValidatorArray, getSyncValidatorArray } from "./utils.js";
4
- var uid = 0;
5
- var FieldApi = class _FieldApi {
6
- constructor(opts) {
7
- this.options = {};
8
- this.mount = () => {
9
- const info = this.getInfo();
10
- info.instances[this.uid] = this;
11
- const unsubscribe = this.form.store.subscribe(() => {
12
- this.store.batch(() => {
13
- const nextValue = this.getValue();
14
- const nextMeta = this.getMeta();
15
- if (nextValue !== this.state.value) {
16
- this.store.setState((prev) => ({ ...prev, value: nextValue }));
17
- }
18
- if (nextMeta !== this.state.meta) {
19
- this.store.setState((prev) => ({ ...prev, meta: nextMeta }));
20
- }
21
- });
22
- });
23
- this.update(this.options);
24
- const { onMount } = this.options.validators || {};
25
- if (onMount) {
26
- const error = this.runValidator({
27
- validate: onMount,
28
- value: {
29
- value: this.state.value,
30
- fieldApi: this
31
- },
32
- type: "validate"
33
- });
34
- if (error) {
35
- this.setMeta((prev) => ({
36
- ...prev,
37
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
38
- errorMap: { ...prev?.errorMap, onMount: error }
39
- }));
40
- }
41
- }
42
- return () => {
43
- const preserveValue = this.options.preserveValue;
44
- unsubscribe();
45
- if (!preserveValue) {
46
- delete info.instances[this.uid];
47
- this.form.deleteField(this.name);
48
- }
49
- if (!Object.keys(info.instances).length && !preserveValue) {
50
- delete this.form.fieldInfo[this.name];
51
- }
52
- };
53
- };
54
- this.update = (opts) => {
55
- if (this.state.value === void 0) {
56
- const formDefault = opts.form.options.defaultValues?.[opts.name];
57
- if (opts.defaultValue !== void 0) {
58
- this.setValue(opts.defaultValue);
59
- } else if (formDefault !== void 0) {
60
- this.setValue(formDefault);
61
- }
62
- }
63
- if (this._getMeta() === void 0) {
64
- this.setMeta(this.state.meta);
65
- }
66
- this.options = opts;
67
- };
68
- this.getValue = () => {
69
- return this.form.getFieldValue(this.name);
70
- };
71
- this.setValue = (updater, options) => {
72
- this.form.setFieldValue(this.name, updater, options);
73
- this.validate("change", this.state.value);
74
- };
75
- this._getMeta = () => this.form.getFieldMeta(this.name);
76
- this.getMeta = () => this._getMeta() ?? {
77
- isValidating: false,
78
- isTouched: false,
79
- touchedErrors: [],
80
- errors: [],
81
- errorMap: {},
82
- ...this.options.defaultMeta
83
- };
84
- this.setMeta = (updater) => this.form.setFieldMeta(this.name, updater);
85
- this.getInfo = () => this.form.getFieldInfo(this.name);
86
- this.pushValue = (value) => this.form.pushFieldValue(this.name, value);
87
- this.insertValue = (index, value) => this.form.insertFieldValue(this.name, index, value);
88
- this.removeValue = (index) => this.form.removeFieldValue(this.name, index);
89
- this.swapValues = (aIndex, bIndex) => this.form.swapFieldValues(this.name, aIndex, bIndex);
90
- this.getSubField = (name) => new _FieldApi({
91
- name: `${this.name}.${name}`,
92
- form: this.form
93
- });
94
- this.validateSync = (value = this.state.value, cause) => {
95
- const validates = getSyncValidatorArray(cause, this.options);
96
- let hasErrored = false;
97
- this.form.store.batch(() => {
98
- for (const validateObj of validates) {
99
- if (!validateObj.validate)
100
- continue;
101
- const error = normalizeError(
102
- this.runValidator({
103
- validate: validateObj.validate,
104
- value: { value, fieldApi: this },
105
- type: "validate"
106
- })
107
- );
108
- const errorMapKey = getErrorMapKey(validateObj.cause);
109
- if (this.state.meta.errorMap[errorMapKey] !== error) {
110
- this.setMeta((prev) => ({
111
- ...prev,
112
- errorMap: {
113
- ...prev.errorMap,
114
- [getErrorMapKey(validateObj.cause)]: error
115
- }
116
- }));
117
- }
118
- if (error) {
119
- hasErrored = true;
120
- }
121
- }
122
- });
123
- const submitErrKey = getErrorMapKey("submit");
124
- if (this.state.meta.errorMap[submitErrKey] && cause !== "submit" && !hasErrored) {
125
- this.setMeta((prev) => ({
126
- ...prev,
127
- errorMap: {
128
- ...prev.errorMap,
129
- [submitErrKey]: void 0
130
- }
131
- }));
132
- }
133
- return { hasErrored };
134
- };
135
- this.validateAsync = async (value = this.state.value, cause) => {
136
- const validates = getAsyncValidatorArray(cause, this.options);
137
- if (!this.state.meta.isValidating) {
138
- this.setMeta((prev) => ({ ...prev, isValidating: true }));
139
- }
140
- const promises = [];
141
- for (const validateObj of validates) {
142
- if (!validateObj.validate)
143
- continue;
144
- const key = getErrorMapKey(validateObj.cause);
145
- const fieldValidatorMeta = this.getInfo().validationMetaMap[key];
146
- fieldValidatorMeta?.lastAbortController.abort();
147
- const controller = new AbortController();
148
- this.getInfo().validationMetaMap[key] = {
149
- lastAbortController: controller
150
- };
151
- promises.push(
152
- new Promise(async (resolve) => {
153
- let rawError;
154
- try {
155
- rawError = await new Promise((rawResolve, rawReject) => {
156
- setTimeout(() => {
157
- if (controller.signal.aborted)
158
- return rawResolve(void 0);
159
- this.runValidator({
160
- validate: validateObj.validate,
161
- value: { value, fieldApi: this, signal: controller.signal },
162
- type: "validateAsync"
163
- }).then(rawResolve).catch(rawReject);
164
- }, validateObj.debounceMs);
165
- });
166
- } catch (e) {
167
- rawError = e;
168
- }
169
- const error = normalizeError(rawError);
170
- this.setMeta((prev) => {
171
- return {
172
- ...prev,
173
- errorMap: {
174
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
175
- ...prev?.errorMap,
176
- [getErrorMapKey(cause)]: error
177
- }
178
- };
179
- });
180
- resolve(error);
181
- })
182
- );
183
- }
184
- let results = [];
185
- if (promises.length) {
186
- results = await Promise.all(promises);
187
- }
188
- this.setMeta((prev) => ({ ...prev, isValidating: false }));
189
- return results.filter(Boolean);
190
- };
191
- this.validate = (cause, value) => {
192
- if (!this.state.meta.isTouched)
193
- return [];
194
- try {
195
- this.form.validate(cause);
196
- } catch (_) {
197
- }
198
- const { hasErrored } = this.validateSync(value, cause);
199
- if (hasErrored && !this.options.asyncAlways) {
200
- return this.state.meta.errors;
201
- }
202
- return this.validateAsync(value, cause);
203
- };
204
- this.handleChange = (updater) => {
205
- this.setValue(updater, { touch: true });
206
- };
207
- this.handleBlur = () => {
208
- const prevTouched = this.state.meta.isTouched;
209
- if (!prevTouched) {
210
- this.setMeta((prev) => ({ ...prev, isTouched: true }));
211
- this.validate("change");
212
- }
213
- this.validate("blur");
214
- };
215
- this.form = opts.form;
216
- this.uid = uid++;
217
- this.name = opts.name;
218
- if (opts.defaultValue !== void 0) {
219
- this.form.setFieldValue(this.name, opts.defaultValue);
220
- }
221
- this.store = new Store(
222
- {
223
- value: this.getValue(),
224
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
225
- meta: this._getMeta() ?? {
226
- isValidating: false,
227
- isTouched: false,
228
- touchedErrors: [],
229
- errors: [],
230
- errorMap: {},
231
- ...opts.defaultMeta
232
- }
233
- },
234
- {
235
- onUpdate: () => {
236
- const state = this.store.state;
237
- state.meta.errors = Object.values(state.meta.errorMap).filter(
238
- (val) => val !== void 0
239
- );
240
- state.meta.touchedErrors = state.meta.isTouched ? state.meta.errors : [];
241
- this.prevState = state;
242
- this.state = state;
243
- }
244
- }
245
- );
246
- this.state = this.store.state;
247
- this.prevState = this.state;
248
- this.options = opts;
249
- }
250
- runValidator(props) {
251
- const adapters = [
252
- this.form.options.validatorAdapter,
253
- this.options.validatorAdapter
254
- ];
255
- for (const adapter of adapters) {
256
- if (adapter && typeof props.validate !== "function") {
257
- return adapter()[props.type](props.value, props.validate);
258
- }
259
- }
260
- return props.validate(props.value);
261
- }
262
- };
263
- function normalizeError(rawError) {
264
- if (rawError) {
265
- if (typeof rawError !== "string") {
266
- return "Invalid Form Values";
267
- }
268
- return rawError;
269
- }
270
- return void 0;
271
- }
272
- function getErrorMapKey(cause) {
273
- switch (cause) {
274
- case "submit":
275
- return "onSubmit";
276
- case "change":
277
- return "onChange";
278
- case "blur":
279
- return "onBlur";
280
- case "mount":
281
- return "onMount";
282
- }
283
- }
284
- export {
285
- FieldApi
286
- };
287
- //# sourceMappingURL=FieldApi.js.map