@reactables/forms 1.3.0-beta.3 → 2.0.0-beta.1

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 (83) hide show
  1. package/dist/Helpers/addAsyncValidationEffects.d.ts +9 -6
  2. package/dist/Helpers/buildFormState.d.ts +6 -6
  3. package/dist/Helpers/buildHub2Source.d.ts +4 -4
  4. package/dist/Helpers/controlRefCheck.d.ts +5 -5
  5. package/dist/Helpers/controlRefCheck.test.d.ts +1 -1
  6. package/dist/Helpers/generateKey.d.ts +1 -1
  7. package/dist/Helpers/getAncestorControls.d.ts +3 -3
  8. package/dist/Helpers/getAncestorControls.test.d.ts +1 -1
  9. package/dist/Helpers/getArrayItems.d.ts +3 -3
  10. package/dist/Helpers/getArrayItems.test.d.ts +1 -1
  11. package/dist/Helpers/getControl.d.ts +3 -3
  12. package/dist/Helpers/getControlBranch.d.ts +3 -3
  13. package/dist/Helpers/getControlBranch.test.d.ts +1 -1
  14. package/dist/Helpers/getDescendantControls.d.ts +3 -3
  15. package/dist/Helpers/getDescendantControls.test.d.ts +1 -1
  16. package/dist/Helpers/getFormKey.d.ts +2 -2
  17. package/dist/Helpers/getValueFromControlConfig.d.ts +2 -2
  18. package/dist/Helpers/getValueFromControlConfig.test.d.ts +1 -1
  19. package/dist/Helpers/index.d.ts +4 -4
  20. package/dist/Helpers/isChildRef.d.ts +2 -2
  21. package/dist/Helpers/reverseObjectKeys.d.ts +2 -2
  22. package/dist/Models/Configs.d.ts +22 -22
  23. package/dist/Models/ControlRef.d.ts +1 -1
  24. package/dist/Models/Controls.d.ts +48 -48
  25. package/dist/Models/FormErrors.d.ts +3 -3
  26. package/dist/Models/Payloads.d.ts +24 -24
  27. package/dist/Models/Validators.d.ts +5 -5
  28. package/dist/Models/index.d.ts +6 -6
  29. package/dist/Reducers/Hub1/addControl.d.ts +5 -5
  30. package/dist/Reducers/Hub1/getErrors.d.ts +4 -4
  31. package/dist/Reducers/Hub1/index.d.ts +6 -7
  32. package/dist/Reducers/Hub1/markControlAsPristine.d.ts +4 -4
  33. package/dist/Reducers/Hub1/markControlAsTouched.d.ts +4 -4
  34. package/dist/Reducers/Hub1/markControlAsUntouched.d.ts +4 -4
  35. package/dist/Reducers/Hub1/pushControl.d.ts +5 -5
  36. package/dist/Reducers/Hub1/removeControl.d.ts +5 -5
  37. package/dist/Reducers/Hub1/resetControl.d.ts +5 -5
  38. package/dist/Reducers/Hub1/updateAncestorPristineValues.d.ts +5 -5
  39. package/dist/Reducers/Hub1/updateAncestorValues.d.ts +6 -6
  40. package/dist/Reducers/Hub1/updateAncestorValuesAddControl.d.ts +6 -6
  41. package/dist/Reducers/Hub1/updateAncestorValuesRemoveControl.d.ts +6 -6
  42. package/dist/Reducers/Hub1/updateValues.d.ts +5 -5
  43. package/dist/Reducers/Hub2/asyncValidation.d.ts +4 -4
  44. package/dist/Reducers/Hub2/asyncValidationResponse.d.ts +4 -0
  45. package/dist/Reducers/Hub2/formChange.d.ts +3 -3
  46. package/dist/Reducers/Hub2/index.d.ts +3 -3
  47. package/dist/Reducers/Hub2/mergeBranchErrors.d.ts +3 -3
  48. package/dist/Reducers/Hub2/mergeControls.d.ts +5 -5
  49. package/dist/Reducers/Hub2/mergeErrors.d.ts +2 -2
  50. package/dist/Reducers/Hub2/mergeRemoveControl.d.ts +6 -6
  51. package/dist/Reducers/index.d.ts +2 -2
  52. package/dist/RxForm/RxForm.d.ts +103 -99
  53. package/dist/RxForm/Tests/addControl.test.d.ts +1 -1
  54. package/dist/RxForm/Tests/combinedTest.test.d.ts +1 -1
  55. package/dist/RxForm/Tests/customReducers.test.d.ts +1 -1
  56. package/dist/RxForm/Tests/initialization.test.d.ts +1 -1
  57. package/dist/RxForm/Tests/load.test.d.ts +1 -1
  58. package/dist/RxForm/Tests/markControlAsPristine.test.d.ts +1 -1
  59. package/dist/RxForm/Tests/markControlTouchStatus.test.d.ts +1 -1
  60. package/dist/RxForm/Tests/pushControl.test.d.ts +1 -1
  61. package/dist/RxForm/Tests/removeControl.test.d.ts +1 -1
  62. package/dist/RxForm/Tests/resetControl.test.d.ts +1 -1
  63. package/dist/RxForm/Tests/updateValues.test.d.ts +1 -1
  64. package/dist/RxForm/index.d.ts +1 -1
  65. package/dist/Testing/AsyncValidators.d.ts +9 -8
  66. package/dist/Testing/Models/Contact.d.ts +11 -11
  67. package/dist/Testing/Models/DoctorInfo.d.ts +6 -6
  68. package/dist/Testing/Models/EmergencyContact.d.ts +6 -6
  69. package/dist/Testing/Models/initialState.d.ts +667 -667
  70. package/dist/Testing/Validators.d.ts +10 -10
  71. package/dist/Testing/asyncConfig.d.ts +3 -3
  72. package/dist/Testing/config.d.ts +3 -3
  73. package/dist/Validators/Validators.d.ts +4 -4
  74. package/dist/Validators/index.d.ts +1 -1
  75. package/dist/index.cjs +1213 -0
  76. package/dist/index.cjs.map +1 -0
  77. package/dist/index.d.ts +4 -4
  78. package/dist/index.js +1064 -1075
  79. package/dist/index.js.map +1 -0
  80. package/package.json +10 -3
  81. package/dist/Reducers/Hub2/asyncValidationResponseSuccess.d.ts +0 -4
  82. package/dist/Reducers/Hub2/hub2Reducer.d.ts +0 -3
  83. package/dist/Testing/Effects.d.ts +0 -10
package/dist/index.cjs ADDED
@@ -0,0 +1,1213 @@
1
+ 'use strict';
2
+
3
+ var core = require('@reactables/core');
4
+ var operators = require('rxjs/operators');
5
+ var rxjs = require('rxjs');
6
+ var isEqual = require('lodash.isequal');
7
+
8
+ var DEFAULT_HUB2_FIELDS = {
9
+ asyncValidatorErrors: {},
10
+ asyncValidateInProgress: {},
11
+ pending: false,
12
+ valid: null,
13
+ childrenValid: null,
14
+ errors: null
15
+ };
16
+
17
+ var Controls = /*#__PURE__*/Object.freeze({
18
+ __proto__: null,
19
+ DEFAULT_HUB2_FIELDS: DEFAULT_HUB2_FIELDS
20
+ });
21
+
22
+ var required = function (value) {
23
+ if (typeof value === 'string' || typeof value === 'object') {
24
+ return { required: !Boolean(value) };
25
+ }
26
+ if (typeof value === 'number') {
27
+ return { required: !(value !== undefined && value !== null) };
28
+ }
29
+ if (typeof value === 'boolean') {
30
+ return { required: !value };
31
+ }
32
+ return { required: false };
33
+ };
34
+ var arrayNotEmpty = function (value) { return ({
35
+ arrayNotEmpty: !Boolean(value.length)
36
+ }); };
37
+ var email = function (value) {
38
+ return value && !/^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$/g.test(value) ? { email: true } : { email: false };
39
+ };
40
+
41
+ var Validators = /*#__PURE__*/Object.freeze({
42
+ __proto__: null,
43
+ arrayNotEmpty: arrayNotEmpty,
44
+ email: email,
45
+ required: required
46
+ });
47
+
48
+ var index = /*#__PURE__*/Object.freeze({
49
+ __proto__: null,
50
+ arrayNotEmpty: arrayNotEmpty,
51
+ email: email,
52
+ required: required
53
+ });
54
+
55
+ /******************************************************************************
56
+ Copyright (c) Microsoft Corporation.
57
+
58
+ Permission to use, copy, modify, and/or distribute this software for any
59
+ purpose with or without fee is hereby granted.
60
+
61
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
62
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
63
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
64
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
65
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
66
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
67
+ PERFORMANCE OF THIS SOFTWARE.
68
+ ***************************************************************************** */
69
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
70
+
71
+
72
+ var __assign = function() {
73
+ __assign = Object.assign || function __assign(t) {
74
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
75
+ s = arguments[i];
76
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
77
+ }
78
+ return t;
79
+ };
80
+ return __assign.apply(this, arguments);
81
+ };
82
+
83
+ function __rest(s, e) {
84
+ var t = {};
85
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
86
+ t[p] = s[p];
87
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
88
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
89
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
90
+ t[p[i]] = s[p[i]];
91
+ }
92
+ return t;
93
+ }
94
+
95
+ function __spreadArray(to, from, pack) {
96
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
97
+ if (ar || !(i in from)) {
98
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
99
+ ar[i] = from[i];
100
+ }
101
+ }
102
+ return to.concat(ar || Array.prototype.slice.call(from));
103
+ }
104
+
105
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
106
+ var e = new Error(message);
107
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
108
+ };
109
+
110
+ var getValueFromControlConfig = function (controlConfig) {
111
+ var controls = controlConfig.controls;
112
+ if (controls && !(controls instanceof Array)) {
113
+ var result = {};
114
+ for (var key in controlConfig.controls) {
115
+ var control = controlConfig.controls[key];
116
+ result[key] = getValueFromControlConfig(control);
117
+ }
118
+ return result;
119
+ }
120
+ else if (controls && controls instanceof Array) {
121
+ var configs = controlConfig.controls;
122
+ var result = configs
123
+ ? configs.map(function (controlConfig) { return getValueFromControlConfig(controlConfig); })
124
+ : [];
125
+ return result;
126
+ }
127
+ else {
128
+ return controlConfig.initialValue;
129
+ }
130
+ };
131
+
132
+ var getFormKey = function (controlRef) {
133
+ return controlRef.length ? controlRef.join('.') : 'root';
134
+ };
135
+
136
+ var generateKey = function (length) {
137
+ var result = '';
138
+ var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
139
+ var charactersLength = characters.length;
140
+ var counter = 0;
141
+ while (counter < length) {
142
+ result += characters.charAt(Math.floor(Math.random() * charactersLength));
143
+ counter += 1;
144
+ }
145
+ return result;
146
+ };
147
+
148
+ var getErrors = function (control, value, _a) {
149
+ var _b;
150
+ var validators = _a.validators;
151
+ return ((_b = control.config.validators) === null || _b === void 0 ? void 0 : _b.reduce(function (acc, validator) {
152
+ if (!validators[validator]) {
153
+ throw "You have not provided a validator for \"".concat(validator, "\"");
154
+ }
155
+ return __assign(__assign({}, acc), validators[validator](value));
156
+ }, {})) || {};
157
+ };
158
+
159
+ var buildState = function (config, form, controlRef, providers) {
160
+ var _a;
161
+ if (form === void 0) { form = { root: null }; }
162
+ if (controlRef === void 0) { controlRef = []; }
163
+ var value = getValueFromControlConfig(config);
164
+ var control = {
165
+ pristineValue: value,
166
+ dirty: false,
167
+ touched: false,
168
+ value: value,
169
+ controlRef: controlRef,
170
+ validatorErrors: {},
171
+ config: config,
172
+ key: generateKey(5)
173
+ };
174
+ var newForm = __assign(__assign({}, form), (_a = {}, _a[getFormKey(controlRef)] = __assign(__assign({}, control), { validatorErrors: getErrors(control, value, providers) }), _a));
175
+ var controls = config.controls;
176
+ // Adding controls for Form Group
177
+ if (controls && !(controls instanceof Array)) {
178
+ newForm = Object.entries(config.controls).reduce(function (acc, _a) {
179
+ var key = _a[0], controlConfig = _a[1];
180
+ return buildState(controlConfig, acc, controlRef.concat(key), providers);
181
+ }, newForm);
182
+ }
183
+ else if (controls && controls instanceof Array) {
184
+ // Adding controls for Form Array
185
+ newForm = config.controls.reduce(function (acc, controlConfig, index) {
186
+ return buildState(controlConfig, acc, controlRef.concat(index), providers);
187
+ }, newForm);
188
+ }
189
+ return newForm;
190
+ };
191
+ var buildFormState = function (config, form, controlRef, providers) {
192
+ if (form === void 0) { form = { root: null }; }
193
+ if (controlRef === void 0) { controlRef = []; }
194
+ return {
195
+ form: buildState(config, form, controlRef, providers)
196
+ };
197
+ };
198
+
199
+ var getScopedEffectsForControl = function (formControl, providers) {
200
+ var config = formControl.config, key = formControl.key, controlRef = formControl.controlRef;
201
+ var asyncValidators = config.asyncValidators;
202
+ var scopedEffects = [];
203
+ if (asyncValidators && asyncValidators.length) {
204
+ scopedEffects = asyncValidators.reduce(function (acc, asyncValidator, validatorIndex) {
205
+ var effect = function (actions$) {
206
+ if (!providers.asyncValidators[asyncValidator]) {
207
+ throw "You have not provided an asyncValidator for \"".concat(asyncValidator, "\"");
208
+ }
209
+ return actions$.pipe(operators.map(function (_a) {
210
+ var control = _a.payload;
211
+ return control;
212
+ }), providers.asyncValidators[asyncValidator], operators.switchMap(function (errors$) {
213
+ return rxjs.concat(rxjs.of({ type: 'asyncValidation', payload: controlRef }), errors$.pipe(operators.map(function (errors) { return ({
214
+ type: 'asyncValidationResponse',
215
+ payload: {
216
+ key: key,
217
+ errors: errors,
218
+ validatorIndex: validatorIndex
219
+ }
220
+ }); }), operators.catchError(function () {
221
+ return rxjs.of({
222
+ type: 'asyncValidationResponse',
223
+ payload: {
224
+ key: key,
225
+ errors: { asyncValidationApiError: true },
226
+ validatorIndex: validatorIndex
227
+ }
228
+ });
229
+ })));
230
+ }));
231
+ };
232
+ return acc.concat(effect);
233
+ }, []);
234
+ }
235
+ return scopedEffects;
236
+ };
237
+ var getAsyncValidationEffects = function (formControls) {
238
+ return formControls.reduce(function (acc, control) {
239
+ var _a;
240
+ if (!((_a = control.config.asyncValidators) === null || _a === void 0 ? void 0 : _a.length))
241
+ return acc;
242
+ var action = { type: 'asyncValidationEffect', payload: control };
243
+ return acc.concat(action);
244
+ }, []);
245
+ };
246
+
247
+ var buildHub2Source = function (hub1State$, initialBaseState) {
248
+ var hub1StateMapped$ = hub1State$.pipe(operators.map(function (payload) { return ({ type: 'formChange', payload: payload }); }));
249
+ var initialAction = { type: 'formChange', payload: initialBaseState };
250
+ var sourceForHub2$ = hub1StateMapped$.pipe(operators.startWith(initialAction), operators.pairwise(), operators.mergeMap(function (_a) {
251
+ var prevForm = _a[0].payload.form, currAction = _a[1];
252
+ var _b = currAction.payload, _changedControls = _b._changedControls, currentForm = _b.form;
253
+ var valueChanged = !isEqual(prevForm.root.value, currentForm.root.value);
254
+ var controlsToCheck = _changedControls && valueChanged ? Object.values(_changedControls) : [];
255
+ var asyncValidationEffectActions = getAsyncValidationEffects(controlsToCheck);
256
+ return rxjs.of.apply(void 0, __spreadArray([currAction], asyncValidationEffectActions, false));
257
+ }));
258
+ return sourceForHub2$;
259
+ };
260
+
261
+ var getControl = function (controlRef, form) {
262
+ return form[getFormKey(controlRef)];
263
+ };
264
+
265
+ var updateAncestorValues = function (form, _a, providers) {
266
+ var _b, _c;
267
+ var _d = _a.payload, controlRef = _d.controlRef, value = _d.value;
268
+ if (controlRef.length) {
269
+ var parentRef = controlRef.slice(0, -1);
270
+ var parentControl = getControl(parentRef, form);
271
+ var parentFormKey = getFormKey(parentControl.controlRef);
272
+ var childKey_1 = controlRef.slice(-1)[0];
273
+ var newValue = void 0;
274
+ // If parent is a Form Array
275
+ if (Array.isArray(parentControl.value)) {
276
+ newValue = parentControl.value.map(function (item, index) {
277
+ return index === childKey_1 ? value : item;
278
+ });
279
+ }
280
+ else {
281
+ // If parent is a Form Group
282
+ newValue = __assign(__assign({}, parentControl.value), (_b = {}, _b[childKey_1] = value, _b));
283
+ }
284
+ var newParentControl = __assign(__assign({}, parentControl), { validatorErrors: getErrors(parentControl, newValue, providers), value: newValue, dirty: !isEqual(newValue, parentControl.pristineValue) });
285
+ return updateAncestorValues(__assign(__assign({}, form), (_c = {}, _c[parentFormKey] = newParentControl, _c)), {
286
+ payload: { controlRef: parentRef, value: newValue }
287
+ }, providers);
288
+ }
289
+ return form;
290
+ };
291
+
292
+ var isChildRef = function (controlRef, parentRef) {
293
+ return (parentRef.every(function (key, index) { return controlRef[index] === key; }) &&
294
+ controlRef.length === parentRef.length + 1);
295
+ };
296
+
297
+ // Includes the original control of interest unless excludeSelf === true
298
+ var getDescendantControls = function (controlRef, form, excludeSelf) {
299
+ if (excludeSelf === void 0) { excludeSelf = false; }
300
+ if (!controlRef.length) {
301
+ return Object.values(form).filter(function (_a) {
302
+ var controlRef = _a.controlRef;
303
+ return excludeSelf ? controlRef.length !== 0 : true;
304
+ });
305
+ }
306
+ var control = getControl(controlRef, form);
307
+ var value = control.value, config = control.config;
308
+ var descendants;
309
+ if (Array.isArray(config.controls)) {
310
+ // If control is a Form Array
311
+ descendants = value.reduce(function (acc, item, index) {
312
+ return acc.concat(getDescendantControls(controlRef.concat(index), form));
313
+ }, []);
314
+ }
315
+ else if (config.controls) {
316
+ // If control is a Form Group
317
+ descendants = Object.keys(value).reduce(function (acc, key) {
318
+ return acc.concat(getDescendantControls(controlRef.concat(key), form));
319
+ }, []);
320
+ }
321
+ if (excludeSelf)
322
+ return descendants;
323
+ return [control].concat(descendants || []);
324
+ };
325
+
326
+ // Includes the original control of interest unless excludeSelf === true
327
+ var getAncestorControls = function (controlRef, form, excludeSelf) {
328
+ if (excludeSelf === void 0) { excludeSelf = false; }
329
+ var formControls = controlRef.reduce(function (acc, key) {
330
+ var currentRef = acc.currentRef.concat(key);
331
+ var formControls = acc.formControls.concat(getControl(currentRef, form));
332
+ return {
333
+ currentRef: currentRef,
334
+ formControls: formControls
335
+ };
336
+ }, {
337
+ currentRef: [],
338
+ formControls: []
339
+ }).formControls;
340
+ var root = form['root'];
341
+ var result = [root].concat(formControls);
342
+ return result.filter(function (control) {
343
+ return excludeSelf ? getFormKey(control.controlRef) !== getFormKey(controlRef) : true;
344
+ });
345
+ };
346
+
347
+ /**
348
+ * @description see if any keys in a ControlRef has a "." probably a mistake by developer
349
+ */
350
+ var controlRefCheck = function (ref) {
351
+ try {
352
+ var hasError = ref.some(function (key) {
353
+ if (typeof key === 'string') {
354
+ return key.includes('.');
355
+ }
356
+ return false;
357
+ });
358
+ if (hasError) {
359
+ var refString = "[".concat(ref.reduce(function (acc, key, index) {
360
+ if (index > 0) {
361
+ acc = acc.concat(', ');
362
+ }
363
+ if (typeof key === 'number') {
364
+ return acc.concat(key.toString());
365
+ }
366
+ return acc.concat("'".concat(key, "'"));
367
+ }, ''), "]");
368
+ var suggestion = "[".concat(ref.reduce(function (acc, key, index) {
369
+ if (index > 0) {
370
+ acc = acc.concat(', ');
371
+ }
372
+ if (typeof key === 'number') {
373
+ return acc.concat(key.toString());
374
+ }
375
+ var splitted = key
376
+ .split('.')
377
+ .map(function (key) { return "'".concat(key, "'"); })
378
+ .join(', ');
379
+ return acc.concat("".concat(splitted));
380
+ }, ''), "]");
381
+ console.warn("You provided ".concat(refString, ". Did you mean ").concat(suggestion, "?"));
382
+ }
383
+ }
384
+ catch (_a) { }
385
+ };
386
+
387
+ var checkKeys = function (obj1, obj2) {
388
+ if (Object.keys(obj1).slice().sort().join() !== Object.keys(obj2).slice().sort().join()) {
389
+ throw 'Can not update value because keys are not the same.';
390
+ }
391
+ };
392
+ var updateDescendantValues = function (form, _a, providers) {
393
+ var _b = _a.payload, controlRef = _b.controlRef, value = _b.value;
394
+ var descendants = getDescendantControls(controlRef, form, true).map(function (control) { return [getFormKey(control.controlRef), control]; });
395
+ var result = descendants.reduce(function (acc, _a) {
396
+ var _b;
397
+ var key = _a[0], control = _a[1];
398
+ if (isChildRef(control.controlRef, controlRef)) {
399
+ var newChildValue = value[control.controlRef.at(-1)];
400
+ var validatorErrors = getErrors(control, newChildValue, providers);
401
+ var oldChildValue = control.value;
402
+ var newControl = __assign(__assign({}, control), { value: newChildValue, validatorErrors: validatorErrors, dirty: !isEqual(newChildValue, control.pristineValue) });
403
+ acc = __assign(__assign({}, acc), (_b = {}, _b[key] = newControl, _b));
404
+ var configControls = control.config.controls;
405
+ if (configControls) {
406
+ checkKeys(oldChildValue, newChildValue);
407
+ acc = updateDescendantValues(acc, {
408
+ payload: { controlRef: control.controlRef, value: newChildValue }
409
+ }, providers);
410
+ }
411
+ }
412
+ return acc;
413
+ }, form);
414
+ return result;
415
+ };
416
+ // Will only update child controls that are present.
417
+ // Use AddControlPayload/RemoveControl action reducers to add/remove control
418
+ var updateValues = function (_a, action, providers, mergeChanges) {
419
+ var _b, _c;
420
+ var form = _a.form, _d = _a._changedControls, _changedControls = _d === void 0 ? {} : _d, _e = _a._removedControls, _removedControls = _e === void 0 ? {} : _e;
421
+ if (mergeChanges === void 0) { mergeChanges = false; }
422
+ var normalizers = providers.normalizers;
423
+ var _f = action.payload, controlRef = _f.controlRef, value = _f.value;
424
+ controlRefCheck(controlRef);
425
+ // Update its own value
426
+ var ctrlKey = getFormKey(controlRef);
427
+ var newValue = value;
428
+ var oldValue = form[ctrlKey].value;
429
+ var config = form[ctrlKey].config;
430
+ if (config.normalizers) {
431
+ newValue = config.normalizers.reduce(function (acc, normalizer) {
432
+ if (!normalizers[normalizer]) {
433
+ throw "You have not provided a normalizer for \"".concat(normalizer, "\"");
434
+ }
435
+ return normalizers[normalizer](acc);
436
+ }, value);
437
+ }
438
+ var validatorErrors = getErrors(form[ctrlKey], newValue, providers);
439
+ var newControl = __assign(__assign({}, form[ctrlKey]), { validatorErrors: validatorErrors, dirty: !isEqual(value, form[ctrlKey].pristineValue), value: newValue });
440
+ var result = {
441
+ form: __assign(__assign({}, form), (_b = {}, _b[ctrlKey] = newControl, _b)),
442
+ _changedControls: (_c = {}, _c[newControl.key] = newControl, _c)
443
+ };
444
+ var configControls = config.controls;
445
+ // Update its descendants
446
+ if (configControls) {
447
+ checkKeys(oldValue, newValue);
448
+ var updatedDescendants = updateDescendantValues(result.form, {
449
+ payload: {
450
+ controlRef: controlRef,
451
+ value: newValue
452
+ }
453
+ }, providers);
454
+ var changedDescendantControls = getDescendantControls(controlRef, updatedDescendants).reduce(function (acc, control) {
455
+ var _a;
456
+ return (__assign(__assign({}, acc), (_a = {}, _a[control.key] = control, _a)));
457
+ }, {});
458
+ result = __assign(__assign({}, result), { form: updatedDescendants, _changedControls: __assign(__assign({}, result._changedControls), changedDescendantControls) });
459
+ }
460
+ // Update its Ancestors
461
+ if (controlRef.length) {
462
+ result = __assign(__assign({}, result), { form: updateAncestorValues(result.form, {
463
+ payload: { controlRef: controlRef, value: newValue }
464
+ }, providers) });
465
+ }
466
+ var changedAncestorControls = getAncestorControls(controlRef, result.form).reduce(function (acc, control) {
467
+ var _a;
468
+ return (__assign(__assign({}, acc), (_a = {}, _a[control.key] = control, _a)));
469
+ }, {});
470
+ var mergedResult = __assign(__assign({}, result), { _changedControls: __assign(__assign(__assign({}, (mergeChanges ? _changedControls : undefined)), changedAncestorControls), result._changedControls), _removedControls: mergeChanges ? _removedControls : undefined });
471
+ return mergedResult;
472
+ };
473
+
474
+ var updateAncestorValuesRemoveControl = function (form, _a, providers) {
475
+ var _b;
476
+ var controlRef = _a.payload;
477
+ if (controlRef.length) {
478
+ var parentRef = controlRef.slice(0, -1);
479
+ var parentControl = getControl(parentRef, form);
480
+ var parentFormKey = getFormKey(parentControl.controlRef);
481
+ var childKey_1 = controlRef.slice(-1)[0];
482
+ var newValue = void 0;
483
+ // If parent is a Form Array
484
+ if (Array.isArray(parentControl.value)) {
485
+ newValue = parentControl.value.filter(function (item, index) { return index !== childKey_1; });
486
+ }
487
+ else {
488
+ // If parent is a Form Group
489
+ newValue = __assign({}, parentControl.value);
490
+ delete newValue[childKey_1];
491
+ }
492
+ var newParentControl = __assign(__assign({}, parentControl), { value: newValue, validatorErrors: getErrors(parentControl, newValue, providers), dirty: !isEqual(newValue, parentControl.pristineValue) });
493
+ return updateAncestorValues(__assign(__assign({}, form), (_b = {}, _b[parentFormKey] = newParentControl, _b)), {
494
+ payload: { controlRef: parentRef, value: newValue }
495
+ }, providers);
496
+ }
497
+ return form;
498
+ };
499
+
500
+ var removeControl = function (state, action, providers, mergeChanges) {
501
+ var _a;
502
+ if (mergeChanges === void 0) { mergeChanges = false; }
503
+ var form = state.form;
504
+ var controlRef = action.payload;
505
+ controlRefCheck(controlRef);
506
+ var controlToRemove = getControl(controlRef, form);
507
+ if (!controlToRemove) {
508
+ throw 'Control not found';
509
+ }
510
+ // Can't remove the root of the form
511
+ if (!controlRef.length)
512
+ return { form: form };
513
+ var parentRef = controlRef.slice(0, -1);
514
+ var parentIsFormArray = Array.isArray(getControl(parentRef, form).config.controls);
515
+ var descendants = getDescendantControls(controlRef, form);
516
+ var descendantkeys = descendants.map(function (_a) {
517
+ var controlRef = _a.controlRef;
518
+ return getFormKey(controlRef);
519
+ });
520
+ var controlsRemoved = __assign({}, form);
521
+ descendantkeys.forEach(function (key) {
522
+ delete controlsRemoved[key];
523
+ });
524
+ // Remove control and all descendants
525
+ var controlRemoved = Object.entries(controlsRemoved).reduce(function (acc, _a) {
526
+ var _b, _c;
527
+ var key = _a[0], control = _a[1];
528
+ // May need to reindex array items of removed control
529
+ // if it was part of a Form Array.
530
+ if (parentIsFormArray) {
531
+ var oldIndex = control.controlRef.at(parentRef.length);
532
+ if (
533
+ // If control is descendant.
534
+ parentRef.every(function (ref, index) { return control.controlRef[index] === ref; }) &&
535
+ control.controlRef.length > parentRef.length &&
536
+ // If the array item index was greater than the index of item removed
537
+ // we need to decrement its index by 1.
538
+ oldIndex > controlRef.at(-1)) {
539
+ var newRef = parentRef
540
+ .concat(oldIndex - 1)
541
+ .concat(control.controlRef.slice(parentRef.length + 1));
542
+ return __assign(__assign({}, acc), (_b = {}, _b[getFormKey(newRef)] = __assign(__assign({}, control), { controlRef: newRef }), _b));
543
+ }
544
+ }
545
+ return __assign(__assign({}, acc), (_c = {}, _c[key] = control, _c));
546
+ }, {});
547
+ var result = updateAncestorValuesRemoveControl(controlRemoved, {
548
+ payload: controlRef
549
+ }, providers);
550
+ var _changedControls = __assign(__assign({}, (mergeChanges ? state._changedControls || {} : undefined)), getAncestorControls(controlRef.slice(0, -1), result).reduce(function (acc, control) {
551
+ var _a;
552
+ return (__assign(__assign({}, acc), (_a = {}, _a[control.key] = control, _a)));
553
+ }, {}));
554
+ // Check for reindexing for changed controls
555
+ if (parentIsFormArray) {
556
+ _changedControls = Object.entries(_changedControls).reduce(function (acc, _a) {
557
+ var _b, _c;
558
+ var key = _a[0], control = _a[1];
559
+ var oldIndex = control.controlRef.at(parentRef.length);
560
+ if (
561
+ // If control is descendant.
562
+ parentRef.every(function (ref, index) { return control.controlRef[index] === ref; }) &&
563
+ control.controlRef.length > parentRef.length &&
564
+ // If the array item index was greater than the index of item removed
565
+ // we need to decrement its index by 1.
566
+ oldIndex > controlRef.at(-1)) {
567
+ var newRef = parentRef
568
+ .concat(oldIndex - 1)
569
+ .concat(control.controlRef.slice(parentRef.length + 1));
570
+ return __assign(__assign({}, acc), (_b = {}, _b[getFormKey(newRef)] = __assign(__assign({}, control), { controlRef: newRef }), _b));
571
+ }
572
+ else {
573
+ return __assign(__assign({}, acc), (_c = {}, _c[key] = control, _c));
574
+ }
575
+ }, {});
576
+ }
577
+ var _removedControls = __assign(__assign({}, (mergeChanges ? state._removedControls || {} : undefined)), (_a = {}, _a[controlToRemove.key] = controlToRemove, _a));
578
+ descendants
579
+ .map(function (_a) {
580
+ var key = _a.key;
581
+ return key;
582
+ })
583
+ .forEach(function (key) {
584
+ delete _changedControls[key];
585
+ });
586
+ return {
587
+ form: result,
588
+ _changedControls: _changedControls,
589
+ _removedControls: _removedControls
590
+ };
591
+ };
592
+
593
+ var updateAncestorValuesAddControl = function (form, _a, providers) {
594
+ var _b, _c;
595
+ var _d = _a.payload, controlRef = _d.controlRef, value = _d.value;
596
+ if (controlRef.length) {
597
+ var parentRef = controlRef.slice(0, -1);
598
+ var parentControl = getControl(parentRef, form);
599
+ var parentFormKey = getFormKey(parentControl.controlRef);
600
+ var childKey = controlRef.slice(-1)[0];
601
+ var newValue = void 0;
602
+ // If parent is a Form Array
603
+ if (Array.isArray(parentControl.value)) {
604
+ newValue = parentControl.value.concat(value);
605
+ }
606
+ else {
607
+ // If parent is a Form Group
608
+ newValue = __assign(__assign({}, form[parentFormKey].value), (_b = {}, _b[childKey] = value, _b));
609
+ }
610
+ var newParentControl = __assign(__assign({}, parentControl), { value: newValue, validatorErrors: getErrors(parentControl, newValue, providers), dirty: !isEqual(newValue, parentControl.pristineValue) });
611
+ return updateAncestorValues(__assign(__assign({}, form), (_c = {}, _c[parentFormKey] = newParentControl, _c)), {
612
+ payload: { controlRef: parentRef, value: newValue }
613
+ }, providers);
614
+ }
615
+ return form;
616
+ };
617
+
618
+ var getControlBranch = function (controlRef, form) {
619
+ var ancestors = getAncestorControls(controlRef, form);
620
+ var childControls = getDescendantControls(controlRef, form).slice(1);
621
+ return ancestors.concat(childControls).sort(function (a, b) { return a.controlRef.length - b.controlRef.length; });
622
+ };
623
+
624
+ var addControl = function (state, action, providers, mergeChanges) {
625
+ if (mergeChanges === void 0) { mergeChanges = false; }
626
+ var _a = action.payload, config = _a.config, controlRef = _a.controlRef;
627
+ controlRefCheck(controlRef);
628
+ // If controlRef does not exist we are adding control to a Form Group
629
+ if (!getControl(controlRef.slice(0, -1), state.form)) {
630
+ throw 'You are attempting to add a control to a non-existent form group';
631
+ }
632
+ var newForm = buildState(config, state.form, controlRef, providers);
633
+ var newValue = getControl(controlRef, newForm).value;
634
+ var ancestorsUpdated = updateAncestorValuesAddControl(newForm, {
635
+ payload: { controlRef: controlRef, value: newValue }
636
+ }, providers);
637
+ var _changedControls = getControlBranch(controlRef, ancestorsUpdated).reduce(function (acc, control) {
638
+ var _a;
639
+ return (__assign(__assign({}, acc), (_a = {}, _a[control.key] = control, _a)));
640
+ }, {});
641
+ return {
642
+ form: ancestorsUpdated,
643
+ _changedControls: __assign(__assign({}, (mergeChanges ? state._changedControls || {} : undefined)), _changedControls),
644
+ _removedControls: mergeChanges ? state._removedControls || {} : undefined
645
+ };
646
+ };
647
+
648
+ var pushControl = function (state, action, providers, mergeChanges) {
649
+ if (mergeChanges === void 0) { mergeChanges = false; }
650
+ var newControlRef;
651
+ var _a = action.payload, config = _a.config, controlRef = _a.controlRef;
652
+ controlRefCheck(controlRef);
653
+ var existingControl = getControl(controlRef, state.form);
654
+ if (!existingControl)
655
+ throw 'You are attempting to push to a control that does not exist';
656
+ // If controlRef exists we are adding control to a Form Array
657
+ if (Array.isArray(existingControl.config.controls)) {
658
+ newControlRef = controlRef.concat(existingControl.value.length);
659
+ }
660
+ else {
661
+ throw 'You are attempting to push to a control that is not a Form Array';
662
+ }
663
+ var newForm = buildState(config, state.form, newControlRef, providers);
664
+ var newValue = getControl(newControlRef, newForm).value;
665
+ var ancestorsUpdated = updateAncestorValuesAddControl(newForm, {
666
+ payload: { controlRef: newControlRef, value: newValue }
667
+ }, providers);
668
+ var _changedControls = getControlBranch(newControlRef, ancestorsUpdated).reduce(function (acc, control) {
669
+ var _a;
670
+ return (__assign(__assign({}, acc), (_a = {}, _a[control.key] = control, _a)));
671
+ }, {});
672
+ return {
673
+ form: ancestorsUpdated,
674
+ _changedControls: __assign(__assign({}, (mergeChanges ? state._changedControls || {} : undefined)), _changedControls),
675
+ _removedControls: mergeChanges ? state._removedControls || {} : undefined
676
+ };
677
+ };
678
+
679
+ var updateAncestorPristineValues = function (form, _a) {
680
+ var _b;
681
+ var controlRef = _a.payload;
682
+ if (controlRef.length) {
683
+ var parentRef = controlRef.slice(0, -1);
684
+ var parentKey = getFormKey(parentRef);
685
+ var siblingControls = getDescendantControls(parentRef, form).filter(
686
+ // Out of descendants we only need the siblings
687
+ function (control) { return control.controlRef.length === controlRef.length; });
688
+ var newValue = void 0;
689
+ // If parent is a Form Array
690
+ if (Array.isArray(form[parentKey].value)) {
691
+ newValue = siblingControls
692
+ .slice()
693
+ .sort(function (a, b) { return a.controlRef.at(-1) - b.controlRef.at(-1); })
694
+ .map(function (control) { return control.pristineValue; });
695
+ }
696
+ else {
697
+ // If parent is a Form Group
698
+ newValue = siblingControls.reduce(function (acc, _a) {
699
+ var _b;
700
+ var controlRef = _a.controlRef, pristineValue = _a.pristineValue;
701
+ return __assign(__assign({}, acc), (_b = {}, _b[controlRef.at(-1)] = pristineValue, _b));
702
+ }, {});
703
+ }
704
+ var newParentControl = __assign(__assign({}, form[parentKey]), { pristineValue: newValue, dirty: isEqual(form[parentKey].value, newValue) });
705
+ return updateAncestorPristineValues(__assign(__assign({}, form), (_b = {}, _b[parentKey] = newParentControl, _b)), {
706
+ payload: parentRef
707
+ });
708
+ }
709
+ return form;
710
+ };
711
+
712
+ var markControlAsPristine = function (state, action, mergeChanges) {
713
+ if (mergeChanges === void 0) { mergeChanges = false; }
714
+ var form = state.form;
715
+ var controlRef = action.payload;
716
+ controlRefCheck(controlRef);
717
+ var descendants = getDescendantControls(controlRef, form).reduce(function (acc, control) {
718
+ var _a;
719
+ return (__assign(__assign({}, acc), (_a = {}, _a[getFormKey(control.controlRef)] = __assign(__assign({}, control), { dirty: false, pristineValue: control.value }), _a)));
720
+ }, {});
721
+ var result = __assign(__assign({}, form), descendants);
722
+ if (controlRef.length) {
723
+ result = updateAncestorPristineValues(result, {
724
+ payload: controlRef
725
+ });
726
+ }
727
+ var _changedControls = getControlBranch(controlRef, result).reduce(function (acc, control) {
728
+ var _a;
729
+ return (__assign(__assign({}, acc), (_a = {}, _a[control.key] = control, _a)));
730
+ }, {});
731
+ return {
732
+ form: result,
733
+ _changedControls: __assign(__assign({}, (mergeChanges ? state._changedControls || {} : undefined)), _changedControls),
734
+ _removedControls: mergeChanges ? state._removedControls || {} : undefined
735
+ };
736
+ };
737
+
738
+ var markControlAsTouched = function (state, action, mergeChanges) {
739
+ if (mergeChanges === void 0) { mergeChanges = false; }
740
+ var form = state.form;
741
+ var _a = action.payload, controlRef = _a.controlRef, _b = _a.markAll, markAll = _b === void 0 ? false : _b;
742
+ controlRefCheck(controlRef);
743
+ var controls = (markAll ? getControlBranch(controlRef, form) : getAncestorControls(controlRef, form)).reduce(function (acc, control) {
744
+ var _a;
745
+ return (__assign(__assign({}, acc), (_a = {}, _a[getFormKey(control.controlRef)] = __assign(__assign({}, control), { touched: true }), _a)));
746
+ }, {});
747
+ var result = {
748
+ form: __assign(__assign({}, form), controls)};
749
+ var _changedControls = getControlBranch(controlRef, result.form).reduce(function (acc, control) {
750
+ var _a;
751
+ return (__assign(__assign({}, acc), (_a = {}, _a[control.key] = control, _a)));
752
+ }, {});
753
+ return {
754
+ form: __assign(__assign({}, form), controls),
755
+ _changedControls: __assign(__assign({}, (mergeChanges ? state._changedControls || {} : undefined)), _changedControls),
756
+ _removedControls: mergeChanges ? state._removedControls || {} : undefined
757
+ };
758
+ };
759
+
760
+ var markControlAsUntouched = function (state, action, mergeChanges) {
761
+ var _a;
762
+ if (mergeChanges === void 0) { mergeChanges = false; }
763
+ var form = state.form;
764
+ var controlRef = action.payload;
765
+ controlRefCheck(controlRef);
766
+ var result = getDescendantControls(controlRef, form).reduce(function (acc, control) {
767
+ var _a;
768
+ return (__assign(__assign({}, acc), (_a = {}, _a[getFormKey(control.controlRef)] = __assign(__assign({}, control), { touched: false }), _a)));
769
+ }, {});
770
+ result = __assign(__assign({}, form), result);
771
+ // Update ancestors
772
+ var currentRef = controlRef;
773
+ var key;
774
+ while (currentRef.length > 0) {
775
+ currentRef = currentRef.slice(0, -1);
776
+ key = getFormKey(currentRef);
777
+ result = __assign(__assign({}, result), (_a = {}, _a[key] = __assign(__assign({}, result[key]), { touched: getDescendantControls(currentRef, result, true).some(function (control) { return control.touched; }) }), _a));
778
+ }
779
+ var _changedControls = getControlBranch(controlRef, result).reduce(function (acc, control) {
780
+ var _a;
781
+ return (__assign(__assign({}, acc), (_a = {}, _a[control.key] = control, _a)));
782
+ }, {});
783
+ return {
784
+ form: result,
785
+ _changedControls: __assign(__assign({}, (mergeChanges ? state._changedControls || {} : undefined)), _changedControls),
786
+ _removedControls: mergeChanges ? state._removedControls || {} : undefined
787
+ };
788
+ };
789
+
790
+ var resetControl = function (state, action, providers, mergeChanges) {
791
+ var _a;
792
+ if (mergeChanges === void 0) { mergeChanges = false; }
793
+ var form = state.form;
794
+ var controlRef = action.payload;
795
+ controlRefCheck(controlRef);
796
+ var controlToReset = getControl(controlRef, form);
797
+ var descendantsRemoved = __assign({}, form);
798
+ var descendants = getDescendantControls(controlRef, form);
799
+ var descendantKeys = descendants.map(function (_a) {
800
+ var controlRef = _a.controlRef;
801
+ return getFormKey(controlRef);
802
+ });
803
+ descendantKeys.forEach(function (key) {
804
+ delete descendantsRemoved[key];
805
+ });
806
+ // Remove all descendants
807
+ var restoredControls = buildState(controlToReset.config, descendantsRemoved, controlToReset.controlRef, providers);
808
+ var restoredControlValue = getControl(controlRef, restoredControls).value;
809
+ var result = updateAncestorValues(restoredControls, {
810
+ payload: { controlRef: controlRef, value: restoredControlValue }
811
+ }, providers);
812
+ var _changedControls = __assign(__assign({}, (mergeChanges ? state._changedControls || {} : undefined)), getControlBranch(controlRef, result).reduce(function (acc, control) {
813
+ var _a;
814
+ return (__assign(__assign({}, acc), (_a = {}, _a[control.key] = control, _a)));
815
+ }, {}));
816
+ var _removedControls = __assign(__assign({}, (mergeChanges ? state._removedControls || {} : undefined)), (_a = {}, _a[controlToReset.key] = controlToReset, _a));
817
+ // If control is removed, we can delete it from the _changedControls check
818
+ descendants
819
+ .map(function (_a) {
820
+ var key = _a.key;
821
+ return key;
822
+ })
823
+ .forEach(function (key) {
824
+ delete _changedControls[key];
825
+ });
826
+ return {
827
+ form: result,
828
+ _changedControls: _changedControls,
829
+ _removedControls: _removedControls
830
+ };
831
+ };
832
+
833
+ var asyncValidation = function (form, _a) {
834
+ var controlRef = _a.payload;
835
+ var updatedSelfAndAncestors = getAncestorControls(controlRef, form).reduce(function (acc, control) {
836
+ var _a;
837
+ var isChangedControl = getFormKey(control.controlRef) === getFormKey(controlRef);
838
+ return __assign(__assign({}, acc), (_a = {}, _a[getFormKey(control.controlRef)] = __assign(__assign({}, control), { pending: true, asyncValidateInProgress: isChangedControl
839
+ ? __assign({}, control.config.asyncValidators.reduce(function (acc, _, index) {
840
+ var _a;
841
+ return (__assign(__assign({}, acc), (_a = {}, _a[index] = true, _a)));
842
+ }, {})) : control.asyncValidateInProgress }), _a));
843
+ }, {});
844
+ return __assign(__assign({}, form), updatedSelfAndAncestors);
845
+ };
846
+
847
+ var reverseObjectKeys = function (form) {
848
+ return Object.keys(form)
849
+ .reverse()
850
+ .reduce(function (acc, key) {
851
+ acc[key] = form[key];
852
+ return acc;
853
+ }, {});
854
+ };
855
+
856
+ var hasErrors$3 = function (errors) {
857
+ return Object.values(errors).some(function (hasError) { return hasError; });
858
+ };
859
+ var mergeBranchErrors = function (form, controlRef) {
860
+ var controlBranch = getControlBranch(controlRef, form).reduce(function (acc, ctrl) {
861
+ var _a;
862
+ return __assign(__assign({}, acc), (_a = {}, _a[getFormKey(ctrl.controlRef)] = ctrl, _a));
863
+ }, {});
864
+ var errorsMerged = Object.entries(controlBranch)
865
+ .reverse()
866
+ .reduce(function (acc, _a) {
867
+ var _b;
868
+ var key = _a[0], control = _a[1];
869
+ var errors = __assign(__assign({}, control.validatorErrors), control.asyncValidatorErrors);
870
+ var selfValid = !hasErrors$3(errors);
871
+ var childrenValid = true;
872
+ if (Array.isArray(control.config.controls)) {
873
+ // If control is a FormArray
874
+ childrenValid = control.value.every(function (item, index) {
875
+ var formKey = getFormKey(control.controlRef.concat(index));
876
+ var valid = acc[formKey] === undefined ? form[formKey].valid : acc[formKey].valid;
877
+ return valid;
878
+ });
879
+ }
880
+ else if (control.config.controls) {
881
+ // If control is a FormGroup
882
+ childrenValid = Object.keys(control.value).every(function (childKey) {
883
+ var formKey = getFormKey(control.controlRef.concat(childKey));
884
+ var valid = acc[formKey] === undefined ? form[formKey].valid : acc[formKey].valid;
885
+ return valid;
886
+ });
887
+ }
888
+ return __assign(__assign({}, acc), (_b = {}, _b[key] = __assign(__assign({}, control), { errors: errors, valid: selfValid && childrenValid, childrenValid: childrenValid }), _b));
889
+ }, {});
890
+ var errorsMergedOrderRestored = reverseObjectKeys(errorsMerged);
891
+ return __assign(__assign({}, form), errorsMergedOrderRestored);
892
+ };
893
+
894
+ var isControlValidating = function (control) {
895
+ if (!control.asyncValidateInProgress)
896
+ return false;
897
+ return Object.values(control.asyncValidateInProgress).some(function (pending) { return pending; });
898
+ };
899
+ var getControlByKey = function (key, form) {
900
+ return Object.values(form).find(function (control) { return control.key === key; });
901
+ };
902
+ var asyncValidationResponse = function (form, _a) {
903
+ var _b, _c;
904
+ var _d = _a.payload, key = _d.key, validatorIndex = _d.validatorIndex, errors = _d.errors;
905
+ var control = getControlByKey(key, form);
906
+ if (!control) {
907
+ return form;
908
+ }
909
+ var controlUpdated = __assign(__assign({}, form), (_b = {}, _b[getFormKey(control.controlRef)] = __assign(__assign({}, control), { asyncValidateInProgress: __assign(__assign({}, control.asyncValidateInProgress), (_c = {}, _c[validatorIndex] = false, _c)), asyncValidatorErrors: __assign(__assign({}, control.asyncValidatorErrors), errors) }), _b));
910
+ var ancestors = getAncestorControls(control.controlRef, controlUpdated);
911
+ var ancestorsUpdated = Object.entries(controlUpdated).reduce(function (acc, _a) {
912
+ var _b, _c;
913
+ var key = _a[0], control = _a[1];
914
+ if (ancestors.includes(control)) {
915
+ var descendants = getDescendantControls(control.controlRef, controlUpdated);
916
+ var pending_1 = descendants.some(function (control) { return isControlValidating(control); });
917
+ return __assign(__assign({}, acc), (_b = {}, _b[key] = __assign(__assign({}, control), { pending: pending_1 }), _b));
918
+ }
919
+ return __assign(__assign({}, acc), (_c = {}, _c[key] = control, _c));
920
+ }, {});
921
+ return mergeBranchErrors(ancestorsUpdated, control.controlRef);
922
+ };
923
+
924
+ var hasErrors$2 = function (errors) {
925
+ return Object.values(errors).some(function (hasError) { return hasError; });
926
+ };
927
+ // TODO: update merge errors to not do the entire form but just a subset of it
928
+ // TODO: separation of concern to update validity of control and ancestors
929
+ var mergeErrors = function (form) {
930
+ var errorsMerged = Object.entries(form)
931
+ .reverse()
932
+ .reduce(function (acc, _a) {
933
+ var _b;
934
+ var key = _a[0], control = _a[1];
935
+ var errors = __assign(__assign({}, control.validatorErrors), control.asyncValidatorErrors);
936
+ var selfValid = !hasErrors$2(errors);
937
+ var childrenValid = true;
938
+ if (Array.isArray(control.config.controls)) {
939
+ // If control is a FormArray
940
+ childrenValid = control.value.every(function (item, index) { return acc[getFormKey(control.controlRef.concat(index))].valid; });
941
+ }
942
+ else if (control.config.controls) {
943
+ // If control is a FormGroup
944
+ childrenValid = Object.keys(control.value).every(function (childKey) { return acc[getFormKey(control.controlRef.concat(childKey))].valid; });
945
+ }
946
+ return __assign(__assign({}, acc), (_b = {}, _b[key] = __assign(__assign({}, control), { errors: errors, valid: selfValid && childrenValid, childrenValid: childrenValid }), _b));
947
+ }, {});
948
+ var restoredOrder = reverseObjectKeys(errorsMerged);
949
+ return restoredOrder;
950
+ };
951
+
952
+ var hasErrors$1 = function (errors) {
953
+ return Object.values(errors).some(function (hasError) { return hasError; });
954
+ };
955
+ var mergeRemoveControl = function (state, form, controlRef) {
956
+ var parentRef = controlRef.slice(0, -1);
957
+ var existingBranch = getControlBranch(parentRef, state);
958
+ var updatedControlBranch = getControlBranch(parentRef, form)
959
+ .reverse()
960
+ .reduce(function (acc, baseControl) {
961
+ var _a;
962
+ var key = getFormKey(baseControl.controlRef);
963
+ var existingControl = existingBranch.find(function (control) { return baseControl.key === control.key; }) ||
964
+ structuredClone(DEFAULT_HUB2_FIELDS);
965
+ var errors = __assign(__assign({}, baseControl.validatorErrors), existingControl.asyncValidatorErrors);
966
+ var selfValid = !hasErrors$1(errors);
967
+ var childrenValid = true;
968
+ if (Array.isArray(baseControl.config.controls)) {
969
+ // If control is a FormArray
970
+ childrenValid = baseControl.value.every(function (item, index) {
971
+ var formKey = getFormKey(baseControl.controlRef.concat(index));
972
+ var valid = acc[formKey] === undefined ? state[formKey].valid : acc[formKey].valid;
973
+ return valid;
974
+ });
975
+ }
976
+ else if (baseControl.config.controls) {
977
+ // If control is a FormGroup
978
+ childrenValid = Object.keys(baseControl.value).every(function (childKey) {
979
+ var formKey = getFormKey(baseControl.controlRef.concat(childKey));
980
+ var valid = acc[formKey] === undefined ? state[formKey].valid : acc[formKey].valid;
981
+ return valid;
982
+ });
983
+ }
984
+ return __assign(__assign({}, acc), (_a = {}, _a[key] = __assign(__assign(__assign({}, existingControl), baseControl), { errors: errors, valid: selfValid && childrenValid, childrenValid: childrenValid }), _a));
985
+ }, {});
986
+ var updatedControlBranchOrderRestored = reverseObjectKeys(updatedControlBranch);
987
+ var descendants = existingBranch.filter(function (control) { return control.controlRef.length > parentRef.length; });
988
+ var _removedControls = __assign({}, state);
989
+ descendants.forEach(function (control) {
990
+ delete _removedControls[getFormKey(control.controlRef)];
991
+ });
992
+ delete _removedControls[getFormKey(controlRef)];
993
+ return __assign(__assign({}, _removedControls), updatedControlBranchOrderRestored);
994
+ };
995
+
996
+ var hasErrors = function (errors) {
997
+ return Object.values(errors).some(function (hasError) { return hasError; });
998
+ };
999
+ var mergeControls = function (state, _a) {
1000
+ var form = _a.form, _b = _a._changedControls, _changedControls = _b === void 0 ? {} : _b, _removedControls = _a._removedControls;
1001
+ var controlsRemoved = _removedControls
1002
+ ? Object.values(_removedControls).reduce(function (acc, _a) {
1003
+ var controlRef = _a.controlRef;
1004
+ return mergeRemoveControl(acc, form, controlRef);
1005
+ }, state)
1006
+ : state;
1007
+ var updatedBranch = Object.values(_changedControls)
1008
+ .reverse()
1009
+ .reduce(function (acc, control) {
1010
+ var _a;
1011
+ var formKey = getFormKey(control.controlRef);
1012
+ var existingControl = controlsRemoved && controlsRemoved[formKey];
1013
+ var newControl = __assign(__assign({}, (existingControl
1014
+ ? existingControl
1015
+ : structuredClone(DEFAULT_HUB2_FIELDS))), control);
1016
+ var errors = __assign(__assign({}, newControl.validatorErrors), newControl.asyncValidatorErrors);
1017
+ var selfValid = !hasErrors(errors);
1018
+ var childrenValid = true;
1019
+ if (Array.isArray(control.config.controls)) {
1020
+ // If control is a FormArray
1021
+ childrenValid = control.value.every(function (item, index) {
1022
+ var formKey = getFormKey(control.controlRef.concat(index));
1023
+ var valid = acc[formKey] === undefined ? controlsRemoved[formKey].valid : acc[formKey].valid;
1024
+ return valid;
1025
+ });
1026
+ }
1027
+ else if (control.config.controls) {
1028
+ // If control is a FormGroup
1029
+ childrenValid = Object.keys(control.value).every(function (childKey) {
1030
+ var formKey = getFormKey(control.controlRef.concat(childKey));
1031
+ var valid = acc[formKey] === undefined ? controlsRemoved[formKey].valid : acc[formKey].valid;
1032
+ return valid;
1033
+ });
1034
+ }
1035
+ return __assign(__assign({}, acc), (_a = {}, _a[formKey] = __assign(__assign({}, newControl), { errors: errors, valid: selfValid && childrenValid, childrenValid: childrenValid }), _a));
1036
+ }, {});
1037
+ var orderRestored = reverseObjectKeys(updatedBranch);
1038
+ var result = __assign(__assign({}, controlsRemoved), orderRestored);
1039
+ return result;
1040
+ };
1041
+
1042
+ var formChange = function (state, _a) {
1043
+ if (state === void 0) { state = null; }
1044
+ var payload = _a.payload;
1045
+ var form = payload.form;
1046
+ if (state === null) {
1047
+ return mergeErrors(Object.entries(form).reduce(function (acc, _a) {
1048
+ var _b;
1049
+ var dictKey = _a[0], baseControl = _a[1];
1050
+ return __assign(__assign({}, acc), (_b = {}, _b[dictKey] = __assign(__assign({}, structuredClone(DEFAULT_HUB2_FIELDS)), baseControl), _b));
1051
+ }, {}));
1052
+ }
1053
+ return mergeControls(state, payload);
1054
+ };
1055
+
1056
+ var control = function (config) {
1057
+ if (Array.isArray(config)) {
1058
+ return config.reduce(function (acc, item, index) {
1059
+ var _a;
1060
+ var indexMap = {
1061
+ 0: 'initialValue',
1062
+ 1: 'validators',
1063
+ 2: 'asyncValidators'
1064
+ };
1065
+ return __assign(__assign({}, acc), (_a = {}, _a[indexMap[index]] = index < 1 ? item : [].concat(item || []), _a));
1066
+ }, {});
1067
+ }
1068
+ return config;
1069
+ };
1070
+ var array = function (config) { return config; };
1071
+ var group = function (config) { return config; };
1072
+ var reducerTools = function (providers) { return ({
1073
+ updateValues: function (state, payload) {
1074
+ return updateValues(state, { payload: payload }, providers, true);
1075
+ },
1076
+ removeControl: function (state, payload) {
1077
+ return removeControl(state, { payload: payload }, providers, true);
1078
+ },
1079
+ pushControl: function (state, payload) {
1080
+ return pushControl(state, { payload: payload }, providers, true);
1081
+ },
1082
+ addControl: function (state, payload) {
1083
+ return addControl(state, { payload: payload }, providers, true);
1084
+ },
1085
+ resetControl: function (state, payload) {
1086
+ return resetControl(state, { payload: payload }, providers, true);
1087
+ },
1088
+ markControlAsPristine: function (state, payload) {
1089
+ return markControlAsPristine(state, { payload: payload }, true);
1090
+ },
1091
+ markControlAsTouched: function (state, payload) {
1092
+ return markControlAsTouched(state, { payload: payload }, true);
1093
+ },
1094
+ markControlAsUntouched: function (state, payload) {
1095
+ return markControlAsUntouched(state, { payload: payload }, true);
1096
+ }
1097
+ }); };
1098
+ var build = function (config, options) {
1099
+ var _a, _b, _c;
1100
+ if (options === void 0) { options = {}; }
1101
+ var providers = {
1102
+ normalizers: __assign({}, (_a = options.providers) === null || _a === void 0 ? void 0 : _a.normalizers),
1103
+ validators: __assign(__assign({}, Validators), (_b = options.providers) === null || _b === void 0 ? void 0 : _b.validators),
1104
+ asyncValidators: __assign({}, (_c = options.providers) === null || _c === void 0 ? void 0 : _c.asyncValidators)
1105
+ };
1106
+ var initialState = buildFormState(config, undefined, undefined, providers);
1107
+ return createReactable(initialState, options);
1108
+ };
1109
+ var load = function (state, options) {
1110
+ if (options === void 0) { options = {}; }
1111
+ var baseFormState = {
1112
+ form: Object.entries(state).reduce(function (acc, _a) {
1113
+ var _b;
1114
+ var key = _a[0], control = _a[1];
1115
+ return __assign(__assign({}, acc), (_b = {}, _b[key] = Object.entries(control)
1116
+ .filter(function (_a) {
1117
+ var key = _a[0];
1118
+ return !Object.keys(DEFAULT_HUB2_FIELDS).includes(key);
1119
+ })
1120
+ .reduce(function (acc, _a) {
1121
+ var _b;
1122
+ var key = _a[0], value = _a[1];
1123
+ return (__assign(__assign({}, acc), (_b = {}, _b[key] = value, _b)));
1124
+ }, {}), _b));
1125
+ }, {})
1126
+ };
1127
+ return createReactable(baseFormState, options);
1128
+ };
1129
+ var createReactable = function (initialBaseState, options, initialFormState) {
1130
+ var _a, _b, _c;
1131
+ if (options === void 0) { options = {}; }
1132
+ var providers = {
1133
+ normalizers: __assign({}, (_a = options.providers) === null || _a === void 0 ? void 0 : _a.normalizers),
1134
+ validators: __assign(__assign({}, Validators), (_b = options.providers) === null || _b === void 0 ? void 0 : _b.validators),
1135
+ asyncValidators: __assign({}, (_c = options.providers) === null || _c === void 0 ? void 0 : _c.asyncValidators)
1136
+ };
1137
+ var reducers = options.reducers, debug = options.debug, name = options.name, otherOptions = __rest(options, ["reducers", "debug", "name"]);
1138
+ var customReducers = Object.entries(reducers || {}).reduce(function (acc, _a) {
1139
+ var _b;
1140
+ var key = _a[0], _case = _a[1];
1141
+ var _reducer = typeof _case === 'function' ? _case : _case.reducer;
1142
+ var effects = typeof _case === 'function' ? [] : _case.effects;
1143
+ return __assign(__assign({}, acc), (_b = {}, _b[key] = {
1144
+ reducer: function (_a, action) {
1145
+ var form = _a.form;
1146
+ return _reducer(reducerTools(providers), { form: form }, action);
1147
+ },
1148
+ effects: effects
1149
+ }, _b));
1150
+ }, {});
1151
+ var _d = core.RxBuilder(__assign({ initialState: initialBaseState, name: "Stage 1 ".concat(name ? name : 'rxForm'), debug: debug, reducers: __assign({ updateValues: function (state, action) {
1152
+ return updateValues(state, action, providers);
1153
+ }, removeControl: function (state, action) { return removeControl(state, action, providers); }, addControl: function (state, action) {
1154
+ return addControl(state, action, providers);
1155
+ }, pushControl: function (state, action) {
1156
+ return pushControl(state, action, providers);
1157
+ }, resetControl: function (state, action) { return resetControl(state, action, providers); }, markControlAsPristine: function (state, action) {
1158
+ return markControlAsPristine(state, action);
1159
+ }, markControlAsTouched: function (state, action) {
1160
+ return markControlAsTouched(state, action);
1161
+ }, markControlAsUntouched: function (state, action) {
1162
+ return markControlAsUntouched(state, action);
1163
+ } }, customReducers) }, otherOptions)), hub1State$ = _d[0], hub1Actions = _d[1], hub1Actions$ = _d[2];
1164
+ var _e = core.RxBuilder({
1165
+ sources: [buildHub2Source(hub1State$, initialBaseState).pipe(operators.skip(0))],
1166
+ initialState: null,
1167
+ name: "Stage 2 ".concat(name ? name : 'rxForm'),
1168
+ debug: debug,
1169
+ reducers: {
1170
+ formChange: formChange,
1171
+ asyncValidationEffect: {
1172
+ reducer: function (state) { return state; },
1173
+ effects: function (control) { return ({
1174
+ key: control.key,
1175
+ effects: getScopedEffectsForControl(control, providers)
1176
+ }); }
1177
+ },
1178
+ asyncValidation: asyncValidation,
1179
+ asyncValidationResponse: asyncValidationResponse
1180
+ }
1181
+ }), state$ = _e[0], hub2Actions = _e[1];
1182
+ var destroy = function () {
1183
+ hub1Actions.destroy();
1184
+ hub2Actions.destroy();
1185
+ };
1186
+ return [
1187
+ state$.pipe(operators.filter(function (form) { return form !== null; })),
1188
+ __assign(__assign({}, hub1Actions), { destroy: destroy }),
1189
+ hub1Actions$,
1190
+ ];
1191
+ };
1192
+
1193
+ var getArrayItems = function (controlRef, form) {
1194
+ var control = getControl(controlRef, form);
1195
+ if (!Array.isArray(control.config.controls)) {
1196
+ throw "".concat(controlRef.join('.'), " is not a Form Array control");
1197
+ }
1198
+ var result = control.value.map(function (_, index) { return form[getFormKey(controlRef.concat(index))]; });
1199
+ return result;
1200
+ };
1201
+
1202
+ exports.ControlModels = Controls;
1203
+ exports.Validators = index;
1204
+ exports.array = array;
1205
+ exports.build = build;
1206
+ exports.control = control;
1207
+ exports.getAncestorControls = getAncestorControls;
1208
+ exports.getArrayItems = getArrayItems;
1209
+ exports.getDescendantControls = getDescendantControls;
1210
+ exports.getValueFromControlConfig = getValueFromControlConfig;
1211
+ exports.group = group;
1212
+ exports.load = load;
1213
+ //# sourceMappingURL=index.cjs.map