@bonlineza/luxity-lib 2.39.4 → 2.39.6

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 (96) hide show
  1. package/Accordion.js +342 -352
  2. package/AddInterest.js +3109 -3068
  3. package/AddProductInterest.js +999 -7572
  4. package/BrandSelector.js +854 -861
  5. package/Checkbox.js +240 -250
  6. package/CheckboxButton.js +229 -236
  7. package/CommunicationPreferenceOptionsRenderer.js +560 -568
  8. package/CommunicationPreferenceSection.js +651 -659
  9. package/CommunicationPreferences.js +2394 -2402
  10. package/ConditionSelector.js +852 -859
  11. package/CountryCodeSelect.js +79 -6650
  12. package/CurrencyInputFormatter.js +86 -96
  13. package/CurrencySelect.js +219 -227
  14. package/DropdownSelector.js +212 -6821
  15. package/GALink.js +43 -51
  16. package/GenderSelector.js +355 -362
  17. package/GraphQLDropdownSelector.js +5308 -11832
  18. package/GraphQLMultiSelector.js +593 -601
  19. package/IconHeader.js +118 -126
  20. package/IconWrapper.js +17 -25
  21. package/InterestCatSelector.js +424 -389
  22. package/InterestItem.js +462 -469
  23. package/Interests.js +4719 -11243
  24. package/InterestsSubheading.js +33 -41
  25. package/InvertedTextButton.js +167 -175
  26. package/LuxityAppSideNav.js +181 -189
  27. package/LuxityDesktopHeader.js +1355 -1363
  28. package/LuxityFooter.js +2228 -2236
  29. package/LuxityGraphQLDropdownSelector.js +5395 -11919
  30. package/LuxityGraphQLMultiselector.js +778 -785
  31. package/LuxityMobileHeader.js +1786 -1794
  32. package/LuxityPageReady.js +199 -209
  33. package/LuxityProductInterestItem.js +359 -367
  34. package/LuxitySideNav.js +665 -673
  35. package/MaterialSelector.js +5430 -11954
  36. package/ModelSelector.js +5430 -11954
  37. package/NotificationDropDown.js +459 -7030
  38. package/Notify.js +20 -32
  39. package/OutlinePrimaryButton.js +134 -142
  40. package/PriceRangeSelector.js +1264 -1265
  41. package/PrimaryButton.js +129 -137
  42. package/RadioButtons.js +308 -318
  43. package/RangeSlider.js +1033 -1039
  44. package/RareStepFooter.js +257 -264
  45. package/RareStepHeader.js +801 -808
  46. package/ReactSelectWrapper.js +33 -6604
  47. package/SecondaryButton.js +144 -152
  48. package/ShoeSizeRangeSelector.js +1147 -1153
  49. package/ShoeSizeSelector.js +1146 -1154
  50. package/SimpleErrorBoundary.js +130 -138
  51. package/StyleSelector.js +854 -861
  52. package/TestComponent.js +15 -0
  53. package/TextButton.js +135 -143
  54. package/Tooltip.js +176 -184
  55. package/Tracking.js +15 -25
  56. package/WrapperButton.js +50 -58
  57. package/build/CountryCodeSelect/index.js +18 -0
  58. package/build/ReactSelectWrapper/index.js +34 -0
  59. package/build/bundle.css +1 -1
  60. package/build/bundle.js +10634 -17192
  61. package/build/constants.js +32 -43
  62. package/package.json +2 -2
  63. package/postcss.config.js +6 -0
  64. package/svg/Accessories.js +34 -42
  65. package/svg/Account.js +30 -38
  66. package/svg/Add.js +31 -39
  67. package/svg/ArrowRight.js +28 -36
  68. package/svg/Bags.js +40 -48
  69. package/svg/BurgerMenu.js +24 -32
  70. package/svg/Calendar.js +98 -106
  71. package/svg/CalendarCircled.js +100 -108
  72. package/svg/CheckCircled.js +32 -40
  73. package/svg/Close.js +29 -37
  74. package/svg/Clothing.js +36 -44
  75. package/svg/Dot.js +32 -40
  76. package/svg/Edit.js +27 -35
  77. package/svg/Eye.js +28 -36
  78. package/svg/FileAttach.js +28 -36
  79. package/svg/FileAttachCircled.js +30 -38
  80. package/svg/Jewellery.js +56 -0
  81. package/svg/LightBulb.js +58 -66
  82. package/svg/Logo.js +132 -140
  83. package/svg/LuxityMenu.js +28 -36
  84. package/svg/Minus.js +29 -37
  85. package/svg/MobileAvatar.js +28 -36
  86. package/svg/MyOrder.js +36 -44
  87. package/svg/MyPayment.js +36 -44
  88. package/svg/MyProfile.js +44 -52
  89. package/svg/MySale.js +31 -39
  90. package/svg/Notification.js +30 -38
  91. package/svg/PointerDown.js +28 -36
  92. package/svg/Search.js +27 -35
  93. package/svg/Shoes.js +37 -45
  94. package/svg/SvgWrapper.js +13 -21
  95. package/svg/Trash.js +32 -40
  96. package/svg/Watches.js +47 -55
@@ -1,2482 +1,2474 @@
1
- (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react'), require('styled-components'), require('@bonlineza/b-lib/EllipsisLoader'), require('react-notify-toast')) :
3
- typeof define === 'function' && define.amd ? define(['react', 'styled-components', '@bonlineza/b-lib/EllipsisLoader', 'react-notify-toast'], factory) :
4
- (global = global || self, global.CommunicationPreferences = factory(global.React, global.styled, global.EllipsisLoader, global['react-notify-toast']));
5
- }(this, (function (React, styled, EllipsisLoader, Notifications) { 'use strict';
6
-
7
- var React__default = 'default' in React ? React['default'] : React;
8
- var styled__default = 'default' in styled ? styled['default'] : styled;
9
- EllipsisLoader = EllipsisLoader && Object.prototype.hasOwnProperty.call(EllipsisLoader, 'default') ? EllipsisLoader['default'] : EllipsisLoader;
10
- var Notifications__default = 'default' in Notifications ? Notifications['default'] : Notifications;
11
-
12
- function ownKeys(object, enumerableOnly) {
13
- var keys = Object.keys(object);
14
-
15
- if (Object.getOwnPropertySymbols) {
16
- var symbols = Object.getOwnPropertySymbols(object);
17
- enumerableOnly && (symbols = symbols.filter(function (sym) {
18
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
19
- })), keys.push.apply(keys, symbols);
20
- }
21
-
22
- return keys;
1
+ import React, { forwardRef, useEffect, useState, Fragment } from 'react';
2
+ import styled, { ThemeProvider } from 'styled-components';
3
+ import EllipsisLoader from '@bonlineza/b-lib/EllipsisLoader';
4
+ import { notify } from 'react-notify-toast';
5
+
6
+ function ownKeys(object, enumerableOnly) {
7
+ var keys = Object.keys(object);
8
+
9
+ if (Object.getOwnPropertySymbols) {
10
+ var symbols = Object.getOwnPropertySymbols(object);
11
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
12
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
13
+ })), keys.push.apply(keys, symbols);
23
14
  }
24
15
 
25
- function _objectSpread2(target) {
26
- for (var i = 1; i < arguments.length; i++) {
27
- var source = null != arguments[i] ? arguments[i] : {};
28
- i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
29
- _defineProperty(target, key, source[key]);
30
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
31
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
32
- });
33
- }
16
+ return keys;
17
+ }
34
18
 
35
- return target;
19
+ function _objectSpread2(target) {
20
+ for (var i = 1; i < arguments.length; i++) {
21
+ var source = null != arguments[i] ? arguments[i] : {};
22
+ i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
23
+ _defineProperty(target, key, source[key]);
24
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
25
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
26
+ });
36
27
  }
37
28
 
38
- function _defineProperty(obj, key, value) {
39
- if (key in obj) {
40
- Object.defineProperty(obj, key, {
41
- value: value,
42
- enumerable: true,
43
- configurable: true,
44
- writable: true
45
- });
46
- } else {
47
- obj[key] = value;
48
- }
29
+ return target;
30
+ }
49
31
 
50
- return obj;
32
+ function _defineProperty(obj, key, value) {
33
+ if (key in obj) {
34
+ Object.defineProperty(obj, key, {
35
+ value: value,
36
+ enumerable: true,
37
+ configurable: true,
38
+ writable: true
39
+ });
40
+ } else {
41
+ obj[key] = value;
51
42
  }
52
43
 
53
- function _extends() {
54
- _extends = Object.assign ? Object.assign.bind() : function (target) {
55
- for (var i = 1; i < arguments.length; i++) {
56
- var source = arguments[i];
44
+ return obj;
45
+ }
46
+
47
+ function _extends() {
48
+ _extends = Object.assign ? Object.assign.bind() : function (target) {
49
+ for (var i = 1; i < arguments.length; i++) {
50
+ var source = arguments[i];
57
51
 
58
- for (var key in source) {
59
- if (Object.prototype.hasOwnProperty.call(source, key)) {
60
- target[key] = source[key];
61
- }
52
+ for (var key in source) {
53
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
54
+ target[key] = source[key];
62
55
  }
63
56
  }
64
-
65
- return target;
66
- };
67
- return _extends.apply(this, arguments);
68
- }
69
-
70
- function _objectWithoutPropertiesLoose(source, excluded) {
71
- if (source == null) return {};
72
- var target = {};
73
- var sourceKeys = Object.keys(source);
74
- var key, i;
75
-
76
- for (i = 0; i < sourceKeys.length; i++) {
77
- key = sourceKeys[i];
78
- if (excluded.indexOf(key) >= 0) continue;
79
- target[key] = source[key];
80
57
  }
81
58
 
82
59
  return target;
60
+ };
61
+ return _extends.apply(this, arguments);
62
+ }
63
+
64
+ function _objectWithoutPropertiesLoose(source, excluded) {
65
+ if (source == null) return {};
66
+ var target = {};
67
+ var sourceKeys = Object.keys(source);
68
+ var key, i;
69
+
70
+ for (i = 0; i < sourceKeys.length; i++) {
71
+ key = sourceKeys[i];
72
+ if (excluded.indexOf(key) >= 0) continue;
73
+ target[key] = source[key];
83
74
  }
84
75
 
85
- function _objectWithoutProperties(source, excluded) {
86
- if (source == null) return {};
87
-
88
- var target = _objectWithoutPropertiesLoose(source, excluded);
76
+ return target;
77
+ }
89
78
 
90
- var key, i;
79
+ function _objectWithoutProperties(source, excluded) {
80
+ if (source == null) return {};
91
81
 
92
- if (Object.getOwnPropertySymbols) {
93
- var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
82
+ var target = _objectWithoutPropertiesLoose(source, excluded);
94
83
 
95
- for (i = 0; i < sourceSymbolKeys.length; i++) {
96
- key = sourceSymbolKeys[i];
97
- if (excluded.indexOf(key) >= 0) continue;
98
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
99
- target[key] = source[key];
100
- }
101
- }
84
+ var key, i;
102
85
 
103
- return target;
104
- }
86
+ if (Object.getOwnPropertySymbols) {
87
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
105
88
 
106
- function _taggedTemplateLiteral(strings, raw) {
107
- if (!raw) {
108
- raw = strings.slice(0);
89
+ for (i = 0; i < sourceSymbolKeys.length; i++) {
90
+ key = sourceSymbolKeys[i];
91
+ if (excluded.indexOf(key) >= 0) continue;
92
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
93
+ target[key] = source[key];
109
94
  }
110
-
111
- return Object.freeze(Object.defineProperties(strings, {
112
- raw: {
113
- value: Object.freeze(raw)
114
- }
115
- }));
116
95
  }
117
96
 
118
- function _slicedToArray(arr, i) {
119
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
120
- }
97
+ return target;
98
+ }
121
99
 
122
- function _arrayWithHoles(arr) {
123
- if (Array.isArray(arr)) return arr;
100
+ function _taggedTemplateLiteral(strings, raw) {
101
+ if (!raw) {
102
+ raw = strings.slice(0);
124
103
  }
125
104
 
126
- function _iterableToArrayLimit(arr, i) {
127
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
128
-
129
- if (_i == null) return;
130
- var _arr = [];
131
- var _n = true;
132
- var _d = false;
133
-
134
- var _s, _e;
135
-
136
- try {
137
- for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
138
- _arr.push(_s.value);
139
-
140
- if (i && _arr.length === i) break;
141
- }
142
- } catch (err) {
143
- _d = true;
144
- _e = err;
145
- } finally {
146
- try {
147
- if (!_n && _i["return"] != null) _i["return"]();
148
- } finally {
149
- if (_d) throw _e;
150
- }
105
+ return Object.freeze(Object.defineProperties(strings, {
106
+ raw: {
107
+ value: Object.freeze(raw)
151
108
  }
109
+ }));
110
+ }
152
111
 
153
- return _arr;
154
- }
155
-
156
- function _unsupportedIterableToArray(o, minLen) {
157
- if (!o) return;
158
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
159
- var n = Object.prototype.toString.call(o).slice(8, -1);
160
- if (n === "Object" && o.constructor) n = o.constructor.name;
161
- if (n === "Map" || n === "Set") return Array.from(o);
162
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
163
- }
164
-
165
- function _arrayLikeToArray(arr, len) {
166
- if (len == null || len > arr.length) len = arr.length;
167
-
168
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
169
-
170
- return arr2;
171
- }
172
-
173
- function _nonIterableRest() {
174
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
175
- }
176
-
177
- var isCheckBoxInput = (element) => element.type === 'checkbox';
178
-
179
- var isDateObject = (value) => value instanceof Date;
180
-
181
- var isNullOrUndefined = (value) => value == null;
182
-
183
- const isObjectType = (value) => typeof value === 'object';
184
- var isObject = (value) => !isNullOrUndefined(value) &&
185
- !Array.isArray(value) &&
186
- isObjectType(value) &&
187
- !isDateObject(value);
188
-
189
- var getEventValue = (event) => isObject(event) && event.target
190
- ? isCheckBoxInput(event.target)
191
- ? event.target.checked
192
- : event.target.value
193
- : event;
194
-
195
- var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
196
-
197
- var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
198
-
199
- var isPlainObject = (tempObject) => {
200
- const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
201
- return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));
202
- };
203
-
204
- var isWeb = typeof window !== 'undefined' &&
205
- typeof window.HTMLElement !== 'undefined' &&
206
- typeof document !== 'undefined';
207
-
208
- function cloneObject(data) {
209
- let copy;
210
- const isArray = Array.isArray(data);
211
- if (data instanceof Date) {
212
- copy = new Date(data);
213
- }
214
- else if (data instanceof Set) {
215
- copy = new Set(data);
216
- }
217
- else if (!(isWeb && (data instanceof Blob || data instanceof FileList)) &&
218
- (isArray || isObject(data))) {
219
- copy = isArray ? [] : {};
220
- if (!isArray && !isPlainObject(data)) {
221
- copy = data;
222
- }
223
- else {
224
- for (const key in data) {
225
- if (data.hasOwnProperty(key)) {
226
- copy[key] = cloneObject(data[key]);
227
- }
228
- }
229
- }
230
- }
231
- else {
232
- return data;
233
- }
234
- return copy;
235
- }
236
-
237
- var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
238
-
239
- var isUndefined = (val) => val === undefined;
240
-
241
- var get = (obj, path, defaultValue) => {
242
- if (!path || !isObject(obj)) {
243
- return defaultValue;
244
- }
245
- const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], obj);
246
- return isUndefined(result) || result === obj
247
- ? isUndefined(obj[path])
248
- ? defaultValue
249
- : obj[path]
250
- : result;
251
- };
252
-
253
- const EVENTS = {
254
- BLUR: 'blur',
255
- FOCUS_OUT: 'focusout',
256
- CHANGE: 'change',
257
- };
258
- const VALIDATION_MODE = {
259
- onBlur: 'onBlur',
260
- onChange: 'onChange',
261
- onSubmit: 'onSubmit',
262
- onTouched: 'onTouched',
263
- all: 'all',
264
- };
265
- const INPUT_VALIDATION_RULES = {
266
- max: 'max',
267
- min: 'min',
268
- maxLength: 'maxLength',
269
- minLength: 'minLength',
270
- pattern: 'pattern',
271
- required: 'required',
272
- validate: 'validate',
273
- };
274
-
275
- const HookFormContext = React__default.createContext(null);
276
- /**
277
- * This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.
278
- *
279
- * @remarks
280
- * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
281
- *
282
- * @returns return all useForm methods
283
- *
284
- * @example
285
- * ```tsx
286
- * function App() {
287
- * const methods = useForm();
288
- * const onSubmit = data => console.log(data);
289
- *
290
- * return (
291
- * <FormProvider {...methods} >
292
- * <form onSubmit={methods.handleSubmit(onSubmit)}>
293
- * <NestedInput />
294
- * <input type="submit" />
295
- * </form>
296
- * </FormProvider>
297
- * );
298
- * }
299
- *
300
- * function NestedInput() {
301
- * const { register } = useFormContext(); // retrieve all hook methods
302
- * return <input {...register("test")} />;
303
- * }
304
- * ```
305
- */
306
- const useFormContext = () => React__default.useContext(HookFormContext);
307
-
308
- var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
309
- const result = {
310
- defaultValues: control._defaultValues,
311
- };
312
- for (const key in formState) {
313
- Object.defineProperty(result, key, {
314
- get: () => {
315
- const _key = key;
316
- if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
317
- control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
318
- }
319
- localProxyFormState && (localProxyFormState[_key] = true);
320
- return formState[_key];
321
- },
322
- });
323
- }
324
- return result;
325
- };
326
-
327
- var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
328
-
329
- var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
330
- updateFormState(formStateData);
331
- const { name, ...formState } = formStateData;
332
- return (isEmptyObject(formState) ||
333
- Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
334
- Object.keys(formState).find((key) => _proxyFormState[key] ===
335
- (!isRoot || VALIDATION_MODE.all)));
336
- };
337
-
338
- var convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]);
339
-
340
- var shouldSubscribeByName = (name, signalName, exact) => exact && signalName
341
- ? name === signalName ||
342
- (Array.isArray(name) &&
343
- name.some((currentName) => currentName && exact && currentName === signalName))
344
- : !name ||
345
- !signalName ||
346
- name === signalName ||
347
- convertToArrayPayload(name).some((currentName) => currentName &&
348
- (currentName.startsWith(signalName) ||
349
- signalName.startsWith(currentName)));
350
-
351
- function useSubscribe(props) {
352
- const _props = React__default.useRef(props);
353
- _props.current = props;
354
- React__default.useEffect(() => {
355
- const subscription = !props.disabled &&
356
- _props.current.subject &&
357
- _props.current.subject.subscribe({
358
- next: _props.current.next,
359
- });
360
- return () => {
361
- subscription && subscription.unsubscribe();
362
- };
363
- }, [props.disabled]);
364
- }
112
+ function _slicedToArray(arr, i) {
113
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
114
+ }
365
115
 
366
- /**
367
- * This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.
368
- *
369
- * @remarks
370
- * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
371
- *
372
- * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
373
- *
374
- * @example
375
- * ```tsx
376
- * function App() {
377
- * const { register, handleSubmit, control } = useForm({
378
- * defaultValues: {
379
- * firstName: "firstName"
380
- * }});
381
- * const { dirtyFields } = useFormState({
382
- * control
383
- * });
384
- * const onSubmit = (data) => console.log(data);
385
- *
386
- * return (
387
- * <form onSubmit={handleSubmit(onSubmit)}>
388
- * <input {...register("firstName")} placeholder="First Name" />
389
- * {dirtyFields.firstName && <p>Field is dirty.</p>}
390
- * <input type="submit" />
391
- * </form>
392
- * );
393
- * }
394
- * ```
395
- */
396
- function useFormState(props) {
397
- const methods = useFormContext();
398
- const { control = methods.control, disabled, name, exact } = props || {};
399
- const [formState, updateFormState] = React__default.useState(control._formState);
400
- const _mounted = React__default.useRef(true);
401
- const _localProxyFormState = React__default.useRef({
402
- isDirty: false,
403
- isLoading: false,
404
- dirtyFields: false,
405
- touchedFields: false,
406
- isValidating: false,
407
- isValid: false,
408
- errors: false,
409
- });
410
- const _name = React__default.useRef(name);
411
- _name.current = name;
412
- useSubscribe({
413
- disabled,
414
- next: (value) => _mounted.current &&
415
- shouldSubscribeByName(_name.current, value.name, exact) &&
416
- shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) &&
417
- updateFormState({
418
- ...control._formState,
419
- ...value,
420
- }),
421
- subject: control._subjects.state,
422
- });
423
- React__default.useEffect(() => {
424
- _mounted.current = true;
425
- _localProxyFormState.current.isValid && control._updateValid(true);
426
- return () => {
427
- _mounted.current = false;
428
- };
429
- }, [control]);
430
- return getProxyFormState(formState, control, _localProxyFormState.current, false);
431
- }
116
+ function _arrayWithHoles(arr) {
117
+ if (Array.isArray(arr)) return arr;
118
+ }
432
119
 
433
- var isString = (value) => typeof value === 'string';
120
+ function _iterableToArrayLimit(arr, i) {
121
+ var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
434
122
 
435
- var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
436
- if (isString(names)) {
437
- isGlobal && _names.watch.add(names);
438
- return get(formValues, names, defaultValue);
439
- }
440
- if (Array.isArray(names)) {
441
- return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
442
- }
443
- isGlobal && (_names.watchAll = true);
444
- return formValues;
445
- };
123
+ if (_i == null) return;
124
+ var _arr = [];
125
+ var _n = true;
126
+ var _d = false;
446
127
 
447
- /**
448
- * Custom hook to subscribe to field change and isolate re-rendering at the component level.
449
- *
450
- * @remarks
451
- *
452
- * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
453
- *
454
- * @example
455
- * ```tsx
456
- * const { watch } = useForm();
457
- * const values = useWatch({
458
- * name: "fieldName"
459
- * control,
460
- * })
461
- * ```
462
- */
463
- function useWatch(props) {
464
- const methods = useFormContext();
465
- const { control = methods.control, name, defaultValue, disabled, exact, } = props || {};
466
- const _name = React__default.useRef(name);
467
- _name.current = name;
468
- useSubscribe({
469
- disabled,
470
- subject: control._subjects.values,
471
- next: (formState) => {
472
- if (shouldSubscribeByName(_name.current, formState.name, exact)) {
473
- updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
474
- }
475
- },
476
- });
477
- const [value, updateValue] = React__default.useState(control._getWatch(name, defaultValue));
478
- React__default.useEffect(() => control._removeUnmounted());
479
- return value;
480
- }
128
+ var _s, _e;
481
129
 
482
- var isKey = (value) => /^\w*$/.test(value);
483
-
484
- var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
485
-
486
- function set(object, path, value) {
487
- let index = -1;
488
- const tempPath = isKey(path) ? [path] : stringToPath(path);
489
- const length = tempPath.length;
490
- const lastIndex = length - 1;
491
- while (++index < length) {
492
- const key = tempPath[index];
493
- let newValue = value;
494
- if (index !== lastIndex) {
495
- const objValue = object[key];
496
- newValue =
497
- isObject(objValue) || Array.isArray(objValue)
498
- ? objValue
499
- : !isNaN(+tempPath[index + 1])
500
- ? []
501
- : {};
502
- }
503
- object[key] = newValue;
504
- object = object[key];
505
- }
506
- return object;
507
- }
130
+ try {
131
+ for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
132
+ _arr.push(_s.value);
508
133
 
509
- /**
510
- * Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.
511
- *
512
- * @remarks
513
- * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
514
- *
515
- * @param props - the path name to the form field value, and validation rules.
516
- *
517
- * @returns field properties, field and form state. {@link UseControllerReturn}
518
- *
519
- * @example
520
- * ```tsx
521
- * function Input(props) {
522
- * const { field, fieldState, formState } = useController(props);
523
- * return (
524
- * <div>
525
- * <input {...field} placeholder={props.name} />
526
- * <p>{fieldState.isTouched && "Touched"}</p>
527
- * <p>{formState.isSubmitted ? "submitted" : ""}</p>
528
- * </div>
529
- * );
530
- * }
531
- * ```
532
- */
533
- function useController(props) {
534
- const methods = useFormContext();
535
- const { name, disabled, control = methods.control, shouldUnregister } = props;
536
- const isArrayField = isNameInFieldArray(control._names.array, name);
537
- const value = useWatch({
538
- control,
539
- name,
540
- defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
541
- exact: true,
542
- });
543
- const formState = useFormState({
544
- control,
545
- name,
546
- });
547
- const _registerProps = React__default.useRef(control.register(name, {
548
- ...props.rules,
549
- value,
550
- }));
551
- _registerProps.current = control.register(name, props.rules);
552
- React__default.useEffect(() => {
553
- const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
554
- const updateMounted = (name, value) => {
555
- const field = get(control._fields, name);
556
- if (field) {
557
- field._f.mount = value;
558
- }
559
- };
560
- updateMounted(name, true);
561
- if (_shouldUnregisterField) {
562
- const value = cloneObject(get(control._options.defaultValues, name));
563
- set(control._defaultValues, name, value);
564
- if (isUndefined(get(control._formValues, name))) {
565
- set(control._formValues, name, value);
566
- }
567
- }
568
- return () => {
569
- (isArrayField
570
- ? _shouldUnregisterField && !control._state.action
571
- : _shouldUnregisterField)
572
- ? control.unregister(name)
573
- : updateMounted(name, false);
574
- };
575
- }, [name, control, isArrayField, shouldUnregister]);
576
- React__default.useEffect(() => {
577
- control._updateDisabledField({
578
- disabled,
579
- fields: control._fields,
580
- name,
581
- });
582
- }, [disabled, name, control]);
583
- return {
584
- field: {
585
- name,
586
- value,
587
- disabled,
588
- onChange: React__default.useCallback((event) => _registerProps.current.onChange({
589
- target: {
590
- value: getEventValue(event),
591
- name: name,
592
- },
593
- type: EVENTS.CHANGE,
594
- }), [name]),
595
- onBlur: React__default.useCallback(() => _registerProps.current.onBlur({
596
- target: {
597
- value: get(control._formValues, name),
598
- name: name,
599
- },
600
- type: EVENTS.BLUR,
601
- }), [name, control]),
602
- ref: (elm) => {
603
- const field = get(control._fields, name);
604
- if (field && elm) {
605
- field._f.ref = {
606
- focus: () => elm.focus(),
607
- select: () => elm.select(),
608
- setCustomValidity: (message) => elm.setCustomValidity(message),
609
- reportValidity: () => elm.reportValidity(),
610
- };
611
- }
612
- },
613
- },
614
- formState,
615
- fieldState: Object.defineProperties({}, {
616
- invalid: {
617
- enumerable: true,
618
- get: () => !!get(formState.errors, name),
619
- },
620
- isDirty: {
621
- enumerable: true,
622
- get: () => !!get(formState.dirtyFields, name),
623
- },
624
- isTouched: {
625
- enumerable: true,
626
- get: () => !!get(formState.touchedFields, name),
627
- },
628
- error: {
629
- enumerable: true,
630
- get: () => get(formState.errors, name),
631
- },
632
- }),
633
- };
134
+ if (i && _arr.length === i) break;
135
+ }
136
+ } catch (err) {
137
+ _d = true;
138
+ _e = err;
139
+ } finally {
140
+ try {
141
+ if (!_n && _i["return"] != null) _i["return"]();
142
+ } finally {
143
+ if (_d) throw _e;
144
+ }
634
145
  }
635
146
 
636
- var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria
637
- ? {
638
- ...errors[name],
639
- types: {
640
- ...(errors[name] && errors[name].types ? errors[name].types : {}),
641
- [type]: message || true,
642
- },
643
- }
644
- : {};
645
-
646
- const focusFieldBy = (fields, callback, fieldsNames) => {
647
- for (const key of fieldsNames || Object.keys(fields)) {
648
- const field = get(fields, key);
649
- if (field) {
650
- const { _f, ...currentField } = field;
651
- if (_f && callback(_f.name)) {
652
- if (_f.ref.focus) {
653
- _f.ref.focus();
654
- break;
655
- }
656
- else if (_f.refs && _f.refs[0].focus) {
657
- _f.refs[0].focus();
658
- break;
659
- }
660
- }
661
- else if (isObject(currentField)) {
662
- focusFieldBy(currentField, callback);
663
- }
664
- }
665
- }
666
- };
667
-
668
- var getValidationModes = (mode) => ({
669
- isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
670
- isOnBlur: mode === VALIDATION_MODE.onBlur,
671
- isOnChange: mode === VALIDATION_MODE.onChange,
672
- isOnAll: mode === VALIDATION_MODE.all,
673
- isOnTouch: mode === VALIDATION_MODE.onTouched,
674
- });
675
-
676
- var isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&
677
- (_names.watchAll ||
678
- _names.watch.has(name) ||
679
- [..._names.watch].some((watchName) => name.startsWith(watchName) &&
680
- /^\.\w+/.test(name.slice(watchName.length))));
681
-
682
- var updateFieldArrayRootError = (errors, error, name) => {
683
- const fieldArrayErrors = compact(get(errors, name));
684
- set(fieldArrayErrors, 'root', error[name]);
685
- set(errors, name, fieldArrayErrors);
686
- return errors;
687
- };
688
-
689
- var isBoolean = (value) => typeof value === 'boolean';
690
-
691
- var isFileInput = (element) => element.type === 'file';
692
-
693
- var isFunction = (value) => typeof value === 'function';
147
+ return _arr;
148
+ }
694
149
 
695
- var isHTMLElement = (value) => {
696
- if (!isWeb) {
697
- return false;
698
- }
699
- const owner = value ? value.ownerDocument : 0;
700
- return (value instanceof
701
- (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));
702
- };
703
-
704
- var isMessage = (value) => isString(value);
705
-
706
- var isRadioInput = (element) => element.type === 'radio';
707
-
708
- var isRegex = (value) => value instanceof RegExp;
709
-
710
- const defaultResult = {
711
- value: false,
712
- isValid: false,
713
- };
714
- const validResult = { value: true, isValid: true };
715
- var getCheckboxValue = (options) => {
716
- if (Array.isArray(options)) {
717
- if (options.length > 1) {
718
- const values = options
719
- .filter((option) => option && option.checked && !option.disabled)
720
- .map((option) => option.value);
721
- return { value: values, isValid: !!values.length };
722
- }
723
- return options[0].checked && !options[0].disabled
724
- ? // @ts-expect-error expected to work in the browser
725
- options[0].attributes && !isUndefined(options[0].attributes.value)
726
- ? isUndefined(options[0].value) || options[0].value === ''
727
- ? validResult
728
- : { value: options[0].value, isValid: true }
729
- : validResult
730
- : defaultResult;
731
- }
732
- return defaultResult;
733
- };
734
-
735
- const defaultReturn = {
736
- isValid: false,
737
- value: null,
738
- };
739
- var getRadioValue = (options) => Array.isArray(options)
740
- ? options.reduce((previous, option) => option && option.checked && !option.disabled
741
- ? {
742
- isValid: true,
743
- value: option.value,
744
- }
745
- : previous, defaultReturn)
746
- : defaultReturn;
747
-
748
- function getValidateError(result, ref, type = 'validate') {
749
- if (isMessage(result) ||
750
- (Array.isArray(result) && result.every(isMessage)) ||
751
- (isBoolean(result) && !result)) {
752
- return {
753
- type,
754
- message: isMessage(result) ? result : '',
755
- ref,
756
- };
757
- }
758
- }
150
+ function _unsupportedIterableToArray(o, minLen) {
151
+ if (!o) return;
152
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
153
+ var n = Object.prototype.toString.call(o).slice(8, -1);
154
+ if (n === "Object" && o.constructor) n = o.constructor.name;
155
+ if (n === "Map" || n === "Set") return Array.from(o);
156
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
157
+ }
759
158
 
760
- var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
761
- ? validationData
762
- : {
763
- value: validationData,
764
- message: '',
765
- };
766
-
767
- var validateField = async (field, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
768
- const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled, } = field._f;
769
- const inputValue = get(formValues, name);
770
- if (!mount || disabled) {
771
- return {};
772
- }
773
- const inputRef = refs ? refs[0] : ref;
774
- const setCustomValidity = (message) => {
775
- if (shouldUseNativeValidation && inputRef.reportValidity) {
776
- inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
777
- inputRef.reportValidity();
778
- }
779
- };
780
- const error = {};
781
- const isRadio = isRadioInput(ref);
782
- const isCheckBox = isCheckBoxInput(ref);
783
- const isRadioOrCheckbox = isRadio || isCheckBox;
784
- const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
785
- isUndefined(ref.value) &&
786
- isUndefined(inputValue)) ||
787
- (isHTMLElement(ref) && ref.value === '') ||
788
- inputValue === '' ||
789
- (Array.isArray(inputValue) && !inputValue.length);
790
- const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
791
- const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
792
- const message = exceedMax ? maxLengthMessage : minLengthMessage;
793
- error[name] = {
794
- type: exceedMax ? maxType : minType,
795
- message,
796
- ref,
797
- ...appendErrorsCurry(exceedMax ? maxType : minType, message),
798
- };
799
- };
800
- if (isFieldArray
801
- ? !Array.isArray(inputValue) || !inputValue.length
802
- : required &&
803
- ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
804
- (isBoolean(inputValue) && !inputValue) ||
805
- (isCheckBox && !getCheckboxValue(refs).isValid) ||
806
- (isRadio && !getRadioValue(refs).isValid))) {
807
- const { value, message } = isMessage(required)
808
- ? { value: !!required, message: required }
809
- : getValueAndMessage(required);
810
- if (value) {
811
- error[name] = {
812
- type: INPUT_VALIDATION_RULES.required,
813
- message,
814
- ref: inputRef,
815
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
816
- };
817
- if (!validateAllFieldCriteria) {
818
- setCustomValidity(message);
819
- return error;
820
- }
821
- }
822
- }
823
- if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
824
- let exceedMax;
825
- let exceedMin;
826
- const maxOutput = getValueAndMessage(max);
827
- const minOutput = getValueAndMessage(min);
828
- if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
829
- const valueNumber = ref.valueAsNumber ||
830
- (inputValue ? +inputValue : inputValue);
831
- if (!isNullOrUndefined(maxOutput.value)) {
832
- exceedMax = valueNumber > maxOutput.value;
833
- }
834
- if (!isNullOrUndefined(minOutput.value)) {
835
- exceedMin = valueNumber < minOutput.value;
836
- }
837
- }
838
- else {
839
- const valueDate = ref.valueAsDate || new Date(inputValue);
840
- const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
841
- const isTime = ref.type == 'time';
842
- const isWeek = ref.type == 'week';
843
- if (isString(maxOutput.value) && inputValue) {
844
- exceedMax = isTime
845
- ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
846
- : isWeek
847
- ? inputValue > maxOutput.value
848
- : valueDate > new Date(maxOutput.value);
849
- }
850
- if (isString(minOutput.value) && inputValue) {
851
- exceedMin = isTime
852
- ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
853
- : isWeek
854
- ? inputValue < minOutput.value
855
- : valueDate < new Date(minOutput.value);
856
- }
857
- }
858
- if (exceedMax || exceedMin) {
859
- getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
860
- if (!validateAllFieldCriteria) {
861
- setCustomValidity(error[name].message);
862
- return error;
863
- }
864
- }
865
- }
866
- if ((maxLength || minLength) &&
867
- !isEmpty &&
868
- (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
869
- const maxLengthOutput = getValueAndMessage(maxLength);
870
- const minLengthOutput = getValueAndMessage(minLength);
871
- const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
872
- inputValue.length > +maxLengthOutput.value;
873
- const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
874
- inputValue.length < +minLengthOutput.value;
875
- if (exceedMax || exceedMin) {
876
- getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
877
- if (!validateAllFieldCriteria) {
878
- setCustomValidity(error[name].message);
879
- return error;
880
- }
881
- }
882
- }
883
- if (pattern && !isEmpty && isString(inputValue)) {
884
- const { value: patternValue, message } = getValueAndMessage(pattern);
885
- if (isRegex(patternValue) && !inputValue.match(patternValue)) {
886
- error[name] = {
887
- type: INPUT_VALIDATION_RULES.pattern,
888
- message,
889
- ref,
890
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
891
- };
892
- if (!validateAllFieldCriteria) {
893
- setCustomValidity(message);
894
- return error;
895
- }
896
- }
897
- }
898
- if (validate) {
899
- if (isFunction(validate)) {
900
- const result = await validate(inputValue, formValues);
901
- const validateError = getValidateError(result, inputRef);
902
- if (validateError) {
903
- error[name] = {
904
- ...validateError,
905
- ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
906
- };
907
- if (!validateAllFieldCriteria) {
908
- setCustomValidity(validateError.message);
909
- return error;
910
- }
911
- }
912
- }
913
- else if (isObject(validate)) {
914
- let validationResult = {};
915
- for (const key in validate) {
916
- if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
917
- break;
918
- }
919
- const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
920
- if (validateError) {
921
- validationResult = {
922
- ...validateError,
923
- ...appendErrorsCurry(key, validateError.message),
924
- };
925
- setCustomValidity(validateError.message);
926
- if (validateAllFieldCriteria) {
927
- error[name] = validationResult;
928
- }
929
- }
930
- }
931
- if (!isEmptyObject(validationResult)) {
932
- error[name] = {
933
- ref: inputRef,
934
- ...validationResult,
935
- };
936
- if (!validateAllFieldCriteria) {
937
- return error;
938
- }
939
- }
940
- }
941
- }
942
- setCustomValidity(true);
943
- return error;
944
- };
159
+ function _arrayLikeToArray(arr, len) {
160
+ if (len == null || len > arr.length) len = arr.length;
945
161
 
946
- function baseGet(object, updatePath) {
947
- const length = updatePath.slice(0, -1).length;
948
- let index = 0;
949
- while (index < length) {
950
- object = isUndefined(object) ? index++ : object[updatePath[index++]];
951
- }
952
- return object;
953
- }
954
- function isEmptyArray(obj) {
955
- for (const key in obj) {
956
- if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
957
- return false;
958
- }
959
- }
960
- return true;
961
- }
962
- function unset(object, path) {
963
- const paths = Array.isArray(path)
964
- ? path
965
- : isKey(path)
966
- ? [path]
967
- : stringToPath(path);
968
- const childObject = paths.length === 1 ? object : baseGet(object, paths);
969
- const index = paths.length - 1;
970
- const key = paths[index];
971
- if (childObject) {
972
- delete childObject[key];
973
- }
974
- if (index !== 0 &&
975
- ((isObject(childObject) && isEmptyObject(childObject)) ||
976
- (Array.isArray(childObject) && isEmptyArray(childObject)))) {
977
- unset(object, paths.slice(0, -1));
978
- }
979
- return object;
980
- }
162
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
981
163
 
982
- function createSubject() {
983
- let _observers = [];
984
- const next = (value) => {
985
- for (const observer of _observers) {
986
- observer.next && observer.next(value);
987
- }
988
- };
989
- const subscribe = (observer) => {
990
- _observers.push(observer);
991
- return {
992
- unsubscribe: () => {
993
- _observers = _observers.filter((o) => o !== observer);
994
- },
995
- };
996
- };
997
- const unsubscribe = () => {
998
- _observers = [];
999
- };
1000
- return {
1001
- get observers() {
1002
- return _observers;
1003
- },
1004
- next,
1005
- subscribe,
1006
- unsubscribe,
1007
- };
1008
- }
164
+ return arr2;
165
+ }
1009
166
 
1010
- var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
167
+ function _nonIterableRest() {
168
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
169
+ }
1011
170
 
1012
- function deepEqual(object1, object2) {
1013
- if (isPrimitive(object1) || isPrimitive(object2)) {
1014
- return object1 === object2;
1015
- }
1016
- if (isDateObject(object1) && isDateObject(object2)) {
1017
- return object1.getTime() === object2.getTime();
1018
- }
1019
- const keys1 = Object.keys(object1);
1020
- const keys2 = Object.keys(object2);
1021
- if (keys1.length !== keys2.length) {
1022
- return false;
1023
- }
1024
- for (const key of keys1) {
1025
- const val1 = object1[key];
1026
- if (!keys2.includes(key)) {
1027
- return false;
1028
- }
1029
- if (key !== 'ref') {
1030
- const val2 = object2[key];
1031
- if ((isDateObject(val1) && isDateObject(val2)) ||
1032
- (isObject(val1) && isObject(val2)) ||
1033
- (Array.isArray(val1) && Array.isArray(val2))
1034
- ? !deepEqual(val1, val2)
1035
- : val1 !== val2) {
1036
- return false;
1037
- }
1038
- }
1039
- }
1040
- return true;
1041
- }
171
+ var isCheckBoxInput = (element) => element.type === 'checkbox';
1042
172
 
1043
- var isMultipleSelect = (element) => element.type === `select-multiple`;
173
+ var isDateObject = (value) => value instanceof Date;
1044
174
 
1045
- var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
175
+ var isNullOrUndefined = (value) => value == null;
1046
176
 
1047
- var live = (ref) => isHTMLElement(ref) && ref.isConnected;
177
+ const isObjectType = (value) => typeof value === 'object';
178
+ var isObject = (value) => !isNullOrUndefined(value) &&
179
+ !Array.isArray(value) &&
180
+ isObjectType(value) &&
181
+ !isDateObject(value);
1048
182
 
1049
- var objectHasFunction = (data) => {
1050
- for (const key in data) {
1051
- if (isFunction(data[key])) {
1052
- return true;
1053
- }
1054
- }
1055
- return false;
1056
- };
183
+ var getEventValue = (event) => isObject(event) && event.target
184
+ ? isCheckBoxInput(event.target)
185
+ ? event.target.checked
186
+ : event.target.value
187
+ : event;
1057
188
 
1058
- function markFieldsDirty(data, fields = {}) {
1059
- const isParentNodeArray = Array.isArray(data);
1060
- if (isObject(data) || isParentNodeArray) {
1061
- for (const key in data) {
1062
- if (Array.isArray(data[key]) ||
1063
- (isObject(data[key]) && !objectHasFunction(data[key]))) {
1064
- fields[key] = Array.isArray(data[key]) ? [] : {};
1065
- markFieldsDirty(data[key], fields[key]);
1066
- }
1067
- else if (!isNullOrUndefined(data[key])) {
1068
- fields[key] = true;
1069
- }
1070
- }
1071
- }
1072
- return fields;
1073
- }
1074
- function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
1075
- const isParentNodeArray = Array.isArray(data);
1076
- if (isObject(data) || isParentNodeArray) {
1077
- for (const key in data) {
1078
- if (Array.isArray(data[key]) ||
1079
- (isObject(data[key]) && !objectHasFunction(data[key]))) {
1080
- if (isUndefined(formValues) ||
1081
- isPrimitive(dirtyFieldsFromValues[key])) {
1082
- dirtyFieldsFromValues[key] = Array.isArray(data[key])
1083
- ? markFieldsDirty(data[key], [])
1084
- : { ...markFieldsDirty(data[key]) };
1085
- }
1086
- else {
1087
- getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
1088
- }
1089
- }
1090
- else {
1091
- dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
1092
- }
1093
- }
1094
- }
1095
- return dirtyFieldsFromValues;
1096
- }
1097
- var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));
1098
-
1099
- var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)
1100
- ? value
1101
- : valueAsNumber
1102
- ? value === ''
1103
- ? NaN
1104
- : value
1105
- ? +value
1106
- : value
1107
- : valueAsDate && isString(value)
1108
- ? new Date(value)
1109
- : setValueAs
1110
- ? setValueAs(value)
1111
- : value;
1112
-
1113
- function getFieldValue(_f) {
1114
- const ref = _f.ref;
1115
- if (_f.refs ? _f.refs.every((ref) => ref.disabled) : ref.disabled) {
1116
- return;
1117
- }
1118
- if (isFileInput(ref)) {
1119
- return ref.files;
1120
- }
1121
- if (isRadioInput(ref)) {
1122
- return getRadioValue(_f.refs).value;
1123
- }
1124
- if (isMultipleSelect(ref)) {
1125
- return [...ref.selectedOptions].map(({ value }) => value);
1126
- }
1127
- if (isCheckBoxInput(ref)) {
1128
- return getCheckboxValue(_f.refs).value;
1129
- }
1130
- return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
1131
- }
189
+ var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
1132
190
 
1133
- var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
1134
- const fields = {};
1135
- for (const name of fieldsNames) {
1136
- const field = get(_fields, name);
1137
- field && set(fields, name, field._f);
1138
- }
1139
- return {
1140
- criteriaMode,
1141
- names: [...fieldsNames],
1142
- fields,
1143
- shouldUseNativeValidation,
1144
- };
1145
- };
191
+ var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
1146
192
 
1147
- var getRuleValue = (rule) => isUndefined(rule)
1148
- ? rule
1149
- : isRegex(rule)
1150
- ? rule.source
1151
- : isObject(rule)
1152
- ? isRegex(rule.value)
1153
- ? rule.value.source
1154
- : rule.value
1155
- : rule;
1156
-
1157
- var hasValidation = (options) => options.mount &&
1158
- (options.required ||
1159
- options.min ||
1160
- options.max ||
1161
- options.maxLength ||
1162
- options.minLength ||
1163
- options.pattern ||
1164
- options.validate);
1165
-
1166
- function schemaErrorLookup(errors, _fields, name) {
1167
- const error = get(errors, name);
1168
- if (error || isKey(name)) {
1169
- return {
1170
- error,
1171
- name,
1172
- };
1173
- }
1174
- const names = name.split('.');
1175
- while (names.length) {
1176
- const fieldName = names.join('.');
1177
- const field = get(_fields, fieldName);
1178
- const foundError = get(errors, fieldName);
1179
- if (field && !Array.isArray(field) && name !== fieldName) {
1180
- return { name };
1181
- }
1182
- if (foundError && foundError.type) {
1183
- return {
1184
- name: fieldName,
1185
- error: foundError,
1186
- };
1187
- }
1188
- names.pop();
1189
- }
1190
- return {
1191
- name,
1192
- };
1193
- }
193
+ var isPlainObject = (tempObject) => {
194
+ const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
195
+ return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));
196
+ };
1194
197
 
1195
- var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
1196
- if (mode.isOnAll) {
1197
- return false;
1198
- }
1199
- else if (!isSubmitted && mode.isOnTouch) {
1200
- return !(isTouched || isBlurEvent);
1201
- }
1202
- else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
1203
- return !isBlurEvent;
1204
- }
1205
- else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
1206
- return isBlurEvent;
1207
- }
1208
- return true;
1209
- };
198
+ var isWeb = typeof window !== 'undefined' &&
199
+ typeof window.HTMLElement !== 'undefined' &&
200
+ typeof document !== 'undefined';
1210
201
 
1211
- var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
202
+ function cloneObject(data) {
203
+ let copy;
204
+ const isArray = Array.isArray(data);
205
+ if (data instanceof Date) {
206
+ copy = new Date(data);
207
+ }
208
+ else if (data instanceof Set) {
209
+ copy = new Set(data);
210
+ }
211
+ else if (!(isWeb && (data instanceof Blob || data instanceof FileList)) &&
212
+ (isArray || isObject(data))) {
213
+ copy = isArray ? [] : {};
214
+ if (!isArray && !isPlainObject(data)) {
215
+ copy = data;
216
+ }
217
+ else {
218
+ for (const key in data) {
219
+ if (data.hasOwnProperty(key)) {
220
+ copy[key] = cloneObject(data[key]);
221
+ }
222
+ }
223
+ }
224
+ }
225
+ else {
226
+ return data;
227
+ }
228
+ return copy;
229
+ }
1212
230
 
1213
- const defaultOptions = {
1214
- mode: VALIDATION_MODE.onSubmit,
1215
- reValidateMode: VALIDATION_MODE.onChange,
1216
- shouldFocusError: true,
1217
- };
1218
- function createFormControl(props = {}, flushRootRender) {
1219
- let _options = {
1220
- ...defaultOptions,
1221
- ...props,
1222
- };
1223
- let _formState = {
1224
- submitCount: 0,
1225
- isDirty: false,
1226
- isLoading: isFunction(_options.defaultValues),
1227
- isValidating: false,
1228
- isSubmitted: false,
1229
- isSubmitting: false,
1230
- isSubmitSuccessful: false,
1231
- isValid: false,
1232
- touchedFields: {},
1233
- dirtyFields: {},
1234
- errors: {},
1235
- };
1236
- let _fields = {};
1237
- let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
1238
- ? cloneObject(_options.defaultValues || _options.values) || {}
1239
- : {};
1240
- let _formValues = _options.shouldUnregister
1241
- ? {}
1242
- : cloneObject(_defaultValues);
1243
- let _state = {
1244
- action: false,
1245
- mount: false,
1246
- watch: false,
1247
- };
1248
- let _names = {
1249
- mount: new Set(),
1250
- unMount: new Set(),
1251
- array: new Set(),
1252
- watch: new Set(),
1253
- };
1254
- let delayErrorCallback;
1255
- let timer = 0;
1256
- const _proxyFormState = {
1257
- isDirty: false,
1258
- dirtyFields: false,
1259
- touchedFields: false,
1260
- isValidating: false,
1261
- isValid: false,
1262
- errors: false,
1263
- };
1264
- const _subjects = {
1265
- values: createSubject(),
1266
- array: createSubject(),
1267
- state: createSubject(),
1268
- };
1269
- const shouldCaptureDirtyFields = props.resetOptions && props.resetOptions.keepDirtyValues;
1270
- const validationModeBeforeSubmit = getValidationModes(_options.mode);
1271
- const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
1272
- const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
1273
- const debounce = (callback) => (wait) => {
1274
- clearTimeout(timer);
1275
- timer = setTimeout(callback, wait);
1276
- };
1277
- const _updateValid = async (shouldUpdateValid) => {
1278
- if (_proxyFormState.isValid || shouldUpdateValid) {
1279
- const isValid = _options.resolver
1280
- ? isEmptyObject((await _executeSchema()).errors)
1281
- : await executeBuiltInValidation(_fields, true);
1282
- if (isValid !== _formState.isValid) {
1283
- _subjects.state.next({
1284
- isValid,
1285
- });
1286
- }
1287
- }
1288
- };
1289
- const _updateIsValidating = (value) => _proxyFormState.isValidating &&
1290
- _subjects.state.next({
1291
- isValidating: value,
1292
- });
1293
- const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
1294
- if (args && method) {
1295
- _state.action = true;
1296
- if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
1297
- const fieldValues = method(get(_fields, name), args.argA, args.argB);
1298
- shouldSetValues && set(_fields, name, fieldValues);
1299
- }
1300
- if (shouldUpdateFieldsAndState &&
1301
- Array.isArray(get(_formState.errors, name))) {
1302
- const errors = method(get(_formState.errors, name), args.argA, args.argB);
1303
- shouldSetValues && set(_formState.errors, name, errors);
1304
- unsetEmptyArray(_formState.errors, name);
1305
- }
1306
- if (_proxyFormState.touchedFields &&
1307
- shouldUpdateFieldsAndState &&
1308
- Array.isArray(get(_formState.touchedFields, name))) {
1309
- const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
1310
- shouldSetValues && set(_formState.touchedFields, name, touchedFields);
1311
- }
1312
- if (_proxyFormState.dirtyFields) {
1313
- _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
1314
- }
1315
- _subjects.state.next({
1316
- name,
1317
- isDirty: _getDirty(name, values),
1318
- dirtyFields: _formState.dirtyFields,
1319
- errors: _formState.errors,
1320
- isValid: _formState.isValid,
1321
- });
1322
- }
1323
- else {
1324
- set(_formValues, name, values);
1325
- }
1326
- };
1327
- const updateErrors = (name, error) => {
1328
- set(_formState.errors, name, error);
1329
- _subjects.state.next({
1330
- errors: _formState.errors,
1331
- });
1332
- };
1333
- const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
1334
- const field = get(_fields, name);
1335
- if (field) {
1336
- const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
1337
- isUndefined(defaultValue) ||
1338
- (ref && ref.defaultChecked) ||
1339
- shouldSkipSetValueAs
1340
- ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))
1341
- : setFieldValue(name, defaultValue);
1342
- _state.mount && _updateValid();
1343
- }
1344
- };
1345
- const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
1346
- let shouldUpdateField = false;
1347
- let isPreviousDirty = false;
1348
- const output = {
1349
- name,
1350
- };
1351
- if (!isBlurEvent || shouldDirty) {
1352
- if (_proxyFormState.isDirty) {
1353
- isPreviousDirty = _formState.isDirty;
1354
- _formState.isDirty = output.isDirty = _getDirty();
1355
- shouldUpdateField = isPreviousDirty !== output.isDirty;
1356
- }
1357
- const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
1358
- isPreviousDirty = get(_formState.dirtyFields, name);
1359
- isCurrentFieldPristine
1360
- ? unset(_formState.dirtyFields, name)
1361
- : set(_formState.dirtyFields, name, true);
1362
- output.dirtyFields = _formState.dirtyFields;
1363
- shouldUpdateField =
1364
- shouldUpdateField ||
1365
- (_proxyFormState.dirtyFields &&
1366
- isPreviousDirty !== !isCurrentFieldPristine);
1367
- }
1368
- if (isBlurEvent) {
1369
- const isPreviousFieldTouched = get(_formState.touchedFields, name);
1370
- if (!isPreviousFieldTouched) {
1371
- set(_formState.touchedFields, name, isBlurEvent);
1372
- output.touchedFields = _formState.touchedFields;
1373
- shouldUpdateField =
1374
- shouldUpdateField ||
1375
- (_proxyFormState.touchedFields &&
1376
- isPreviousFieldTouched !== isBlurEvent);
1377
- }
1378
- }
1379
- shouldUpdateField && shouldRender && _subjects.state.next(output);
1380
- return shouldUpdateField ? output : {};
1381
- };
1382
- const shouldRenderByError = (name, isValid, error, fieldState) => {
1383
- const previousFieldError = get(_formState.errors, name);
1384
- const shouldUpdateValid = _proxyFormState.isValid &&
1385
- isBoolean(isValid) &&
1386
- _formState.isValid !== isValid;
1387
- if (props.delayError && error) {
1388
- delayErrorCallback = debounce(() => updateErrors(name, error));
1389
- delayErrorCallback(props.delayError);
1390
- }
1391
- else {
1392
- clearTimeout(timer);
1393
- delayErrorCallback = null;
1394
- error
1395
- ? set(_formState.errors, name, error)
1396
- : unset(_formState.errors, name);
1397
- }
1398
- if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||
1399
- !isEmptyObject(fieldState) ||
1400
- shouldUpdateValid) {
1401
- const updatedFormState = {
1402
- ...fieldState,
1403
- ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
1404
- errors: _formState.errors,
1405
- name,
1406
- };
1407
- _formState = {
1408
- ..._formState,
1409
- ...updatedFormState,
1410
- };
1411
- _subjects.state.next(updatedFormState);
1412
- }
1413
- _updateIsValidating(false);
1414
- };
1415
- const _executeSchema = async (name) => _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1416
- const executeSchemaAndUpdateState = async (names) => {
1417
- const { errors } = await _executeSchema(names);
1418
- if (names) {
1419
- for (const name of names) {
1420
- const error = get(errors, name);
1421
- error
1422
- ? set(_formState.errors, name, error)
1423
- : unset(_formState.errors, name);
1424
- }
1425
- }
1426
- else {
1427
- _formState.errors = errors;
1428
- }
1429
- return errors;
1430
- };
1431
- const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
1432
- valid: true,
1433
- }) => {
1434
- for (const name in fields) {
1435
- const field = fields[name];
1436
- if (field) {
1437
- const { _f, ...fieldValue } = field;
1438
- if (_f) {
1439
- const isFieldArrayRoot = _names.array.has(_f.name);
1440
- const fieldError = await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
1441
- if (fieldError[_f.name]) {
1442
- context.valid = false;
1443
- if (shouldOnlyCheckValid) {
1444
- break;
1445
- }
1446
- }
1447
- !shouldOnlyCheckValid &&
1448
- (get(fieldError, _f.name)
1449
- ? isFieldArrayRoot
1450
- ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)
1451
- : set(_formState.errors, _f.name, fieldError[_f.name])
1452
- : unset(_formState.errors, _f.name));
1453
- }
1454
- fieldValue &&
1455
- (await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context));
1456
- }
1457
- }
1458
- return context.valid;
1459
- };
1460
- const _removeUnmounted = () => {
1461
- for (const name of _names.unMount) {
1462
- const field = get(_fields, name);
1463
- field &&
1464
- (field._f.refs
1465
- ? field._f.refs.every((ref) => !live(ref))
1466
- : !live(field._f.ref)) &&
1467
- unregister(name);
1468
- }
1469
- _names.unMount = new Set();
1470
- };
1471
- const _getDirty = (name, data) => (name && data && set(_formValues, name, data),
1472
- !deepEqual(getValues(), _defaultValues));
1473
- const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
1474
- ...(_state.mount
1475
- ? _formValues
1476
- : isUndefined(defaultValue)
1477
- ? _defaultValues
1478
- : isString(names)
1479
- ? { [names]: defaultValue }
1480
- : defaultValue),
1481
- }, isGlobal, defaultValue);
1482
- const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
1483
- const setFieldValue = (name, value, options = {}) => {
1484
- const field = get(_fields, name);
1485
- let fieldValue = value;
1486
- if (field) {
1487
- const fieldReference = field._f;
1488
- if (fieldReference) {
1489
- !fieldReference.disabled &&
1490
- set(_formValues, name, getFieldValueAs(value, fieldReference));
1491
- fieldValue =
1492
- isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)
1493
- ? ''
1494
- : value;
1495
- if (isMultipleSelect(fieldReference.ref)) {
1496
- [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));
1497
- }
1498
- else if (fieldReference.refs) {
1499
- if (isCheckBoxInput(fieldReference.ref)) {
1500
- fieldReference.refs.length > 1
1501
- ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) &&
1502
- (checkboxRef.checked = Array.isArray(fieldValue)
1503
- ? !!fieldValue.find((data) => data === checkboxRef.value)
1504
- : fieldValue === checkboxRef.value))
1505
- : fieldReference.refs[0] &&
1506
- (fieldReference.refs[0].checked = !!fieldValue);
1507
- }
1508
- else {
1509
- fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));
1510
- }
1511
- }
1512
- else if (isFileInput(fieldReference.ref)) {
1513
- fieldReference.ref.value = '';
1514
- }
1515
- else {
1516
- fieldReference.ref.value = fieldValue;
1517
- if (!fieldReference.ref.type) {
1518
- _subjects.values.next({
1519
- name,
1520
- values: { ..._formValues },
1521
- });
1522
- }
1523
- }
1524
- }
1525
- }
1526
- (options.shouldDirty || options.shouldTouch) &&
1527
- updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
1528
- options.shouldValidate && trigger(name);
1529
- };
1530
- const setValues = (name, value, options) => {
1531
- for (const fieldKey in value) {
1532
- const fieldValue = value[fieldKey];
1533
- const fieldName = `${name}.${fieldKey}`;
1534
- const field = get(_fields, fieldName);
1535
- (_names.array.has(name) ||
1536
- !isPrimitive(fieldValue) ||
1537
- (field && !field._f)) &&
1538
- !isDateObject(fieldValue)
1539
- ? setValues(fieldName, fieldValue, options)
1540
- : setFieldValue(fieldName, fieldValue, options);
1541
- }
1542
- };
1543
- const setValue = (name, value, options = {}) => {
1544
- const field = get(_fields, name);
1545
- const isFieldArray = _names.array.has(name);
1546
- const cloneValue = cloneObject(value);
1547
- set(_formValues, name, cloneValue);
1548
- if (isFieldArray) {
1549
- _subjects.array.next({
1550
- name,
1551
- values: { ..._formValues },
1552
- });
1553
- if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) &&
1554
- options.shouldDirty) {
1555
- _subjects.state.next({
1556
- name,
1557
- dirtyFields: getDirtyFields(_defaultValues, _formValues),
1558
- isDirty: _getDirty(name, cloneValue),
1559
- });
1560
- }
1561
- }
1562
- else {
1563
- field && !field._f && !isNullOrUndefined(cloneValue)
1564
- ? setValues(name, cloneValue, options)
1565
- : setFieldValue(name, cloneValue, options);
1566
- }
1567
- isWatched(name, _names) && _subjects.state.next({ ..._formState });
1568
- _subjects.values.next({
1569
- name,
1570
- values: { ..._formValues },
1571
- });
1572
- !_state.mount && flushRootRender();
1573
- };
1574
- const onChange = async (event) => {
1575
- const target = event.target;
1576
- let name = target.name;
1577
- let isFieldValueUpdated = true;
1578
- const field = get(_fields, name);
1579
- const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
1580
- if (field) {
1581
- let error;
1582
- let isValid;
1583
- const fieldValue = getCurrentFieldValue();
1584
- const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
1585
- const shouldSkipValidation = (!hasValidation(field._f) &&
1586
- !_options.resolver &&
1587
- !get(_formState.errors, name) &&
1588
- !field._f.deps) ||
1589
- skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
1590
- const watched = isWatched(name, _names, isBlurEvent);
1591
- set(_formValues, name, fieldValue);
1592
- if (isBlurEvent) {
1593
- field._f.onBlur && field._f.onBlur(event);
1594
- delayErrorCallback && delayErrorCallback(0);
1595
- }
1596
- else if (field._f.onChange) {
1597
- field._f.onChange(event);
1598
- }
1599
- const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
1600
- const shouldRender = !isEmptyObject(fieldState) || watched;
1601
- !isBlurEvent &&
1602
- _subjects.values.next({
1603
- name,
1604
- type: event.type,
1605
- values: { ..._formValues },
1606
- });
1607
- if (shouldSkipValidation) {
1608
- _proxyFormState.isValid && _updateValid();
1609
- return (shouldRender &&
1610
- _subjects.state.next({ name, ...(watched ? {} : fieldState) }));
1611
- }
1612
- !isBlurEvent && watched && _subjects.state.next({ ..._formState });
1613
- _updateIsValidating(true);
1614
- if (_options.resolver) {
1615
- const { errors } = await _executeSchema([name]);
1616
- const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
1617
- const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
1618
- error = errorLookupResult.error;
1619
- name = errorLookupResult.name;
1620
- isValid = isEmptyObject(errors);
1621
- }
1622
- else {
1623
- error = (await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
1624
- isFieldValueUpdated =
1625
- isNaN(fieldValue) ||
1626
- fieldValue === get(_formValues, name, fieldValue);
1627
- if (isFieldValueUpdated) {
1628
- if (error) {
1629
- isValid = false;
1630
- }
1631
- else if (_proxyFormState.isValid) {
1632
- isValid = await executeBuiltInValidation(_fields, true);
1633
- }
1634
- }
1635
- }
1636
- if (isFieldValueUpdated) {
1637
- field._f.deps &&
1638
- trigger(field._f.deps);
1639
- shouldRenderByError(name, isValid, error, fieldState);
1640
- }
1641
- }
1642
- };
1643
- const trigger = async (name, options = {}) => {
1644
- let isValid;
1645
- let validationResult;
1646
- const fieldNames = convertToArrayPayload(name);
1647
- _updateIsValidating(true);
1648
- if (_options.resolver) {
1649
- const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
1650
- isValid = isEmptyObject(errors);
1651
- validationResult = name
1652
- ? !fieldNames.some((name) => get(errors, name))
1653
- : isValid;
1654
- }
1655
- else if (name) {
1656
- validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
1657
- const field = get(_fields, fieldName);
1658
- return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
1659
- }))).every(Boolean);
1660
- !(!validationResult && !_formState.isValid) && _updateValid();
1661
- }
1662
- else {
1663
- validationResult = isValid = await executeBuiltInValidation(_fields);
1664
- }
1665
- _subjects.state.next({
1666
- ...(!isString(name) ||
1667
- (_proxyFormState.isValid && isValid !== _formState.isValid)
1668
- ? {}
1669
- : { name }),
1670
- ...(_options.resolver || !name ? { isValid } : {}),
1671
- errors: _formState.errors,
1672
- isValidating: false,
1673
- });
1674
- options.shouldFocus &&
1675
- !validationResult &&
1676
- focusFieldBy(_fields, (key) => key && get(_formState.errors, key), name ? fieldNames : _names.mount);
1677
- return validationResult;
1678
- };
1679
- const getValues = (fieldNames) => {
1680
- const values = {
1681
- ..._defaultValues,
1682
- ...(_state.mount ? _formValues : {}),
1683
- };
1684
- return isUndefined(fieldNames)
1685
- ? values
1686
- : isString(fieldNames)
1687
- ? get(values, fieldNames)
1688
- : fieldNames.map((name) => get(values, name));
1689
- };
1690
- const getFieldState = (name, formState) => ({
1691
- invalid: !!get((formState || _formState).errors, name),
1692
- isDirty: !!get((formState || _formState).dirtyFields, name),
1693
- isTouched: !!get((formState || _formState).touchedFields, name),
1694
- error: get((formState || _formState).errors, name),
1695
- });
1696
- const clearErrors = (name) => {
1697
- name &&
1698
- convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
1699
- _subjects.state.next({
1700
- errors: name ? _formState.errors : {},
1701
- });
1702
- };
1703
- const setError = (name, error, options) => {
1704
- const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
1705
- set(_formState.errors, name, {
1706
- ...error,
1707
- ref,
1708
- });
1709
- _subjects.state.next({
1710
- name,
1711
- errors: _formState.errors,
1712
- isValid: false,
1713
- });
1714
- options && options.shouldFocus && ref && ref.focus && ref.focus();
1715
- };
1716
- const watch = (name, defaultValue) => isFunction(name)
1717
- ? _subjects.values.subscribe({
1718
- next: (payload) => name(_getWatch(undefined, defaultValue), payload),
1719
- })
1720
- : _getWatch(name, defaultValue, true);
1721
- const unregister = (name, options = {}) => {
1722
- for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
1723
- _names.mount.delete(fieldName);
1724
- _names.array.delete(fieldName);
1725
- if (!options.keepValue) {
1726
- unset(_fields, fieldName);
1727
- unset(_formValues, fieldName);
1728
- }
1729
- !options.keepError && unset(_formState.errors, fieldName);
1730
- !options.keepDirty && unset(_formState.dirtyFields, fieldName);
1731
- !options.keepTouched && unset(_formState.touchedFields, fieldName);
1732
- !_options.shouldUnregister &&
1733
- !options.keepDefaultValue &&
1734
- unset(_defaultValues, fieldName);
1735
- }
1736
- _subjects.values.next({
1737
- values: { ..._formValues },
1738
- });
1739
- _subjects.state.next({
1740
- ..._formState,
1741
- ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),
1742
- });
1743
- !options.keepIsValid && _updateValid();
1744
- };
1745
- const _updateDisabledField = ({ disabled, name, field, fields, }) => {
1746
- if (isBoolean(disabled)) {
1747
- const value = disabled
1748
- ? undefined
1749
- : get(_formValues, name, getFieldValue(field ? field._f : get(fields, name)._f));
1750
- set(_formValues, name, value);
1751
- updateTouchAndDirty(name, value, false, false, true);
1752
- }
1753
- };
1754
- const register = (name, options = {}) => {
1755
- let field = get(_fields, name);
1756
- const disabledIsDefined = isBoolean(options.disabled);
1757
- set(_fields, name, {
1758
- ...(field || {}),
1759
- _f: {
1760
- ...(field && field._f ? field._f : { ref: { name } }),
1761
- name,
1762
- mount: true,
1763
- ...options,
1764
- },
1765
- });
1766
- _names.mount.add(name);
1767
- if (field) {
1768
- _updateDisabledField({
1769
- field,
1770
- disabled: options.disabled,
1771
- name,
1772
- });
1773
- }
1774
- else {
1775
- updateValidAndValue(name, true, options.value);
1776
- }
1777
- return {
1778
- ...(disabledIsDefined ? { disabled: options.disabled } : {}),
1779
- ...(_options.progressive
1780
- ? {
1781
- required: !!options.required,
1782
- min: getRuleValue(options.min),
1783
- max: getRuleValue(options.max),
1784
- minLength: getRuleValue(options.minLength),
1785
- maxLength: getRuleValue(options.maxLength),
1786
- pattern: getRuleValue(options.pattern),
1787
- }
1788
- : {}),
1789
- name,
1790
- onChange,
1791
- onBlur: onChange,
1792
- ref: (ref) => {
1793
- if (ref) {
1794
- register(name, options);
1795
- field = get(_fields, name);
1796
- const fieldRef = isUndefined(ref.value)
1797
- ? ref.querySelectorAll
1798
- ? ref.querySelectorAll('input,select,textarea')[0] || ref
1799
- : ref
1800
- : ref;
1801
- const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
1802
- const refs = field._f.refs || [];
1803
- if (radioOrCheckbox
1804
- ? refs.find((option) => option === fieldRef)
1805
- : fieldRef === field._f.ref) {
1806
- return;
1807
- }
1808
- set(_fields, name, {
1809
- _f: {
1810
- ...field._f,
1811
- ...(radioOrCheckbox
1812
- ? {
1813
- refs: [
1814
- ...refs.filter(live),
1815
- fieldRef,
1816
- ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
1817
- ],
1818
- ref: { type: fieldRef.type, name },
1819
- }
1820
- : { ref: fieldRef }),
1821
- },
1822
- });
1823
- updateValidAndValue(name, false, undefined, fieldRef);
1824
- }
1825
- else {
1826
- field = get(_fields, name, {});
1827
- if (field._f) {
1828
- field._f.mount = false;
1829
- }
1830
- (_options.shouldUnregister || options.shouldUnregister) &&
1831
- !(isNameInFieldArray(_names.array, name) && _state.action) &&
1832
- _names.unMount.add(name);
1833
- }
1834
- },
1835
- };
1836
- };
1837
- const _focusError = () => _options.shouldFocusError &&
1838
- focusFieldBy(_fields, (key) => key && get(_formState.errors, key), _names.mount);
1839
- const handleSubmit = (onValid, onInvalid) => async (e) => {
1840
- if (e) {
1841
- e.preventDefault && e.preventDefault();
1842
- e.persist && e.persist();
1843
- }
1844
- let fieldValues = cloneObject(_formValues);
1845
- _subjects.state.next({
1846
- isSubmitting: true,
1847
- });
1848
- if (_options.resolver) {
1849
- const { errors, values } = await _executeSchema();
1850
- _formState.errors = errors;
1851
- fieldValues = values;
1852
- }
1853
- else {
1854
- await executeBuiltInValidation(_fields);
1855
- }
1856
- unset(_formState.errors, 'root');
1857
- if (isEmptyObject(_formState.errors)) {
1858
- _subjects.state.next({
1859
- errors: {},
1860
- });
1861
- await onValid(fieldValues, e);
1862
- }
1863
- else {
1864
- if (onInvalid) {
1865
- await onInvalid({ ..._formState.errors }, e);
1866
- }
1867
- _focusError();
1868
- setTimeout(_focusError);
1869
- }
1870
- _subjects.state.next({
1871
- isSubmitted: true,
1872
- isSubmitting: false,
1873
- isSubmitSuccessful: isEmptyObject(_formState.errors),
1874
- submitCount: _formState.submitCount + 1,
1875
- errors: _formState.errors,
1876
- });
1877
- };
1878
- const resetField = (name, options = {}) => {
1879
- if (get(_fields, name)) {
1880
- if (isUndefined(options.defaultValue)) {
1881
- setValue(name, get(_defaultValues, name));
1882
- }
1883
- else {
1884
- setValue(name, options.defaultValue);
1885
- set(_defaultValues, name, options.defaultValue);
1886
- }
1887
- if (!options.keepTouched) {
1888
- unset(_formState.touchedFields, name);
1889
- }
1890
- if (!options.keepDirty) {
1891
- unset(_formState.dirtyFields, name);
1892
- _formState.isDirty = options.defaultValue
1893
- ? _getDirty(name, get(_defaultValues, name))
1894
- : _getDirty();
1895
- }
1896
- if (!options.keepError) {
1897
- unset(_formState.errors, name);
1898
- _proxyFormState.isValid && _updateValid();
1899
- }
1900
- _subjects.state.next({ ..._formState });
1901
- }
1902
- };
1903
- const _reset = (formValues, keepStateOptions = {}) => {
1904
- const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
1905
- const cloneUpdatedValues = cloneObject(updatedValues);
1906
- const values = formValues && !isEmptyObject(formValues)
1907
- ? cloneUpdatedValues
1908
- : _defaultValues;
1909
- if (!keepStateOptions.keepDefaultValues) {
1910
- _defaultValues = updatedValues;
1911
- }
1912
- if (!keepStateOptions.keepValues) {
1913
- if (keepStateOptions.keepDirtyValues || shouldCaptureDirtyFields) {
1914
- for (const fieldName of _names.mount) {
1915
- get(_formState.dirtyFields, fieldName)
1916
- ? set(values, fieldName, get(_formValues, fieldName))
1917
- : setValue(fieldName, get(values, fieldName));
1918
- }
1919
- }
1920
- else {
1921
- if (isWeb && isUndefined(formValues)) {
1922
- for (const name of _names.mount) {
1923
- const field = get(_fields, name);
1924
- if (field && field._f) {
1925
- const fieldReference = Array.isArray(field._f.refs)
1926
- ? field._f.refs[0]
1927
- : field._f.ref;
1928
- if (isHTMLElement(fieldReference)) {
1929
- const form = fieldReference.closest('form');
1930
- if (form) {
1931
- form.reset();
1932
- break;
1933
- }
1934
- }
1935
- }
1936
- }
1937
- }
1938
- _fields = {};
1939
- }
1940
- _formValues = props.shouldUnregister
1941
- ? keepStateOptions.keepDefaultValues
1942
- ? cloneObject(_defaultValues)
1943
- : {}
1944
- : cloneObject(values);
1945
- _subjects.array.next({
1946
- values: { ...values },
1947
- });
1948
- _subjects.values.next({
1949
- values: { ...values },
1950
- });
1951
- }
1952
- _names = {
1953
- mount: new Set(),
1954
- unMount: new Set(),
1955
- array: new Set(),
1956
- watch: new Set(),
1957
- watchAll: false,
1958
- focus: '',
1959
- };
1960
- !_state.mount && flushRootRender();
1961
- _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid;
1962
- _state.watch = !!props.shouldUnregister;
1963
- _subjects.state.next({
1964
- submitCount: keepStateOptions.keepSubmitCount
1965
- ? _formState.submitCount
1966
- : 0,
1967
- isDirty: keepStateOptions.keepDirty
1968
- ? _formState.isDirty
1969
- : !!(keepStateOptions.keepDefaultValues &&
1970
- !deepEqual(formValues, _defaultValues)),
1971
- isSubmitted: keepStateOptions.keepIsSubmitted
1972
- ? _formState.isSubmitted
1973
- : false,
1974
- dirtyFields: keepStateOptions.keepDirtyValues
1975
- ? _formState.dirtyFields
1976
- : keepStateOptions.keepDefaultValues && formValues
1977
- ? getDirtyFields(_defaultValues, formValues)
1978
- : {},
1979
- touchedFields: keepStateOptions.keepTouched
1980
- ? _formState.touchedFields
1981
- : {},
1982
- errors: keepStateOptions.keepErrors ? _formState.errors : {},
1983
- isSubmitting: false,
1984
- isSubmitSuccessful: false,
1985
- });
1986
- };
1987
- const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)
1988
- ? formValues(_formValues)
1989
- : formValues, keepStateOptions);
1990
- const setFocus = (name, options = {}) => {
1991
- const field = get(_fields, name);
1992
- const fieldReference = field && field._f;
1993
- if (fieldReference) {
1994
- const fieldRef = fieldReference.refs
1995
- ? fieldReference.refs[0]
1996
- : fieldReference.ref;
1997
- if (fieldRef.focus) {
1998
- fieldRef.focus();
1999
- options.shouldSelect && fieldRef.select();
2000
- }
2001
- }
2002
- };
2003
- const _updateFormState = (updatedFormState) => {
2004
- _formState = {
2005
- ..._formState,
2006
- ...updatedFormState,
2007
- };
2008
- };
2009
- const _resetDefaultValues = () => isFunction(_options.defaultValues) &&
2010
- _options.defaultValues().then((values) => {
2011
- reset(values, _options.resetOptions);
2012
- _subjects.state.next({
2013
- isLoading: false,
2014
- });
2015
- });
2016
- return {
2017
- control: {
2018
- register,
2019
- unregister,
2020
- getFieldState,
2021
- handleSubmit,
2022
- setError,
2023
- _executeSchema,
2024
- _getWatch,
2025
- _getDirty,
2026
- _updateValid,
2027
- _removeUnmounted,
2028
- _updateFieldArray,
2029
- _updateDisabledField,
2030
- _getFieldArray,
2031
- _reset,
2032
- _resetDefaultValues,
2033
- _updateFormState,
2034
- _subjects,
2035
- _proxyFormState,
2036
- get _fields() {
2037
- return _fields;
2038
- },
2039
- get _formValues() {
2040
- return _formValues;
2041
- },
2042
- get _state() {
2043
- return _state;
2044
- },
2045
- set _state(value) {
2046
- _state = value;
2047
- },
2048
- get _defaultValues() {
2049
- return _defaultValues;
2050
- },
2051
- get _names() {
2052
- return _names;
2053
- },
2054
- set _names(value) {
2055
- _names = value;
2056
- },
2057
- get _formState() {
2058
- return _formState;
2059
- },
2060
- set _formState(value) {
2061
- _formState = value;
2062
- },
2063
- get _options() {
2064
- return _options;
2065
- },
2066
- set _options(value) {
2067
- _options = {
2068
- ..._options,
2069
- ...value,
2070
- };
2071
- },
2072
- },
2073
- trigger,
2074
- register,
2075
- handleSubmit,
2076
- watch,
2077
- setValue,
2078
- getValues,
2079
- reset,
2080
- resetField,
2081
- clearErrors,
2082
- unregister,
2083
- setError,
2084
- setFocus,
2085
- getFieldState,
2086
- };
2087
- }
231
+ var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
2088
232
 
2089
- /**
2090
- * Custom hook to manage the entire form.
2091
- *
2092
- * @remarks
2093
- * [API](https://react-hook-form.com/docs/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
2094
- *
2095
- * @param props - form configuration and validation parameters.
2096
- *
2097
- * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
2098
- *
2099
- * @example
2100
- * ```tsx
2101
- * function App() {
2102
- * const { register, handleSubmit, watch, formState: { errors } } = useForm();
2103
- * const onSubmit = data => console.log(data);
2104
- *
2105
- * console.log(watch("example"));
2106
- *
2107
- * return (
2108
- * <form onSubmit={handleSubmit(onSubmit)}>
2109
- * <input defaultValue="test" {...register("example")} />
2110
- * <input {...register("exampleRequired", { required: true })} />
2111
- * {errors.exampleRequired && <span>This field is required</span>}
2112
- * <button>Submit</button>
2113
- * </form>
2114
- * );
2115
- * }
2116
- * ```
2117
- */
2118
- function useForm(props = {}) {
2119
- const _formControl = React__default.useRef();
2120
- const _values = React__default.useRef();
2121
- const [formState, updateFormState] = React__default.useState({
2122
- isDirty: false,
2123
- isValidating: false,
2124
- isLoading: isFunction(props.defaultValues),
2125
- isSubmitted: false,
2126
- isSubmitting: false,
2127
- isSubmitSuccessful: false,
2128
- isValid: false,
2129
- submitCount: 0,
2130
- dirtyFields: {},
2131
- touchedFields: {},
2132
- errors: {},
2133
- defaultValues: isFunction(props.defaultValues)
2134
- ? undefined
2135
- : props.defaultValues,
2136
- });
2137
- if (!_formControl.current) {
2138
- _formControl.current = {
2139
- ...createFormControl(props, () => updateFormState((formState) => ({ ...formState }))),
2140
- formState,
2141
- };
2142
- }
2143
- const control = _formControl.current.control;
2144
- control._options = props;
2145
- useSubscribe({
2146
- subject: control._subjects.state,
2147
- next: (value) => {
2148
- if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
2149
- updateFormState({ ...control._formState });
2150
- }
2151
- },
2152
- });
2153
- React__default.useEffect(() => {
2154
- if (props.values && !deepEqual(props.values, _values.current)) {
2155
- control._reset(props.values, control._options.resetOptions);
2156
- _values.current = props.values;
2157
- }
2158
- else {
2159
- control._resetDefaultValues();
2160
- }
2161
- }, [props.values, control]);
2162
- React__default.useEffect(() => {
2163
- if (!control._state.mount) {
2164
- control._updateValid();
2165
- control._state.mount = true;
2166
- }
2167
- if (control._state.watch) {
2168
- control._state.watch = false;
2169
- control._subjects.state.next({ ...control._formState });
2170
- }
2171
- control._removeUnmounted();
2172
- });
2173
- _formControl.current.formState = getProxyFormState(formState, control);
2174
- return _formControl.current;
2175
- }
233
+ var isUndefined = (val) => val === undefined;
2176
234
 
2177
- var theme = {
2178
- breakpoints: ['40em', '52em', '64em'],
2179
- space: ['0px', '4px', '8px', '16px', '32px', '64px', '128px', '256px', '512px'],
2180
- fontSizes: ['12px', '14px', '16px', '20px', '24px', '32px', '48px', '64px', '72px'],
2181
- marginPaddings: ['0.5rem', '1rem', '1.5rem', '2rem', '2.5rem', '3rem', '3.5rem', '4rem', '4.5rem', '5rem', '5.5rem', '6rem'],
2182
- letterSpacings: ['-0.5px', '0px', '+0.5px'],
2183
- radii: ['0px', '2px', '4px', '8px'],
2184
- borderRadius: '6px',
2185
- colors: {
2186
- primary: '#000',
2187
- base: '#4e4949',
2188
- baseLt: '#817c7c',
2189
- borderColor: '#d8d8d8',
2190
- ntrlMin: '#fff',
2191
- ntrlMinTen: '#e6e6e6',
2192
- gray: '#efefef',
2193
- darkerGray: '#454141'
2194
- },
2195
- rareStepColors: {
2196
- primary: '#202b58',
2197
- secondary: '#ef5c2d',
2198
- ntrlMin: '#ffffff',
2199
- ntrl40: '#f4f4f4',
2200
- ntrl50: '#808080',
2201
- ntrl60: '#e8e8e8',
2202
- ntrl70: '#252525',
2203
- ntrlMax: '#000000'
2204
- },
2205
- rareStepFontWeights: {
2206
- normal: 400,
2207
- medium: 500,
2208
- semiBold: 600,
2209
- bold: 700
2210
- },
2211
- rareStepFontSize: {
2212
- h1: '36px',
2213
- h2: '30px',
2214
- h3: '24px',
2215
- h4: '20px',
2216
- h5: '16px',
2217
- h6: '14px',
2218
- footerTitle: '16px'
2219
- },
2220
- rareStepPageSizes: {
2221
- mobile: '500px',
2222
- tablet: '768px',
2223
- desktop: '992px',
2224
- screenl: '1280px',
2225
- screenxl: '1680px',
2226
- screenxxl: '1920px',
2227
- container: '1600px'
235
+ var get = (obj, path, defaultValue) => {
236
+ if (!path || !isObject(obj)) {
237
+ return defaultValue;
2228
238
  }
2229
- };
2230
-
2231
- var themed = (function (Component) {
2232
- return /*#__PURE__*/React.forwardRef(function (props, ref) {
2233
- return /*#__PURE__*/React__default.createElement(styled.ThemeProvider, {
2234
- theme: theme
2235
- }, /*#__PURE__*/React__default.createElement(Component, _extends({}, props, {
2236
- ref: ref
2237
- })));
239
+ const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], obj);
240
+ return isUndefined(result) || result === obj
241
+ ? isUndefined(obj[path])
242
+ ? defaultValue
243
+ : obj[path]
244
+ : result;
245
+ };
246
+
247
+ const EVENTS = {
248
+ BLUR: 'blur',
249
+ FOCUS_OUT: 'focusout',
250
+ CHANGE: 'change',
251
+ };
252
+ const VALIDATION_MODE = {
253
+ onBlur: 'onBlur',
254
+ onChange: 'onChange',
255
+ onSubmit: 'onSubmit',
256
+ onTouched: 'onTouched',
257
+ all: 'all',
258
+ };
259
+ const INPUT_VALIDATION_RULES = {
260
+ max: 'max',
261
+ min: 'min',
262
+ maxLength: 'maxLength',
263
+ minLength: 'minLength',
264
+ pattern: 'pattern',
265
+ required: 'required',
266
+ validate: 'validate',
267
+ };
268
+
269
+ const HookFormContext = React.createContext(null);
270
+ /**
271
+ * This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.
272
+ *
273
+ * @remarks
274
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
275
+ *
276
+ * @returns return all useForm methods
277
+ *
278
+ * @example
279
+ * ```tsx
280
+ * function App() {
281
+ * const methods = useForm();
282
+ * const onSubmit = data => console.log(data);
283
+ *
284
+ * return (
285
+ * <FormProvider {...methods} >
286
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
287
+ * <NestedInput />
288
+ * <input type="submit" />
289
+ * </form>
290
+ * </FormProvider>
291
+ * );
292
+ * }
293
+ *
294
+ * function NestedInput() {
295
+ * const { register } = useFormContext(); // retrieve all hook methods
296
+ * return <input {...register("test")} />;
297
+ * }
298
+ * ```
299
+ */
300
+ const useFormContext = () => React.useContext(HookFormContext);
301
+
302
+ var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
303
+ const result = {
304
+ defaultValues: control._defaultValues,
305
+ };
306
+ for (const key in formState) {
307
+ Object.defineProperty(result, key, {
308
+ get: () => {
309
+ const _key = key;
310
+ if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
311
+ control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
312
+ }
313
+ localProxyFormState && (localProxyFormState[_key] = true);
314
+ return formState[_key];
315
+ },
316
+ });
317
+ }
318
+ return result;
319
+ };
320
+
321
+ var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
322
+
323
+ var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
324
+ updateFormState(formStateData);
325
+ const { name, ...formState } = formStateData;
326
+ return (isEmptyObject(formState) ||
327
+ Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
328
+ Object.keys(formState).find((key) => _proxyFormState[key] ===
329
+ (!isRoot || VALIDATION_MODE.all)));
330
+ };
331
+
332
+ var convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]);
333
+
334
+ var shouldSubscribeByName = (name, signalName, exact) => exact && signalName
335
+ ? name === signalName ||
336
+ (Array.isArray(name) &&
337
+ name.some((currentName) => currentName && exact && currentName === signalName))
338
+ : !name ||
339
+ !signalName ||
340
+ name === signalName ||
341
+ convertToArrayPayload(name).some((currentName) => currentName &&
342
+ (currentName.startsWith(signalName) ||
343
+ signalName.startsWith(currentName)));
344
+
345
+ function useSubscribe(props) {
346
+ const _props = React.useRef(props);
347
+ _props.current = props;
348
+ React.useEffect(() => {
349
+ const subscription = !props.disabled &&
350
+ _props.current.subject &&
351
+ _props.current.subject.subscribe({
352
+ next: _props.current.next,
353
+ });
354
+ return () => {
355
+ subscription && subscription.unsubscribe();
356
+ };
357
+ }, [props.disabled]);
358
+ }
359
+
360
+ /**
361
+ * This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.
362
+ *
363
+ * @remarks
364
+ * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
365
+ *
366
+ * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
367
+ *
368
+ * @example
369
+ * ```tsx
370
+ * function App() {
371
+ * const { register, handleSubmit, control } = useForm({
372
+ * defaultValues: {
373
+ * firstName: "firstName"
374
+ * }});
375
+ * const { dirtyFields } = useFormState({
376
+ * control
377
+ * });
378
+ * const onSubmit = (data) => console.log(data);
379
+ *
380
+ * return (
381
+ * <form onSubmit={handleSubmit(onSubmit)}>
382
+ * <input {...register("firstName")} placeholder="First Name" />
383
+ * {dirtyFields.firstName && <p>Field is dirty.</p>}
384
+ * <input type="submit" />
385
+ * </form>
386
+ * );
387
+ * }
388
+ * ```
389
+ */
390
+ function useFormState(props) {
391
+ const methods = useFormContext();
392
+ const { control = methods.control, disabled, name, exact } = props || {};
393
+ const [formState, updateFormState] = React.useState(control._formState);
394
+ const _mounted = React.useRef(true);
395
+ const _localProxyFormState = React.useRef({
396
+ isDirty: false,
397
+ isLoading: false,
398
+ dirtyFields: false,
399
+ touchedFields: false,
400
+ isValidating: false,
401
+ isValid: false,
402
+ errors: false,
2238
403
  });
2239
- });
2240
-
2241
- var _templateObject;
2242
- var RadioButtonLabel = styled__default.label(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n display: flex;\n margin-bottom: ", ";\n margin-right: ", ";\n"])), function (props) {
2243
- return props.theme.marginPaddings[0];
2244
- }, function (props) {
2245
- return props.theme.marginPaddings[0];
2246
- });
2247
-
2248
- var _templateObject$1;
2249
- var RadioButtonText = styled__default.div(_templateObject$1 || (_templateObject$1 = _taggedTemplateLiteral(["\n display: flex;\n align-items: center;\n"])));
2250
-
2251
- var _templateObject$2;
2252
- var RadioButtonCircle = styled__default.div(_templateObject$2 || (_templateObject$2 = _taggedTemplateLiteral(["\n height: 20px;\n width: 20px;\n border-radius: 50%;\n margin-right: 5px;\n border: 1px solid ", ";\n display: flex;\n"])), function (props) {
2253
- return props.theme.colors.base;
2254
- });
2255
-
2256
- var _templateObject$3;
2257
- var RadioButtonCircleInner = styled__default.div(_templateObject$3 || (_templateObject$3 = _taggedTemplateLiteral(["\n height: 8px;\n width: 8px;\n border-radius: 50%;\n margin: auto;\n"])));
404
+ const _name = React.useRef(name);
405
+ _name.current = name;
406
+ useSubscribe({
407
+ disabled,
408
+ next: (value) => _mounted.current &&
409
+ shouldSubscribeByName(_name.current, value.name, exact) &&
410
+ shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) &&
411
+ updateFormState({
412
+ ...control._formState,
413
+ ...value,
414
+ }),
415
+ subject: control._subjects.state,
416
+ });
417
+ React.useEffect(() => {
418
+ _mounted.current = true;
419
+ _localProxyFormState.current.isValid && control._updateValid(true);
420
+ return () => {
421
+ _mounted.current = false;
422
+ };
423
+ }, [control]);
424
+ return getProxyFormState(formState, control, _localProxyFormState.current, false);
425
+ }
426
+
427
+ var isString = (value) => typeof value === 'string';
428
+
429
+ var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
430
+ if (isString(names)) {
431
+ isGlobal && _names.watch.add(names);
432
+ return get(formValues, names, defaultValue);
433
+ }
434
+ if (Array.isArray(names)) {
435
+ return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
436
+ }
437
+ isGlobal && (_names.watchAll = true);
438
+ return formValues;
439
+ };
440
+
441
+ /**
442
+ * Custom hook to subscribe to field change and isolate re-rendering at the component level.
443
+ *
444
+ * @remarks
445
+ *
446
+ * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
447
+ *
448
+ * @example
449
+ * ```tsx
450
+ * const { watch } = useForm();
451
+ * const values = useWatch({
452
+ * name: "fieldName"
453
+ * control,
454
+ * })
455
+ * ```
456
+ */
457
+ function useWatch(props) {
458
+ const methods = useFormContext();
459
+ const { control = methods.control, name, defaultValue, disabled, exact, } = props || {};
460
+ const _name = React.useRef(name);
461
+ _name.current = name;
462
+ useSubscribe({
463
+ disabled,
464
+ subject: control._subjects.values,
465
+ next: (formState) => {
466
+ if (shouldSubscribeByName(_name.current, formState.name, exact)) {
467
+ updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
468
+ }
469
+ },
470
+ });
471
+ const [value, updateValue] = React.useState(control._getWatch(name, defaultValue));
472
+ React.useEffect(() => control._removeUnmounted());
473
+ return value;
474
+ }
475
+
476
+ var isKey = (value) => /^\w*$/.test(value);
477
+
478
+ var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
479
+
480
+ function set(object, path, value) {
481
+ let index = -1;
482
+ const tempPath = isKey(path) ? [path] : stringToPath(path);
483
+ const length = tempPath.length;
484
+ const lastIndex = length - 1;
485
+ while (++index < length) {
486
+ const key = tempPath[index];
487
+ let newValue = value;
488
+ if (index !== lastIndex) {
489
+ const objValue = object[key];
490
+ newValue =
491
+ isObject(objValue) || Array.isArray(objValue)
492
+ ? objValue
493
+ : !isNaN(+tempPath[index + 1])
494
+ ? []
495
+ : {};
496
+ }
497
+ object[key] = newValue;
498
+ object = object[key];
499
+ }
500
+ return object;
501
+ }
502
+
503
+ /**
504
+ * Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.
505
+ *
506
+ * @remarks
507
+ * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
508
+ *
509
+ * @param props - the path name to the form field value, and validation rules.
510
+ *
511
+ * @returns field properties, field and form state. {@link UseControllerReturn}
512
+ *
513
+ * @example
514
+ * ```tsx
515
+ * function Input(props) {
516
+ * const { field, fieldState, formState } = useController(props);
517
+ * return (
518
+ * <div>
519
+ * <input {...field} placeholder={props.name} />
520
+ * <p>{fieldState.isTouched && "Touched"}</p>
521
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
522
+ * </div>
523
+ * );
524
+ * }
525
+ * ```
526
+ */
527
+ function useController(props) {
528
+ const methods = useFormContext();
529
+ const { name, disabled, control = methods.control, shouldUnregister } = props;
530
+ const isArrayField = isNameInFieldArray(control._names.array, name);
531
+ const value = useWatch({
532
+ control,
533
+ name,
534
+ defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
535
+ exact: true,
536
+ });
537
+ const formState = useFormState({
538
+ control,
539
+ name,
540
+ });
541
+ const _registerProps = React.useRef(control.register(name, {
542
+ ...props.rules,
543
+ value,
544
+ }));
545
+ _registerProps.current = control.register(name, props.rules);
546
+ React.useEffect(() => {
547
+ const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
548
+ const updateMounted = (name, value) => {
549
+ const field = get(control._fields, name);
550
+ if (field) {
551
+ field._f.mount = value;
552
+ }
553
+ };
554
+ updateMounted(name, true);
555
+ if (_shouldUnregisterField) {
556
+ const value = cloneObject(get(control._options.defaultValues, name));
557
+ set(control._defaultValues, name, value);
558
+ if (isUndefined(get(control._formValues, name))) {
559
+ set(control._formValues, name, value);
560
+ }
561
+ }
562
+ return () => {
563
+ (isArrayField
564
+ ? _shouldUnregisterField && !control._state.action
565
+ : _shouldUnregisterField)
566
+ ? control.unregister(name)
567
+ : updateMounted(name, false);
568
+ };
569
+ }, [name, control, isArrayField, shouldUnregister]);
570
+ React.useEffect(() => {
571
+ control._updateDisabledField({
572
+ disabled,
573
+ fields: control._fields,
574
+ name,
575
+ });
576
+ }, [disabled, name, control]);
577
+ return {
578
+ field: {
579
+ name,
580
+ value,
581
+ disabled,
582
+ onChange: React.useCallback((event) => _registerProps.current.onChange({
583
+ target: {
584
+ value: getEventValue(event),
585
+ name: name,
586
+ },
587
+ type: EVENTS.CHANGE,
588
+ }), [name]),
589
+ onBlur: React.useCallback(() => _registerProps.current.onBlur({
590
+ target: {
591
+ value: get(control._formValues, name),
592
+ name: name,
593
+ },
594
+ type: EVENTS.BLUR,
595
+ }), [name, control]),
596
+ ref: (elm) => {
597
+ const field = get(control._fields, name);
598
+ if (field && elm) {
599
+ field._f.ref = {
600
+ focus: () => elm.focus(),
601
+ select: () => elm.select(),
602
+ setCustomValidity: (message) => elm.setCustomValidity(message),
603
+ reportValidity: () => elm.reportValidity(),
604
+ };
605
+ }
606
+ },
607
+ },
608
+ formState,
609
+ fieldState: Object.defineProperties({}, {
610
+ invalid: {
611
+ enumerable: true,
612
+ get: () => !!get(formState.errors, name),
613
+ },
614
+ isDirty: {
615
+ enumerable: true,
616
+ get: () => !!get(formState.dirtyFields, name),
617
+ },
618
+ isTouched: {
619
+ enumerable: true,
620
+ get: () => !!get(formState.touchedFields, name),
621
+ },
622
+ error: {
623
+ enumerable: true,
624
+ get: () => get(formState.errors, name),
625
+ },
626
+ }),
627
+ };
628
+ }
629
+
630
+ var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria
631
+ ? {
632
+ ...errors[name],
633
+ types: {
634
+ ...(errors[name] && errors[name].types ? errors[name].types : {}),
635
+ [type]: message || true,
636
+ },
637
+ }
638
+ : {};
639
+
640
+ const focusFieldBy = (fields, callback, fieldsNames) => {
641
+ for (const key of fieldsNames || Object.keys(fields)) {
642
+ const field = get(fields, key);
643
+ if (field) {
644
+ const { _f, ...currentField } = field;
645
+ if (_f && callback(_f.name)) {
646
+ if (_f.ref.focus) {
647
+ _f.ref.focus();
648
+ break;
649
+ }
650
+ else if (_f.refs && _f.refs[0].focus) {
651
+ _f.refs[0].focus();
652
+ break;
653
+ }
654
+ }
655
+ else if (isObject(currentField)) {
656
+ focusFieldBy(currentField, callback);
657
+ }
658
+ }
659
+ }
660
+ };
661
+
662
+ var getValidationModes = (mode) => ({
663
+ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
664
+ isOnBlur: mode === VALIDATION_MODE.onBlur,
665
+ isOnChange: mode === VALIDATION_MODE.onChange,
666
+ isOnAll: mode === VALIDATION_MODE.all,
667
+ isOnTouch: mode === VALIDATION_MODE.onTouched,
668
+ });
669
+
670
+ var isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&
671
+ (_names.watchAll ||
672
+ _names.watch.has(name) ||
673
+ [..._names.watch].some((watchName) => name.startsWith(watchName) &&
674
+ /^\.\w+/.test(name.slice(watchName.length))));
675
+
676
+ var updateFieldArrayRootError = (errors, error, name) => {
677
+ const fieldArrayErrors = compact(get(errors, name));
678
+ set(fieldArrayErrors, 'root', error[name]);
679
+ set(errors, name, fieldArrayErrors);
680
+ return errors;
681
+ };
682
+
683
+ var isBoolean = (value) => typeof value === 'boolean';
684
+
685
+ var isFileInput = (element) => element.type === 'file';
686
+
687
+ var isFunction = (value) => typeof value === 'function';
688
+
689
+ var isHTMLElement = (value) => {
690
+ if (!isWeb) {
691
+ return false;
692
+ }
693
+ const owner = value ? value.ownerDocument : 0;
694
+ return (value instanceof
695
+ (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));
696
+ };
697
+
698
+ var isMessage = (value) => isString(value);
699
+
700
+ var isRadioInput = (element) => element.type === 'radio';
701
+
702
+ var isRegex = (value) => value instanceof RegExp;
703
+
704
+ const defaultResult = {
705
+ value: false,
706
+ isValid: false,
707
+ };
708
+ const validResult = { value: true, isValid: true };
709
+ var getCheckboxValue = (options) => {
710
+ if (Array.isArray(options)) {
711
+ if (options.length > 1) {
712
+ const values = options
713
+ .filter((option) => option && option.checked && !option.disabled)
714
+ .map((option) => option.value);
715
+ return { value: values, isValid: !!values.length };
716
+ }
717
+ return options[0].checked && !options[0].disabled
718
+ ? // @ts-expect-error expected to work in the browser
719
+ options[0].attributes && !isUndefined(options[0].attributes.value)
720
+ ? isUndefined(options[0].value) || options[0].value === ''
721
+ ? validResult
722
+ : { value: options[0].value, isValid: true }
723
+ : validResult
724
+ : defaultResult;
725
+ }
726
+ return defaultResult;
727
+ };
728
+
729
+ const defaultReturn = {
730
+ isValid: false,
731
+ value: null,
732
+ };
733
+ var getRadioValue = (options) => Array.isArray(options)
734
+ ? options.reduce((previous, option) => option && option.checked && !option.disabled
735
+ ? {
736
+ isValid: true,
737
+ value: option.value,
738
+ }
739
+ : previous, defaultReturn)
740
+ : defaultReturn;
741
+
742
+ function getValidateError(result, ref, type = 'validate') {
743
+ if (isMessage(result) ||
744
+ (Array.isArray(result) && result.every(isMessage)) ||
745
+ (isBoolean(result) && !result)) {
746
+ return {
747
+ type,
748
+ message: isMessage(result) ? result : '',
749
+ ref,
750
+ };
751
+ }
752
+ }
2258
753
 
2259
- var _templateObject$4;
2260
- var RadioButtonInput = styled__default.input(_templateObject$4 || (_templateObject$4 = _taggedTemplateLiteral(["\n display: none;\n :checked ~ ", " {\n ", " {\n background-color: ", ";\n }\n }\n"])), RadioButtonCircle, RadioButtonCircleInner, function (props) {
2261
- return props.theme.colors.base;
2262
- });
754
+ var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
755
+ ? validationData
756
+ : {
757
+ value: validationData,
758
+ message: '',
759
+ };
2263
760
 
2264
- var _excluded = ["ref"];
761
+ var validateField = async (field, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
762
+ const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled, } = field._f;
763
+ const inputValue = get(formValues, name);
764
+ if (!mount || disabled) {
765
+ return {};
766
+ }
767
+ const inputRef = refs ? refs[0] : ref;
768
+ const setCustomValidity = (message) => {
769
+ if (shouldUseNativeValidation && inputRef.reportValidity) {
770
+ inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
771
+ inputRef.reportValidity();
772
+ }
773
+ };
774
+ const error = {};
775
+ const isRadio = isRadioInput(ref);
776
+ const isCheckBox = isCheckBoxInput(ref);
777
+ const isRadioOrCheckbox = isRadio || isCheckBox;
778
+ const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
779
+ isUndefined(ref.value) &&
780
+ isUndefined(inputValue)) ||
781
+ (isHTMLElement(ref) && ref.value === '') ||
782
+ inputValue === '' ||
783
+ (Array.isArray(inputValue) && !inputValue.length);
784
+ const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
785
+ const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
786
+ const message = exceedMax ? maxLengthMessage : minLengthMessage;
787
+ error[name] = {
788
+ type: exceedMax ? maxType : minType,
789
+ message,
790
+ ref,
791
+ ...appendErrorsCurry(exceedMax ? maxType : minType, message),
792
+ };
793
+ };
794
+ if (isFieldArray
795
+ ? !Array.isArray(inputValue) || !inputValue.length
796
+ : required &&
797
+ ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
798
+ (isBoolean(inputValue) && !inputValue) ||
799
+ (isCheckBox && !getCheckboxValue(refs).isValid) ||
800
+ (isRadio && !getRadioValue(refs).isValid))) {
801
+ const { value, message } = isMessage(required)
802
+ ? { value: !!required, message: required }
803
+ : getValueAndMessage(required);
804
+ if (value) {
805
+ error[name] = {
806
+ type: INPUT_VALIDATION_RULES.required,
807
+ message,
808
+ ref: inputRef,
809
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
810
+ };
811
+ if (!validateAllFieldCriteria) {
812
+ setCustomValidity(message);
813
+ return error;
814
+ }
815
+ }
816
+ }
817
+ if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
818
+ let exceedMax;
819
+ let exceedMin;
820
+ const maxOutput = getValueAndMessage(max);
821
+ const minOutput = getValueAndMessage(min);
822
+ if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
823
+ const valueNumber = ref.valueAsNumber ||
824
+ (inputValue ? +inputValue : inputValue);
825
+ if (!isNullOrUndefined(maxOutput.value)) {
826
+ exceedMax = valueNumber > maxOutput.value;
827
+ }
828
+ if (!isNullOrUndefined(minOutput.value)) {
829
+ exceedMin = valueNumber < minOutput.value;
830
+ }
831
+ }
832
+ else {
833
+ const valueDate = ref.valueAsDate || new Date(inputValue);
834
+ const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
835
+ const isTime = ref.type == 'time';
836
+ const isWeek = ref.type == 'week';
837
+ if (isString(maxOutput.value) && inputValue) {
838
+ exceedMax = isTime
839
+ ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
840
+ : isWeek
841
+ ? inputValue > maxOutput.value
842
+ : valueDate > new Date(maxOutput.value);
843
+ }
844
+ if (isString(minOutput.value) && inputValue) {
845
+ exceedMin = isTime
846
+ ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
847
+ : isWeek
848
+ ? inputValue < minOutput.value
849
+ : valueDate < new Date(minOutput.value);
850
+ }
851
+ }
852
+ if (exceedMax || exceedMin) {
853
+ getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
854
+ if (!validateAllFieldCriteria) {
855
+ setCustomValidity(error[name].message);
856
+ return error;
857
+ }
858
+ }
859
+ }
860
+ if ((maxLength || minLength) &&
861
+ !isEmpty &&
862
+ (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
863
+ const maxLengthOutput = getValueAndMessage(maxLength);
864
+ const minLengthOutput = getValueAndMessage(minLength);
865
+ const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
866
+ inputValue.length > +maxLengthOutput.value;
867
+ const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
868
+ inputValue.length < +minLengthOutput.value;
869
+ if (exceedMax || exceedMin) {
870
+ getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
871
+ if (!validateAllFieldCriteria) {
872
+ setCustomValidity(error[name].message);
873
+ return error;
874
+ }
875
+ }
876
+ }
877
+ if (pattern && !isEmpty && isString(inputValue)) {
878
+ const { value: patternValue, message } = getValueAndMessage(pattern);
879
+ if (isRegex(patternValue) && !inputValue.match(patternValue)) {
880
+ error[name] = {
881
+ type: INPUT_VALIDATION_RULES.pattern,
882
+ message,
883
+ ref,
884
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
885
+ };
886
+ if (!validateAllFieldCriteria) {
887
+ setCustomValidity(message);
888
+ return error;
889
+ }
890
+ }
891
+ }
892
+ if (validate) {
893
+ if (isFunction(validate)) {
894
+ const result = await validate(inputValue, formValues);
895
+ const validateError = getValidateError(result, inputRef);
896
+ if (validateError) {
897
+ error[name] = {
898
+ ...validateError,
899
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
900
+ };
901
+ if (!validateAllFieldCriteria) {
902
+ setCustomValidity(validateError.message);
903
+ return error;
904
+ }
905
+ }
906
+ }
907
+ else if (isObject(validate)) {
908
+ let validationResult = {};
909
+ for (const key in validate) {
910
+ if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
911
+ break;
912
+ }
913
+ const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
914
+ if (validateError) {
915
+ validationResult = {
916
+ ...validateError,
917
+ ...appendErrorsCurry(key, validateError.message),
918
+ };
919
+ setCustomValidity(validateError.message);
920
+ if (validateAllFieldCriteria) {
921
+ error[name] = validationResult;
922
+ }
923
+ }
924
+ }
925
+ if (!isEmptyObject(validationResult)) {
926
+ error[name] = {
927
+ ref: inputRef,
928
+ ...validationResult,
929
+ };
930
+ if (!validateAllFieldCriteria) {
931
+ return error;
932
+ }
933
+ }
934
+ }
935
+ }
936
+ setCustomValidity(true);
937
+ return error;
938
+ };
939
+
940
+ function baseGet(object, updatePath) {
941
+ const length = updatePath.slice(0, -1).length;
942
+ let index = 0;
943
+ while (index < length) {
944
+ object = isUndefined(object) ? index++ : object[updatePath[index++]];
945
+ }
946
+ return object;
947
+ }
948
+ function isEmptyArray(obj) {
949
+ for (const key in obj) {
950
+ if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
951
+ return false;
952
+ }
953
+ }
954
+ return true;
955
+ }
956
+ function unset(object, path) {
957
+ const paths = Array.isArray(path)
958
+ ? path
959
+ : isKey(path)
960
+ ? [path]
961
+ : stringToPath(path);
962
+ const childObject = paths.length === 1 ? object : baseGet(object, paths);
963
+ const index = paths.length - 1;
964
+ const key = paths[index];
965
+ if (childObject) {
966
+ delete childObject[key];
967
+ }
968
+ if (index !== 0 &&
969
+ ((isObject(childObject) && isEmptyObject(childObject)) ||
970
+ (Array.isArray(childObject) && isEmptyArray(childObject)))) {
971
+ unset(object, paths.slice(0, -1));
972
+ }
973
+ return object;
974
+ }
975
+
976
+ function createSubject() {
977
+ let _observers = [];
978
+ const next = (value) => {
979
+ for (const observer of _observers) {
980
+ observer.next && observer.next(value);
981
+ }
982
+ };
983
+ const subscribe = (observer) => {
984
+ _observers.push(observer);
985
+ return {
986
+ unsubscribe: () => {
987
+ _observers = _observers.filter((o) => o !== observer);
988
+ },
989
+ };
990
+ };
991
+ const unsubscribe = () => {
992
+ _observers = [];
993
+ };
994
+ return {
995
+ get observers() {
996
+ return _observers;
997
+ },
998
+ next,
999
+ subscribe,
1000
+ unsubscribe,
1001
+ };
1002
+ }
2265
1003
 
2266
- var _templateObject$5, _templateObject2;
2267
- var OptionsRow = styled__default.div(_templateObject$5 || (_templateObject$5 = _taggedTemplateLiteral(["\n display: flex;\n flex-wrap: nowrap;\n flex-direction: row;\n"])));
2268
- var Options = styled__default.div(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n display: flex;\n flex-wrap: nowrap;\n flex-direction: row;\n flex-basis: 60%;\n"])));
1004
+ var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
2269
1005
 
2270
- var CommunicationPreferenceOptionsRenderer = function CommunicationPreferenceOptionsRenderer(_ref) {
2271
- var control = _ref.control,
2272
- name = _ref.name,
2273
- isDisabled = _ref.isDisabled,
2274
- options = _ref.options,
2275
- defaultValue = _ref.defaultValue,
2276
- setValue = _ref.setValue;
1006
+ function deepEqual(object1, object2) {
1007
+ if (isPrimitive(object1) || isPrimitive(object2)) {
1008
+ return object1 === object2;
1009
+ }
1010
+ if (isDateObject(object1) && isDateObject(object2)) {
1011
+ return object1.getTime() === object2.getTime();
1012
+ }
1013
+ const keys1 = Object.keys(object1);
1014
+ const keys2 = Object.keys(object2);
1015
+ if (keys1.length !== keys2.length) {
1016
+ return false;
1017
+ }
1018
+ for (const key of keys1) {
1019
+ const val1 = object1[key];
1020
+ if (!keys2.includes(key)) {
1021
+ return false;
1022
+ }
1023
+ if (key !== 'ref') {
1024
+ const val2 = object2[key];
1025
+ if ((isDateObject(val1) && isDateObject(val2)) ||
1026
+ (isObject(val1) && isObject(val2)) ||
1027
+ (Array.isArray(val1) && Array.isArray(val2))
1028
+ ? !deepEqual(val1, val2)
1029
+ : val1 !== val2) {
1030
+ return false;
1031
+ }
1032
+ }
1033
+ }
1034
+ return true;
1035
+ }
2277
1036
 
2278
- var _useController = useController({
2279
- name: name,
2280
- control: control,
2281
- defaultValue: defaultValue
2282
- }),
2283
- _useController$field = _useController.field,
2284
- ref = _useController$field.ref,
2285
- inputProps = _objectWithoutProperties(_useController$field, _excluded),
2286
- _useController$fieldS = _useController.fieldState,
2287
- invalid = _useController$fieldS.invalid,
2288
- error = _useController$fieldS.error;
2289
-
2290
- React.useEffect(function () {
2291
- if (defaultValue) {
2292
- setValue(name, defaultValue);
2293
- }
2294
- }, [defaultValue, name, setValue]);
2295
- return /*#__PURE__*/React__default.createElement(OptionsRow, null, /*#__PURE__*/React__default.createElement(Options, null, options.map(function (option) {
2296
- return /*#__PURE__*/React__default.createElement(RadioButtonLabel, {
2297
- key: option.value,
2298
- htmlFor: option.value
2299
- }, /*#__PURE__*/React__default.createElement(RadioButtonInput, _extends({
2300
- id: option.value,
2301
- ref: ref,
2302
- type: "radio",
2303
- name: name,
2304
- defaultChecked: inputProps.value === option.value.toString()
2305
- }, inputProps, {
2306
- disabled: isDisabled,
2307
- value: option.value
2308
- })), /*#__PURE__*/React__default.createElement(RadioButtonCircle, null, /*#__PURE__*/React__default.createElement(RadioButtonCircleInner, null)), /*#__PURE__*/React__default.createElement(RadioButtonText, null, option.label));
2309
- })), invalid && /*#__PURE__*/React__default.createElement("span", {
2310
- className: "form__error"
2311
- }, error === null || error === void 0 ? void 0 : error.message));
2312
- };
1037
+ var isMultipleSelect = (element) => element.type === `select-multiple`;
2313
1038
 
2314
- var _templateObject$6, _templateObject2$1;
2315
- var SectionContainer = styled__default.div(_templateObject$6 || (_templateObject$6 = _taggedTemplateLiteral(["\n border-top: flex 1px solid ", ";\n border-top-width: calc(100% - 50px);\n padding: 5px 10px;\n"])), function (props) {
2316
- return props.theme.colors.primary;
2317
- });
2318
- var SectionHeading = styled__default.div(_templateObject2$1 || (_templateObject2$1 = _taggedTemplateLiteral(["\n padding: 5px 10px;\n"])));
2319
-
2320
- var CommunicationPreferenceSection = function CommunicationPreferenceSection(_ref) {
2321
- var section_heading = _ref.section_heading,
2322
- description = _ref.description,
2323
- control = _ref.control,
2324
- name = _ref.name,
2325
- isDisabled = _ref.isDisabled,
2326
- options = _ref.options,
2327
- defaultValue = _ref.defaultValue,
2328
- setValue = _ref.setValue;
2329
- return /*#__PURE__*/React__default.createElement(SectionContainer, null, /*#__PURE__*/React__default.createElement(SectionHeading, null, section_heading), /*#__PURE__*/React__default.createElement(CommunicationPreferenceOptionsRenderer, {
2330
- description: description,
2331
- control: control,
2332
- name: name,
2333
- isDisabled: isDisabled,
2334
- options: options,
2335
- defaultValue: defaultValue,
2336
- setValue: setValue
2337
- }));
2338
- };
1039
+ var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
2339
1040
 
2340
- var CommunicationPreferenceSection$1 = themed(CommunicationPreferenceSection);
1041
+ var live = (ref) => isHTMLElement(ref) && ref.isConnected;
2341
1042
 
2342
- var defaultNotifyTime = 5000;
2343
- var success = function success(message) {
2344
- Notifications.notify.show(message, 'success', defaultNotifyTime);
2345
- };
2346
- var error = function error(message) {
2347
- Notifications.notify.show(message, 'error', defaultNotifyTime);
2348
- };
1043
+ var objectHasFunction = (data) => {
1044
+ for (const key in data) {
1045
+ if (isFunction(data[key])) {
1046
+ return true;
1047
+ }
1048
+ }
1049
+ return false;
1050
+ };
1051
+
1052
+ function markFieldsDirty(data, fields = {}) {
1053
+ const isParentNodeArray = Array.isArray(data);
1054
+ if (isObject(data) || isParentNodeArray) {
1055
+ for (const key in data) {
1056
+ if (Array.isArray(data[key]) ||
1057
+ (isObject(data[key]) && !objectHasFunction(data[key]))) {
1058
+ fields[key] = Array.isArray(data[key]) ? [] : {};
1059
+ markFieldsDirty(data[key], fields[key]);
1060
+ }
1061
+ else if (!isNullOrUndefined(data[key])) {
1062
+ fields[key] = true;
1063
+ }
1064
+ }
1065
+ }
1066
+ return fields;
1067
+ }
1068
+ function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
1069
+ const isParentNodeArray = Array.isArray(data);
1070
+ if (isObject(data) || isParentNodeArray) {
1071
+ for (const key in data) {
1072
+ if (Array.isArray(data[key]) ||
1073
+ (isObject(data[key]) && !objectHasFunction(data[key]))) {
1074
+ if (isUndefined(formValues) ||
1075
+ isPrimitive(dirtyFieldsFromValues[key])) {
1076
+ dirtyFieldsFromValues[key] = Array.isArray(data[key])
1077
+ ? markFieldsDirty(data[key], [])
1078
+ : { ...markFieldsDirty(data[key]) };
1079
+ }
1080
+ else {
1081
+ getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
1082
+ }
1083
+ }
1084
+ else {
1085
+ dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
1086
+ }
1087
+ }
1088
+ }
1089
+ return dirtyFieldsFromValues;
1090
+ }
1091
+ var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));
1092
+
1093
+ var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)
1094
+ ? value
1095
+ : valueAsNumber
1096
+ ? value === ''
1097
+ ? NaN
1098
+ : value
1099
+ ? +value
1100
+ : value
1101
+ : valueAsDate && isString(value)
1102
+ ? new Date(value)
1103
+ : setValueAs
1104
+ ? setValueAs(value)
1105
+ : value;
1106
+
1107
+ function getFieldValue(_f) {
1108
+ const ref = _f.ref;
1109
+ if (_f.refs ? _f.refs.every((ref) => ref.disabled) : ref.disabled) {
1110
+ return;
1111
+ }
1112
+ if (isFileInput(ref)) {
1113
+ return ref.files;
1114
+ }
1115
+ if (isRadioInput(ref)) {
1116
+ return getRadioValue(_f.refs).value;
1117
+ }
1118
+ if (isMultipleSelect(ref)) {
1119
+ return [...ref.selectedOptions].map(({ value }) => value);
1120
+ }
1121
+ if (isCheckBoxInput(ref)) {
1122
+ return getCheckboxValue(_f.refs).value;
1123
+ }
1124
+ return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
1125
+ }
1126
+
1127
+ var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
1128
+ const fields = {};
1129
+ for (const name of fieldsNames) {
1130
+ const field = get(_fields, name);
1131
+ field && set(fields, name, field._f);
1132
+ }
1133
+ return {
1134
+ criteriaMode,
1135
+ names: [...fieldsNames],
1136
+ fields,
1137
+ shouldUseNativeValidation,
1138
+ };
1139
+ };
1140
+
1141
+ var getRuleValue = (rule) => isUndefined(rule)
1142
+ ? rule
1143
+ : isRegex(rule)
1144
+ ? rule.source
1145
+ : isObject(rule)
1146
+ ? isRegex(rule.value)
1147
+ ? rule.value.source
1148
+ : rule.value
1149
+ : rule;
1150
+
1151
+ var hasValidation = (options) => options.mount &&
1152
+ (options.required ||
1153
+ options.min ||
1154
+ options.max ||
1155
+ options.maxLength ||
1156
+ options.minLength ||
1157
+ options.pattern ||
1158
+ options.validate);
1159
+
1160
+ function schemaErrorLookup(errors, _fields, name) {
1161
+ const error = get(errors, name);
1162
+ if (error || isKey(name)) {
1163
+ return {
1164
+ error,
1165
+ name,
1166
+ };
1167
+ }
1168
+ const names = name.split('.');
1169
+ while (names.length) {
1170
+ const fieldName = names.join('.');
1171
+ const field = get(_fields, fieldName);
1172
+ const foundError = get(errors, fieldName);
1173
+ if (field && !Array.isArray(field) && name !== fieldName) {
1174
+ return { name };
1175
+ }
1176
+ if (foundError && foundError.type) {
1177
+ return {
1178
+ name: fieldName,
1179
+ error: foundError,
1180
+ };
1181
+ }
1182
+ names.pop();
1183
+ }
1184
+ return {
1185
+ name,
1186
+ };
1187
+ }
2349
1188
 
2350
- var simpleRequest = (function (axiosInstance, url) {
2351
- var method = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'get';
2352
- var payload = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2353
- var onSuccess = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : function () {
2354
- return null;
1189
+ var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
1190
+ if (mode.isOnAll) {
1191
+ return false;
1192
+ }
1193
+ else if (!isSubmitted && mode.isOnTouch) {
1194
+ return !(isTouched || isBlurEvent);
1195
+ }
1196
+ else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
1197
+ return !isBlurEvent;
1198
+ }
1199
+ else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
1200
+ return isBlurEvent;
1201
+ }
1202
+ return true;
1203
+ };
1204
+
1205
+ var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
1206
+
1207
+ const defaultOptions = {
1208
+ mode: VALIDATION_MODE.onSubmit,
1209
+ reValidateMode: VALIDATION_MODE.onChange,
1210
+ shouldFocusError: true,
1211
+ };
1212
+ function createFormControl(props = {}, flushRootRender) {
1213
+ let _options = {
1214
+ ...defaultOptions,
1215
+ ...props,
1216
+ };
1217
+ let _formState = {
1218
+ submitCount: 0,
1219
+ isDirty: false,
1220
+ isLoading: isFunction(_options.defaultValues),
1221
+ isValidating: false,
1222
+ isSubmitted: false,
1223
+ isSubmitting: false,
1224
+ isSubmitSuccessful: false,
1225
+ isValid: false,
1226
+ touchedFields: {},
1227
+ dirtyFields: {},
1228
+ errors: {},
2355
1229
  };
2356
- var onFailed = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : function () {
2357
- return null;
1230
+ let _fields = {};
1231
+ let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
1232
+ ? cloneObject(_options.defaultValues || _options.values) || {}
1233
+ : {};
1234
+ let _formValues = _options.shouldUnregister
1235
+ ? {}
1236
+ : cloneObject(_defaultValues);
1237
+ let _state = {
1238
+ action: false,
1239
+ mount: false,
1240
+ watch: false,
1241
+ };
1242
+ let _names = {
1243
+ mount: new Set(),
1244
+ unMount: new Set(),
1245
+ array: new Set(),
1246
+ watch: new Set(),
1247
+ };
1248
+ let delayErrorCallback;
1249
+ let timer = 0;
1250
+ const _proxyFormState = {
1251
+ isDirty: false,
1252
+ dirtyFields: false,
1253
+ touchedFields: false,
1254
+ isValidating: false,
1255
+ isValid: false,
1256
+ errors: false,
1257
+ };
1258
+ const _subjects = {
1259
+ values: createSubject(),
1260
+ array: createSubject(),
1261
+ state: createSubject(),
1262
+ };
1263
+ const shouldCaptureDirtyFields = props.resetOptions && props.resetOptions.keepDirtyValues;
1264
+ const validationModeBeforeSubmit = getValidationModes(_options.mode);
1265
+ const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
1266
+ const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
1267
+ const debounce = (callback) => (wait) => {
1268
+ clearTimeout(timer);
1269
+ timer = setTimeout(callback, wait);
1270
+ };
1271
+ const _updateValid = async (shouldUpdateValid) => {
1272
+ if (_proxyFormState.isValid || shouldUpdateValid) {
1273
+ const isValid = _options.resolver
1274
+ ? isEmptyObject((await _executeSchema()).errors)
1275
+ : await executeBuiltInValidation(_fields, true);
1276
+ if (isValid !== _formState.isValid) {
1277
+ _subjects.state.next({
1278
+ isValid,
1279
+ });
1280
+ }
1281
+ }
1282
+ };
1283
+ const _updateIsValidating = (value) => _proxyFormState.isValidating &&
1284
+ _subjects.state.next({
1285
+ isValidating: value,
1286
+ });
1287
+ const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
1288
+ if (args && method) {
1289
+ _state.action = true;
1290
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
1291
+ const fieldValues = method(get(_fields, name), args.argA, args.argB);
1292
+ shouldSetValues && set(_fields, name, fieldValues);
1293
+ }
1294
+ if (shouldUpdateFieldsAndState &&
1295
+ Array.isArray(get(_formState.errors, name))) {
1296
+ const errors = method(get(_formState.errors, name), args.argA, args.argB);
1297
+ shouldSetValues && set(_formState.errors, name, errors);
1298
+ unsetEmptyArray(_formState.errors, name);
1299
+ }
1300
+ if (_proxyFormState.touchedFields &&
1301
+ shouldUpdateFieldsAndState &&
1302
+ Array.isArray(get(_formState.touchedFields, name))) {
1303
+ const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
1304
+ shouldSetValues && set(_formState.touchedFields, name, touchedFields);
1305
+ }
1306
+ if (_proxyFormState.dirtyFields) {
1307
+ _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
1308
+ }
1309
+ _subjects.state.next({
1310
+ name,
1311
+ isDirty: _getDirty(name, values),
1312
+ dirtyFields: _formState.dirtyFields,
1313
+ errors: _formState.errors,
1314
+ isValid: _formState.isValid,
1315
+ });
1316
+ }
1317
+ else {
1318
+ set(_formValues, name, values);
1319
+ }
1320
+ };
1321
+ const updateErrors = (name, error) => {
1322
+ set(_formState.errors, name, error);
1323
+ _subjects.state.next({
1324
+ errors: _formState.errors,
1325
+ });
2358
1326
  };
2359
- var requestConfigParams = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null;
2360
- return axiosInstance[method.toLowerCase()](url, payload, requestConfigParams).then(function (res) {
2361
- onSuccess(res);
2362
- return res;
2363
- }).catch(function (err) {
2364
- onFailed(err);
2365
- return err;
1327
+ const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
1328
+ const field = get(_fields, name);
1329
+ if (field) {
1330
+ const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
1331
+ isUndefined(defaultValue) ||
1332
+ (ref && ref.defaultChecked) ||
1333
+ shouldSkipSetValueAs
1334
+ ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))
1335
+ : setFieldValue(name, defaultValue);
1336
+ _state.mount && _updateValid();
1337
+ }
1338
+ };
1339
+ const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
1340
+ let shouldUpdateField = false;
1341
+ let isPreviousDirty = false;
1342
+ const output = {
1343
+ name,
1344
+ };
1345
+ if (!isBlurEvent || shouldDirty) {
1346
+ if (_proxyFormState.isDirty) {
1347
+ isPreviousDirty = _formState.isDirty;
1348
+ _formState.isDirty = output.isDirty = _getDirty();
1349
+ shouldUpdateField = isPreviousDirty !== output.isDirty;
1350
+ }
1351
+ const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
1352
+ isPreviousDirty = get(_formState.dirtyFields, name);
1353
+ isCurrentFieldPristine
1354
+ ? unset(_formState.dirtyFields, name)
1355
+ : set(_formState.dirtyFields, name, true);
1356
+ output.dirtyFields = _formState.dirtyFields;
1357
+ shouldUpdateField =
1358
+ shouldUpdateField ||
1359
+ (_proxyFormState.dirtyFields &&
1360
+ isPreviousDirty !== !isCurrentFieldPristine);
1361
+ }
1362
+ if (isBlurEvent) {
1363
+ const isPreviousFieldTouched = get(_formState.touchedFields, name);
1364
+ if (!isPreviousFieldTouched) {
1365
+ set(_formState.touchedFields, name, isBlurEvent);
1366
+ output.touchedFields = _formState.touchedFields;
1367
+ shouldUpdateField =
1368
+ shouldUpdateField ||
1369
+ (_proxyFormState.touchedFields &&
1370
+ isPreviousFieldTouched !== isBlurEvent);
1371
+ }
1372
+ }
1373
+ shouldUpdateField && shouldRender && _subjects.state.next(output);
1374
+ return shouldUpdateField ? output : {};
1375
+ };
1376
+ const shouldRenderByError = (name, isValid, error, fieldState) => {
1377
+ const previousFieldError = get(_formState.errors, name);
1378
+ const shouldUpdateValid = _proxyFormState.isValid &&
1379
+ isBoolean(isValid) &&
1380
+ _formState.isValid !== isValid;
1381
+ if (props.delayError && error) {
1382
+ delayErrorCallback = debounce(() => updateErrors(name, error));
1383
+ delayErrorCallback(props.delayError);
1384
+ }
1385
+ else {
1386
+ clearTimeout(timer);
1387
+ delayErrorCallback = null;
1388
+ error
1389
+ ? set(_formState.errors, name, error)
1390
+ : unset(_formState.errors, name);
1391
+ }
1392
+ if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||
1393
+ !isEmptyObject(fieldState) ||
1394
+ shouldUpdateValid) {
1395
+ const updatedFormState = {
1396
+ ...fieldState,
1397
+ ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
1398
+ errors: _formState.errors,
1399
+ name,
1400
+ };
1401
+ _formState = {
1402
+ ..._formState,
1403
+ ...updatedFormState,
1404
+ };
1405
+ _subjects.state.next(updatedFormState);
1406
+ }
1407
+ _updateIsValidating(false);
1408
+ };
1409
+ const _executeSchema = async (name) => _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1410
+ const executeSchemaAndUpdateState = async (names) => {
1411
+ const { errors } = await _executeSchema(names);
1412
+ if (names) {
1413
+ for (const name of names) {
1414
+ const error = get(errors, name);
1415
+ error
1416
+ ? set(_formState.errors, name, error)
1417
+ : unset(_formState.errors, name);
1418
+ }
1419
+ }
1420
+ else {
1421
+ _formState.errors = errors;
1422
+ }
1423
+ return errors;
1424
+ };
1425
+ const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
1426
+ valid: true,
1427
+ }) => {
1428
+ for (const name in fields) {
1429
+ const field = fields[name];
1430
+ if (field) {
1431
+ const { _f, ...fieldValue } = field;
1432
+ if (_f) {
1433
+ const isFieldArrayRoot = _names.array.has(_f.name);
1434
+ const fieldError = await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
1435
+ if (fieldError[_f.name]) {
1436
+ context.valid = false;
1437
+ if (shouldOnlyCheckValid) {
1438
+ break;
1439
+ }
1440
+ }
1441
+ !shouldOnlyCheckValid &&
1442
+ (get(fieldError, _f.name)
1443
+ ? isFieldArrayRoot
1444
+ ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)
1445
+ : set(_formState.errors, _f.name, fieldError[_f.name])
1446
+ : unset(_formState.errors, _f.name));
1447
+ }
1448
+ fieldValue &&
1449
+ (await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context));
1450
+ }
1451
+ }
1452
+ return context.valid;
1453
+ };
1454
+ const _removeUnmounted = () => {
1455
+ for (const name of _names.unMount) {
1456
+ const field = get(_fields, name);
1457
+ field &&
1458
+ (field._f.refs
1459
+ ? field._f.refs.every((ref) => !live(ref))
1460
+ : !live(field._f.ref)) &&
1461
+ unregister(name);
1462
+ }
1463
+ _names.unMount = new Set();
1464
+ };
1465
+ const _getDirty = (name, data) => (name && data && set(_formValues, name, data),
1466
+ !deepEqual(getValues(), _defaultValues));
1467
+ const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
1468
+ ...(_state.mount
1469
+ ? _formValues
1470
+ : isUndefined(defaultValue)
1471
+ ? _defaultValues
1472
+ : isString(names)
1473
+ ? { [names]: defaultValue }
1474
+ : defaultValue),
1475
+ }, isGlobal, defaultValue);
1476
+ const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
1477
+ const setFieldValue = (name, value, options = {}) => {
1478
+ const field = get(_fields, name);
1479
+ let fieldValue = value;
1480
+ if (field) {
1481
+ const fieldReference = field._f;
1482
+ if (fieldReference) {
1483
+ !fieldReference.disabled &&
1484
+ set(_formValues, name, getFieldValueAs(value, fieldReference));
1485
+ fieldValue =
1486
+ isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)
1487
+ ? ''
1488
+ : value;
1489
+ if (isMultipleSelect(fieldReference.ref)) {
1490
+ [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));
1491
+ }
1492
+ else if (fieldReference.refs) {
1493
+ if (isCheckBoxInput(fieldReference.ref)) {
1494
+ fieldReference.refs.length > 1
1495
+ ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) &&
1496
+ (checkboxRef.checked = Array.isArray(fieldValue)
1497
+ ? !!fieldValue.find((data) => data === checkboxRef.value)
1498
+ : fieldValue === checkboxRef.value))
1499
+ : fieldReference.refs[0] &&
1500
+ (fieldReference.refs[0].checked = !!fieldValue);
1501
+ }
1502
+ else {
1503
+ fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));
1504
+ }
1505
+ }
1506
+ else if (isFileInput(fieldReference.ref)) {
1507
+ fieldReference.ref.value = '';
1508
+ }
1509
+ else {
1510
+ fieldReference.ref.value = fieldValue;
1511
+ if (!fieldReference.ref.type) {
1512
+ _subjects.values.next({
1513
+ name,
1514
+ values: { ..._formValues },
1515
+ });
1516
+ }
1517
+ }
1518
+ }
1519
+ }
1520
+ (options.shouldDirty || options.shouldTouch) &&
1521
+ updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
1522
+ options.shouldValidate && trigger(name);
1523
+ };
1524
+ const setValues = (name, value, options) => {
1525
+ for (const fieldKey in value) {
1526
+ const fieldValue = value[fieldKey];
1527
+ const fieldName = `${name}.${fieldKey}`;
1528
+ const field = get(_fields, fieldName);
1529
+ (_names.array.has(name) ||
1530
+ !isPrimitive(fieldValue) ||
1531
+ (field && !field._f)) &&
1532
+ !isDateObject(fieldValue)
1533
+ ? setValues(fieldName, fieldValue, options)
1534
+ : setFieldValue(fieldName, fieldValue, options);
1535
+ }
1536
+ };
1537
+ const setValue = (name, value, options = {}) => {
1538
+ const field = get(_fields, name);
1539
+ const isFieldArray = _names.array.has(name);
1540
+ const cloneValue = cloneObject(value);
1541
+ set(_formValues, name, cloneValue);
1542
+ if (isFieldArray) {
1543
+ _subjects.array.next({
1544
+ name,
1545
+ values: { ..._formValues },
1546
+ });
1547
+ if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) &&
1548
+ options.shouldDirty) {
1549
+ _subjects.state.next({
1550
+ name,
1551
+ dirtyFields: getDirtyFields(_defaultValues, _formValues),
1552
+ isDirty: _getDirty(name, cloneValue),
1553
+ });
1554
+ }
1555
+ }
1556
+ else {
1557
+ field && !field._f && !isNullOrUndefined(cloneValue)
1558
+ ? setValues(name, cloneValue, options)
1559
+ : setFieldValue(name, cloneValue, options);
1560
+ }
1561
+ isWatched(name, _names) && _subjects.state.next({ ..._formState });
1562
+ _subjects.values.next({
1563
+ name,
1564
+ values: { ..._formValues },
1565
+ });
1566
+ !_state.mount && flushRootRender();
1567
+ };
1568
+ const onChange = async (event) => {
1569
+ const target = event.target;
1570
+ let name = target.name;
1571
+ let isFieldValueUpdated = true;
1572
+ const field = get(_fields, name);
1573
+ const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
1574
+ if (field) {
1575
+ let error;
1576
+ let isValid;
1577
+ const fieldValue = getCurrentFieldValue();
1578
+ const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
1579
+ const shouldSkipValidation = (!hasValidation(field._f) &&
1580
+ !_options.resolver &&
1581
+ !get(_formState.errors, name) &&
1582
+ !field._f.deps) ||
1583
+ skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
1584
+ const watched = isWatched(name, _names, isBlurEvent);
1585
+ set(_formValues, name, fieldValue);
1586
+ if (isBlurEvent) {
1587
+ field._f.onBlur && field._f.onBlur(event);
1588
+ delayErrorCallback && delayErrorCallback(0);
1589
+ }
1590
+ else if (field._f.onChange) {
1591
+ field._f.onChange(event);
1592
+ }
1593
+ const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
1594
+ const shouldRender = !isEmptyObject(fieldState) || watched;
1595
+ !isBlurEvent &&
1596
+ _subjects.values.next({
1597
+ name,
1598
+ type: event.type,
1599
+ values: { ..._formValues },
1600
+ });
1601
+ if (shouldSkipValidation) {
1602
+ _proxyFormState.isValid && _updateValid();
1603
+ return (shouldRender &&
1604
+ _subjects.state.next({ name, ...(watched ? {} : fieldState) }));
1605
+ }
1606
+ !isBlurEvent && watched && _subjects.state.next({ ..._formState });
1607
+ _updateIsValidating(true);
1608
+ if (_options.resolver) {
1609
+ const { errors } = await _executeSchema([name]);
1610
+ const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
1611
+ const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
1612
+ error = errorLookupResult.error;
1613
+ name = errorLookupResult.name;
1614
+ isValid = isEmptyObject(errors);
1615
+ }
1616
+ else {
1617
+ error = (await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
1618
+ isFieldValueUpdated =
1619
+ isNaN(fieldValue) ||
1620
+ fieldValue === get(_formValues, name, fieldValue);
1621
+ if (isFieldValueUpdated) {
1622
+ if (error) {
1623
+ isValid = false;
1624
+ }
1625
+ else if (_proxyFormState.isValid) {
1626
+ isValid = await executeBuiltInValidation(_fields, true);
1627
+ }
1628
+ }
1629
+ }
1630
+ if (isFieldValueUpdated) {
1631
+ field._f.deps &&
1632
+ trigger(field._f.deps);
1633
+ shouldRenderByError(name, isValid, error, fieldState);
1634
+ }
1635
+ }
1636
+ };
1637
+ const trigger = async (name, options = {}) => {
1638
+ let isValid;
1639
+ let validationResult;
1640
+ const fieldNames = convertToArrayPayload(name);
1641
+ _updateIsValidating(true);
1642
+ if (_options.resolver) {
1643
+ const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
1644
+ isValid = isEmptyObject(errors);
1645
+ validationResult = name
1646
+ ? !fieldNames.some((name) => get(errors, name))
1647
+ : isValid;
1648
+ }
1649
+ else if (name) {
1650
+ validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
1651
+ const field = get(_fields, fieldName);
1652
+ return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
1653
+ }))).every(Boolean);
1654
+ !(!validationResult && !_formState.isValid) && _updateValid();
1655
+ }
1656
+ else {
1657
+ validationResult = isValid = await executeBuiltInValidation(_fields);
1658
+ }
1659
+ _subjects.state.next({
1660
+ ...(!isString(name) ||
1661
+ (_proxyFormState.isValid && isValid !== _formState.isValid)
1662
+ ? {}
1663
+ : { name }),
1664
+ ...(_options.resolver || !name ? { isValid } : {}),
1665
+ errors: _formState.errors,
1666
+ isValidating: false,
1667
+ });
1668
+ options.shouldFocus &&
1669
+ !validationResult &&
1670
+ focusFieldBy(_fields, (key) => key && get(_formState.errors, key), name ? fieldNames : _names.mount);
1671
+ return validationResult;
1672
+ };
1673
+ const getValues = (fieldNames) => {
1674
+ const values = {
1675
+ ..._defaultValues,
1676
+ ...(_state.mount ? _formValues : {}),
1677
+ };
1678
+ return isUndefined(fieldNames)
1679
+ ? values
1680
+ : isString(fieldNames)
1681
+ ? get(values, fieldNames)
1682
+ : fieldNames.map((name) => get(values, name));
1683
+ };
1684
+ const getFieldState = (name, formState) => ({
1685
+ invalid: !!get((formState || _formState).errors, name),
1686
+ isDirty: !!get((formState || _formState).dirtyFields, name),
1687
+ isTouched: !!get((formState || _formState).touchedFields, name),
1688
+ error: get((formState || _formState).errors, name),
2366
1689
  });
1690
+ const clearErrors = (name) => {
1691
+ name &&
1692
+ convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
1693
+ _subjects.state.next({
1694
+ errors: name ? _formState.errors : {},
1695
+ });
1696
+ };
1697
+ const setError = (name, error, options) => {
1698
+ const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
1699
+ set(_formState.errors, name, {
1700
+ ...error,
1701
+ ref,
1702
+ });
1703
+ _subjects.state.next({
1704
+ name,
1705
+ errors: _formState.errors,
1706
+ isValid: false,
1707
+ });
1708
+ options && options.shouldFocus && ref && ref.focus && ref.focus();
1709
+ };
1710
+ const watch = (name, defaultValue) => isFunction(name)
1711
+ ? _subjects.values.subscribe({
1712
+ next: (payload) => name(_getWatch(undefined, defaultValue), payload),
1713
+ })
1714
+ : _getWatch(name, defaultValue, true);
1715
+ const unregister = (name, options = {}) => {
1716
+ for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
1717
+ _names.mount.delete(fieldName);
1718
+ _names.array.delete(fieldName);
1719
+ if (!options.keepValue) {
1720
+ unset(_fields, fieldName);
1721
+ unset(_formValues, fieldName);
1722
+ }
1723
+ !options.keepError && unset(_formState.errors, fieldName);
1724
+ !options.keepDirty && unset(_formState.dirtyFields, fieldName);
1725
+ !options.keepTouched && unset(_formState.touchedFields, fieldName);
1726
+ !_options.shouldUnregister &&
1727
+ !options.keepDefaultValue &&
1728
+ unset(_defaultValues, fieldName);
1729
+ }
1730
+ _subjects.values.next({
1731
+ values: { ..._formValues },
1732
+ });
1733
+ _subjects.state.next({
1734
+ ..._formState,
1735
+ ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),
1736
+ });
1737
+ !options.keepIsValid && _updateValid();
1738
+ };
1739
+ const _updateDisabledField = ({ disabled, name, field, fields, }) => {
1740
+ if (isBoolean(disabled)) {
1741
+ const value = disabled
1742
+ ? undefined
1743
+ : get(_formValues, name, getFieldValue(field ? field._f : get(fields, name)._f));
1744
+ set(_formValues, name, value);
1745
+ updateTouchAndDirty(name, value, false, false, true);
1746
+ }
1747
+ };
1748
+ const register = (name, options = {}) => {
1749
+ let field = get(_fields, name);
1750
+ const disabledIsDefined = isBoolean(options.disabled);
1751
+ set(_fields, name, {
1752
+ ...(field || {}),
1753
+ _f: {
1754
+ ...(field && field._f ? field._f : { ref: { name } }),
1755
+ name,
1756
+ mount: true,
1757
+ ...options,
1758
+ },
1759
+ });
1760
+ _names.mount.add(name);
1761
+ if (field) {
1762
+ _updateDisabledField({
1763
+ field,
1764
+ disabled: options.disabled,
1765
+ name,
1766
+ });
1767
+ }
1768
+ else {
1769
+ updateValidAndValue(name, true, options.value);
1770
+ }
1771
+ return {
1772
+ ...(disabledIsDefined ? { disabled: options.disabled } : {}),
1773
+ ...(_options.progressive
1774
+ ? {
1775
+ required: !!options.required,
1776
+ min: getRuleValue(options.min),
1777
+ max: getRuleValue(options.max),
1778
+ minLength: getRuleValue(options.minLength),
1779
+ maxLength: getRuleValue(options.maxLength),
1780
+ pattern: getRuleValue(options.pattern),
1781
+ }
1782
+ : {}),
1783
+ name,
1784
+ onChange,
1785
+ onBlur: onChange,
1786
+ ref: (ref) => {
1787
+ if (ref) {
1788
+ register(name, options);
1789
+ field = get(_fields, name);
1790
+ const fieldRef = isUndefined(ref.value)
1791
+ ? ref.querySelectorAll
1792
+ ? ref.querySelectorAll('input,select,textarea')[0] || ref
1793
+ : ref
1794
+ : ref;
1795
+ const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
1796
+ const refs = field._f.refs || [];
1797
+ if (radioOrCheckbox
1798
+ ? refs.find((option) => option === fieldRef)
1799
+ : fieldRef === field._f.ref) {
1800
+ return;
1801
+ }
1802
+ set(_fields, name, {
1803
+ _f: {
1804
+ ...field._f,
1805
+ ...(radioOrCheckbox
1806
+ ? {
1807
+ refs: [
1808
+ ...refs.filter(live),
1809
+ fieldRef,
1810
+ ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
1811
+ ],
1812
+ ref: { type: fieldRef.type, name },
1813
+ }
1814
+ : { ref: fieldRef }),
1815
+ },
1816
+ });
1817
+ updateValidAndValue(name, false, undefined, fieldRef);
1818
+ }
1819
+ else {
1820
+ field = get(_fields, name, {});
1821
+ if (field._f) {
1822
+ field._f.mount = false;
1823
+ }
1824
+ (_options.shouldUnregister || options.shouldUnregister) &&
1825
+ !(isNameInFieldArray(_names.array, name) && _state.action) &&
1826
+ _names.unMount.add(name);
1827
+ }
1828
+ },
1829
+ };
1830
+ };
1831
+ const _focusError = () => _options.shouldFocusError &&
1832
+ focusFieldBy(_fields, (key) => key && get(_formState.errors, key), _names.mount);
1833
+ const handleSubmit = (onValid, onInvalid) => async (e) => {
1834
+ if (e) {
1835
+ e.preventDefault && e.preventDefault();
1836
+ e.persist && e.persist();
1837
+ }
1838
+ let fieldValues = cloneObject(_formValues);
1839
+ _subjects.state.next({
1840
+ isSubmitting: true,
1841
+ });
1842
+ if (_options.resolver) {
1843
+ const { errors, values } = await _executeSchema();
1844
+ _formState.errors = errors;
1845
+ fieldValues = values;
1846
+ }
1847
+ else {
1848
+ await executeBuiltInValidation(_fields);
1849
+ }
1850
+ unset(_formState.errors, 'root');
1851
+ if (isEmptyObject(_formState.errors)) {
1852
+ _subjects.state.next({
1853
+ errors: {},
1854
+ });
1855
+ await onValid(fieldValues, e);
1856
+ }
1857
+ else {
1858
+ if (onInvalid) {
1859
+ await onInvalid({ ..._formState.errors }, e);
1860
+ }
1861
+ _focusError();
1862
+ setTimeout(_focusError);
1863
+ }
1864
+ _subjects.state.next({
1865
+ isSubmitted: true,
1866
+ isSubmitting: false,
1867
+ isSubmitSuccessful: isEmptyObject(_formState.errors),
1868
+ submitCount: _formState.submitCount + 1,
1869
+ errors: _formState.errors,
1870
+ });
1871
+ };
1872
+ const resetField = (name, options = {}) => {
1873
+ if (get(_fields, name)) {
1874
+ if (isUndefined(options.defaultValue)) {
1875
+ setValue(name, get(_defaultValues, name));
1876
+ }
1877
+ else {
1878
+ setValue(name, options.defaultValue);
1879
+ set(_defaultValues, name, options.defaultValue);
1880
+ }
1881
+ if (!options.keepTouched) {
1882
+ unset(_formState.touchedFields, name);
1883
+ }
1884
+ if (!options.keepDirty) {
1885
+ unset(_formState.dirtyFields, name);
1886
+ _formState.isDirty = options.defaultValue
1887
+ ? _getDirty(name, get(_defaultValues, name))
1888
+ : _getDirty();
1889
+ }
1890
+ if (!options.keepError) {
1891
+ unset(_formState.errors, name);
1892
+ _proxyFormState.isValid && _updateValid();
1893
+ }
1894
+ _subjects.state.next({ ..._formState });
1895
+ }
1896
+ };
1897
+ const _reset = (formValues, keepStateOptions = {}) => {
1898
+ const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
1899
+ const cloneUpdatedValues = cloneObject(updatedValues);
1900
+ const values = formValues && !isEmptyObject(formValues)
1901
+ ? cloneUpdatedValues
1902
+ : _defaultValues;
1903
+ if (!keepStateOptions.keepDefaultValues) {
1904
+ _defaultValues = updatedValues;
1905
+ }
1906
+ if (!keepStateOptions.keepValues) {
1907
+ if (keepStateOptions.keepDirtyValues || shouldCaptureDirtyFields) {
1908
+ for (const fieldName of _names.mount) {
1909
+ get(_formState.dirtyFields, fieldName)
1910
+ ? set(values, fieldName, get(_formValues, fieldName))
1911
+ : setValue(fieldName, get(values, fieldName));
1912
+ }
1913
+ }
1914
+ else {
1915
+ if (isWeb && isUndefined(formValues)) {
1916
+ for (const name of _names.mount) {
1917
+ const field = get(_fields, name);
1918
+ if (field && field._f) {
1919
+ const fieldReference = Array.isArray(field._f.refs)
1920
+ ? field._f.refs[0]
1921
+ : field._f.ref;
1922
+ if (isHTMLElement(fieldReference)) {
1923
+ const form = fieldReference.closest('form');
1924
+ if (form) {
1925
+ form.reset();
1926
+ break;
1927
+ }
1928
+ }
1929
+ }
1930
+ }
1931
+ }
1932
+ _fields = {};
1933
+ }
1934
+ _formValues = props.shouldUnregister
1935
+ ? keepStateOptions.keepDefaultValues
1936
+ ? cloneObject(_defaultValues)
1937
+ : {}
1938
+ : cloneObject(values);
1939
+ _subjects.array.next({
1940
+ values: { ...values },
1941
+ });
1942
+ _subjects.values.next({
1943
+ values: { ...values },
1944
+ });
1945
+ }
1946
+ _names = {
1947
+ mount: new Set(),
1948
+ unMount: new Set(),
1949
+ array: new Set(),
1950
+ watch: new Set(),
1951
+ watchAll: false,
1952
+ focus: '',
1953
+ };
1954
+ !_state.mount && flushRootRender();
1955
+ _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid;
1956
+ _state.watch = !!props.shouldUnregister;
1957
+ _subjects.state.next({
1958
+ submitCount: keepStateOptions.keepSubmitCount
1959
+ ? _formState.submitCount
1960
+ : 0,
1961
+ isDirty: keepStateOptions.keepDirty
1962
+ ? _formState.isDirty
1963
+ : !!(keepStateOptions.keepDefaultValues &&
1964
+ !deepEqual(formValues, _defaultValues)),
1965
+ isSubmitted: keepStateOptions.keepIsSubmitted
1966
+ ? _formState.isSubmitted
1967
+ : false,
1968
+ dirtyFields: keepStateOptions.keepDirtyValues
1969
+ ? _formState.dirtyFields
1970
+ : keepStateOptions.keepDefaultValues && formValues
1971
+ ? getDirtyFields(_defaultValues, formValues)
1972
+ : {},
1973
+ touchedFields: keepStateOptions.keepTouched
1974
+ ? _formState.touchedFields
1975
+ : {},
1976
+ errors: keepStateOptions.keepErrors ? _formState.errors : {},
1977
+ isSubmitting: false,
1978
+ isSubmitSuccessful: false,
1979
+ });
1980
+ };
1981
+ const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)
1982
+ ? formValues(_formValues)
1983
+ : formValues, keepStateOptions);
1984
+ const setFocus = (name, options = {}) => {
1985
+ const field = get(_fields, name);
1986
+ const fieldReference = field && field._f;
1987
+ if (fieldReference) {
1988
+ const fieldRef = fieldReference.refs
1989
+ ? fieldReference.refs[0]
1990
+ : fieldReference.ref;
1991
+ if (fieldRef.focus) {
1992
+ fieldRef.focus();
1993
+ options.shouldSelect && fieldRef.select();
1994
+ }
1995
+ }
1996
+ };
1997
+ const _updateFormState = (updatedFormState) => {
1998
+ _formState = {
1999
+ ..._formState,
2000
+ ...updatedFormState,
2001
+ };
2002
+ };
2003
+ const _resetDefaultValues = () => isFunction(_options.defaultValues) &&
2004
+ _options.defaultValues().then((values) => {
2005
+ reset(values, _options.resetOptions);
2006
+ _subjects.state.next({
2007
+ isLoading: false,
2008
+ });
2009
+ });
2010
+ return {
2011
+ control: {
2012
+ register,
2013
+ unregister,
2014
+ getFieldState,
2015
+ handleSubmit,
2016
+ setError,
2017
+ _executeSchema,
2018
+ _getWatch,
2019
+ _getDirty,
2020
+ _updateValid,
2021
+ _removeUnmounted,
2022
+ _updateFieldArray,
2023
+ _updateDisabledField,
2024
+ _getFieldArray,
2025
+ _reset,
2026
+ _resetDefaultValues,
2027
+ _updateFormState,
2028
+ _subjects,
2029
+ _proxyFormState,
2030
+ get _fields() {
2031
+ return _fields;
2032
+ },
2033
+ get _formValues() {
2034
+ return _formValues;
2035
+ },
2036
+ get _state() {
2037
+ return _state;
2038
+ },
2039
+ set _state(value) {
2040
+ _state = value;
2041
+ },
2042
+ get _defaultValues() {
2043
+ return _defaultValues;
2044
+ },
2045
+ get _names() {
2046
+ return _names;
2047
+ },
2048
+ set _names(value) {
2049
+ _names = value;
2050
+ },
2051
+ get _formState() {
2052
+ return _formState;
2053
+ },
2054
+ set _formState(value) {
2055
+ _formState = value;
2056
+ },
2057
+ get _options() {
2058
+ return _options;
2059
+ },
2060
+ set _options(value) {
2061
+ _options = {
2062
+ ..._options,
2063
+ ...value,
2064
+ };
2065
+ },
2066
+ },
2067
+ trigger,
2068
+ register,
2069
+ handleSubmit,
2070
+ watch,
2071
+ setValue,
2072
+ getValues,
2073
+ reset,
2074
+ resetField,
2075
+ clearErrors,
2076
+ unregister,
2077
+ setError,
2078
+ setFocus,
2079
+ getFieldState,
2080
+ };
2081
+ }
2082
+
2083
+ /**
2084
+ * Custom hook to manage the entire form.
2085
+ *
2086
+ * @remarks
2087
+ * [API](https://react-hook-form.com/docs/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
2088
+ *
2089
+ * @param props - form configuration and validation parameters.
2090
+ *
2091
+ * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
2092
+ *
2093
+ * @example
2094
+ * ```tsx
2095
+ * function App() {
2096
+ * const { register, handleSubmit, watch, formState: { errors } } = useForm();
2097
+ * const onSubmit = data => console.log(data);
2098
+ *
2099
+ * console.log(watch("example"));
2100
+ *
2101
+ * return (
2102
+ * <form onSubmit={handleSubmit(onSubmit)}>
2103
+ * <input defaultValue="test" {...register("example")} />
2104
+ * <input {...register("exampleRequired", { required: true })} />
2105
+ * {errors.exampleRequired && <span>This field is required</span>}
2106
+ * <button>Submit</button>
2107
+ * </form>
2108
+ * );
2109
+ * }
2110
+ * ```
2111
+ */
2112
+ function useForm(props = {}) {
2113
+ const _formControl = React.useRef();
2114
+ const _values = React.useRef();
2115
+ const [formState, updateFormState] = React.useState({
2116
+ isDirty: false,
2117
+ isValidating: false,
2118
+ isLoading: isFunction(props.defaultValues),
2119
+ isSubmitted: false,
2120
+ isSubmitting: false,
2121
+ isSubmitSuccessful: false,
2122
+ isValid: false,
2123
+ submitCount: 0,
2124
+ dirtyFields: {},
2125
+ touchedFields: {},
2126
+ errors: {},
2127
+ defaultValues: isFunction(props.defaultValues)
2128
+ ? undefined
2129
+ : props.defaultValues,
2130
+ });
2131
+ if (!_formControl.current) {
2132
+ _formControl.current = {
2133
+ ...createFormControl(props, () => updateFormState((formState) => ({ ...formState }))),
2134
+ formState,
2135
+ };
2136
+ }
2137
+ const control = _formControl.current.control;
2138
+ control._options = props;
2139
+ useSubscribe({
2140
+ subject: control._subjects.state,
2141
+ next: (value) => {
2142
+ if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
2143
+ updateFormState({ ...control._formState });
2144
+ }
2145
+ },
2146
+ });
2147
+ React.useEffect(() => {
2148
+ if (props.values && !deepEqual(props.values, _values.current)) {
2149
+ control._reset(props.values, control._options.resetOptions);
2150
+ _values.current = props.values;
2151
+ }
2152
+ else {
2153
+ control._resetDefaultValues();
2154
+ }
2155
+ }, [props.values, control]);
2156
+ React.useEffect(() => {
2157
+ if (!control._state.mount) {
2158
+ control._updateValid();
2159
+ control._state.mount = true;
2160
+ }
2161
+ if (control._state.watch) {
2162
+ control._state.watch = false;
2163
+ control._subjects.state.next({ ...control._formState });
2164
+ }
2165
+ control._removeUnmounted();
2166
+ });
2167
+ _formControl.current.formState = getProxyFormState(formState, control);
2168
+ return _formControl.current;
2169
+ }
2170
+
2171
+ var theme = {
2172
+ breakpoints: ['40em', '52em', '64em'],
2173
+ space: ['0px', '4px', '8px', '16px', '32px', '64px', '128px', '256px', '512px'],
2174
+ fontSizes: ['12px', '14px', '16px', '20px', '24px', '32px', '48px', '64px', '72px'],
2175
+ marginPaddings: ['0.5rem', '1rem', '1.5rem', '2rem', '2.5rem', '3rem', '3.5rem', '4rem', '4.5rem', '5rem', '5.5rem', '6rem'],
2176
+ letterSpacings: ['-0.5px', '0px', '+0.5px'],
2177
+ radii: ['0px', '2px', '4px', '8px'],
2178
+ borderRadius: '6px',
2179
+ colors: {
2180
+ primary: '#000',
2181
+ base: '#4e4949',
2182
+ baseLt: '#817c7c',
2183
+ borderColor: '#d8d8d8',
2184
+ ntrlMin: '#fff',
2185
+ ntrlMinTen: '#e6e6e6',
2186
+ gray: '#efefef',
2187
+ darkerGray: '#454141'
2188
+ },
2189
+ rareStepColors: {
2190
+ primary: '#202b58',
2191
+ secondary: '#ef5c2d',
2192
+ ntrlMin: '#ffffff',
2193
+ ntrl40: '#f4f4f4',
2194
+ ntrl50: '#808080',
2195
+ ntrl60: '#e8e8e8',
2196
+ ntrl70: '#252525',
2197
+ ntrlMax: '#000000'
2198
+ },
2199
+ rareStepFontWeights: {
2200
+ normal: 400,
2201
+ medium: 500,
2202
+ semiBold: 600,
2203
+ bold: 700
2204
+ },
2205
+ rareStepFontSize: {
2206
+ h1: '36px',
2207
+ h2: '30px',
2208
+ h3: '24px',
2209
+ h4: '20px',
2210
+ h5: '16px',
2211
+ h6: '14px',
2212
+ footerTitle: '16px'
2213
+ },
2214
+ rareStepPageSizes: {
2215
+ mobile: '500px',
2216
+ tablet: '768px',
2217
+ desktop: '992px',
2218
+ screenl: '1280px',
2219
+ screenxl: '1680px',
2220
+ screenxxl: '1920px',
2221
+ container: '1600px'
2222
+ }
2223
+ };
2224
+
2225
+ var themed = (function (Component) {
2226
+ return /*#__PURE__*/forwardRef(function (props, ref) {
2227
+ return /*#__PURE__*/React.createElement(ThemeProvider, {
2228
+ theme: theme
2229
+ }, /*#__PURE__*/React.createElement(Component, _extends({}, props, {
2230
+ ref: ref
2231
+ })));
2367
2232
  });
2368
-
2369
- /** @format */
2370
- var method = {
2371
- DELETE: 'DELETE',
2372
- POST: 'POST',
2373
- GET: 'GET'
2233
+ });
2234
+
2235
+ var _templateObject;
2236
+ var RadioButtonLabel = styled.label(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n display: flex;\n margin-bottom: ", ";\n margin-right: ", ";\n"])), function (props) {
2237
+ return props.theme.marginPaddings[0];
2238
+ }, function (props) {
2239
+ return props.theme.marginPaddings[0];
2240
+ });
2241
+
2242
+ var _templateObject$1;
2243
+ var RadioButtonText = styled.div(_templateObject$1 || (_templateObject$1 = _taggedTemplateLiteral(["\n display: flex;\n align-items: center;\n"])));
2244
+
2245
+ var _templateObject$2;
2246
+ var RadioButtonCircle = styled.div(_templateObject$2 || (_templateObject$2 = _taggedTemplateLiteral(["\n height: 20px;\n width: 20px;\n border-radius: 50%;\n margin-right: 5px;\n border: 1px solid ", ";\n display: flex;\n"])), function (props) {
2247
+ return props.theme.colors.base;
2248
+ });
2249
+
2250
+ var _templateObject$3;
2251
+ var RadioButtonCircleInner = styled.div(_templateObject$3 || (_templateObject$3 = _taggedTemplateLiteral(["\n height: 8px;\n width: 8px;\n border-radius: 50%;\n margin: auto;\n"])));
2252
+
2253
+ var _templateObject$4;
2254
+ var RadioButtonInput = styled.input(_templateObject$4 || (_templateObject$4 = _taggedTemplateLiteral(["\n display: none;\n :checked ~ ", " {\n ", " {\n background-color: ", ";\n }\n }\n"])), RadioButtonCircle, RadioButtonCircleInner, function (props) {
2255
+ return props.theme.colors.base;
2256
+ });
2257
+
2258
+ var _excluded = ["ref"];
2259
+
2260
+ var _templateObject$5, _templateObject2;
2261
+ var OptionsRow = styled.div(_templateObject$5 || (_templateObject$5 = _taggedTemplateLiteral(["\n display: flex;\n flex-wrap: nowrap;\n flex-direction: row;\n"])));
2262
+ var Options = styled.div(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n display: flex;\n flex-wrap: nowrap;\n flex-direction: row;\n flex-basis: 60%;\n"])));
2263
+
2264
+ var CommunicationPreferenceOptionsRenderer = function CommunicationPreferenceOptionsRenderer(_ref) {
2265
+ var control = _ref.control,
2266
+ name = _ref.name,
2267
+ isDisabled = _ref.isDisabled,
2268
+ options = _ref.options,
2269
+ defaultValue = _ref.defaultValue,
2270
+ setValue = _ref.setValue;
2271
+
2272
+ var _useController = useController({
2273
+ name: name,
2274
+ control: control,
2275
+ defaultValue: defaultValue
2276
+ }),
2277
+ _useController$field = _useController.field,
2278
+ ref = _useController$field.ref,
2279
+ inputProps = _objectWithoutProperties(_useController$field, _excluded),
2280
+ _useController$fieldS = _useController.fieldState,
2281
+ invalid = _useController$fieldS.invalid,
2282
+ error = _useController$fieldS.error;
2283
+
2284
+ useEffect(function () {
2285
+ if (defaultValue) {
2286
+ setValue(name, defaultValue);
2287
+ }
2288
+ }, [defaultValue, name, setValue]);
2289
+ return /*#__PURE__*/React.createElement(OptionsRow, null, /*#__PURE__*/React.createElement(Options, null, options.map(function (option) {
2290
+ return /*#__PURE__*/React.createElement(RadioButtonLabel, {
2291
+ key: option.value,
2292
+ htmlFor: option.value
2293
+ }, /*#__PURE__*/React.createElement(RadioButtonInput, _extends({
2294
+ id: option.value,
2295
+ ref: ref,
2296
+ type: "radio",
2297
+ name: name,
2298
+ defaultChecked: inputProps.value === option.value.toString()
2299
+ }, inputProps, {
2300
+ disabled: isDisabled,
2301
+ value: option.value
2302
+ })), /*#__PURE__*/React.createElement(RadioButtonCircle, null, /*#__PURE__*/React.createElement(RadioButtonCircleInner, null)), /*#__PURE__*/React.createElement(RadioButtonText, null, option.label));
2303
+ })), invalid && /*#__PURE__*/React.createElement("span", {
2304
+ className: "form__error"
2305
+ }, error === null || error === void 0 ? void 0 : error.message));
2306
+ };
2307
+
2308
+ var _templateObject$6, _templateObject2$1;
2309
+ var SectionContainer = styled.div(_templateObject$6 || (_templateObject$6 = _taggedTemplateLiteral(["\n border-top: flex 1px solid ", ";\n border-top-width: calc(100% - 50px);\n padding: 5px 10px;\n"])), function (props) {
2310
+ return props.theme.colors.primary;
2311
+ });
2312
+ var SectionHeading = styled.div(_templateObject2$1 || (_templateObject2$1 = _taggedTemplateLiteral(["\n padding: 5px 10px;\n"])));
2313
+
2314
+ var CommunicationPreferenceSection = function CommunicationPreferenceSection(_ref) {
2315
+ var section_heading = _ref.section_heading,
2316
+ description = _ref.description,
2317
+ control = _ref.control,
2318
+ name = _ref.name,
2319
+ isDisabled = _ref.isDisabled,
2320
+ options = _ref.options,
2321
+ defaultValue = _ref.defaultValue,
2322
+ setValue = _ref.setValue;
2323
+ return /*#__PURE__*/React.createElement(SectionContainer, null, /*#__PURE__*/React.createElement(SectionHeading, null, section_heading), /*#__PURE__*/React.createElement(CommunicationPreferenceOptionsRenderer, {
2324
+ description: description,
2325
+ control: control,
2326
+ name: name,
2327
+ isDisabled: isDisabled,
2328
+ options: options,
2329
+ defaultValue: defaultValue,
2330
+ setValue: setValue
2331
+ }));
2332
+ };
2333
+
2334
+ var CommunicationPreferenceSection$1 = themed(CommunicationPreferenceSection);
2335
+
2336
+ var defaultNotifyTime = 5000;
2337
+ var success = function success(message) {
2338
+ notify.show(message, 'success', defaultNotifyTime);
2339
+ };
2340
+ var error = function error(message) {
2341
+ notify.show(message, 'error', defaultNotifyTime);
2342
+ };
2343
+
2344
+ var simpleRequest = (function (axiosInstance, url) {
2345
+ var method = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'get';
2346
+ var payload = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2347
+ var onSuccess = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : function () {
2348
+ return null;
2374
2349
  };
2375
-
2376
- var _templateObject$7, _templateObject2$2, _templateObject3;
2377
- var CommunicationPreferenceContainer = styled__default.div(_templateObject$7 || (_templateObject$7 = _taggedTemplateLiteral(["\n border: solid 1px #d1d5dbff;\n margin-bottom: 40px;\n"])));
2378
- var EditButtonRow = styled__default.div(_templateObject2$2 || (_templateObject2$2 = _taggedTemplateLiteral(["\n display: flex;\n justify-content: end;\n padding: 10px 5px;\n margin-right: 16px;\n"])));
2379
- var SubmitButton = styled__default.input(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n flex-basis: 15%;\n margin-right: 5px;\n"])));
2380
- var BaseRequest = {
2381
- loading: false,
2382
- success: false,
2383
- failed: false
2350
+ var onFailed = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : function () {
2351
+ return null;
2352
+ };
2353
+ var requestConfigParams = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null;
2354
+ return axiosInstance[method.toLowerCase()](url, payload, requestConfigParams).then(function (res) {
2355
+ onSuccess(res);
2356
+ return res;
2357
+ }).catch(function (err) {
2358
+ onFailed(err);
2359
+ return err;
2360
+ });
2361
+ });
2362
+
2363
+ /** @format */
2364
+ var method = {
2365
+ DELETE: 'DELETE',
2366
+ POST: 'POST',
2367
+ GET: 'GET'
2368
+ };
2369
+
2370
+ var _templateObject$7, _templateObject2$2, _templateObject3;
2371
+ var CommunicationPreferenceContainer = styled.div(_templateObject$7 || (_templateObject$7 = _taggedTemplateLiteral(["\n border: solid 1px #d1d5dbff;\n margin-bottom: 40px;\n"])));
2372
+ var EditButtonRow = styled.div(_templateObject2$2 || (_templateObject2$2 = _taggedTemplateLiteral(["\n display: flex;\n justify-content: end;\n padding: 10px 5px;\n margin-right: 16px;\n"])));
2373
+ var SubmitButton = styled.input(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n flex-basis: 15%;\n margin-right: 5px;\n"])));
2374
+ var BaseRequest = {
2375
+ loading: false,
2376
+ success: false,
2377
+ failed: false
2378
+ };
2379
+
2380
+ var CommunicationPreferences = function CommunicationPreferences(_ref) {
2381
+ var header = _ref.header,
2382
+ requestInstance = _ref.requestInstance,
2383
+ updateNotificationsApi = _ref.updateNotificationsApi,
2384
+ preferenceData = _ref.preferenceData,
2385
+ btnClassName = _ref.btnClassName;
2386
+
2387
+ var _useForm = useForm(),
2388
+ handleSubmit = _useForm.handleSubmit,
2389
+ control = _useForm.control,
2390
+ setValue = _useForm.setValue;
2391
+
2392
+ var _useState = useState(_objectSpread2({}, BaseRequest)),
2393
+ _useState2 = _slicedToArray(_useState, 2),
2394
+ requestState = _useState2[0],
2395
+ setRequestState = _useState2[1];
2396
+
2397
+ var _useState3 = useState(false),
2398
+ _useState4 = _slicedToArray(_useState3, 2),
2399
+ isEditing = _useState4[0],
2400
+ setIsEditing = _useState4[1]; //
2401
+
2402
+
2403
+ var communicationOptions = [{
2404
+ label: 'WhatsApp',
2405
+ value: 'WHATSAPP'
2406
+ }, {
2407
+ label: 'Email',
2408
+ value: 'EMAIL'
2409
+ }];
2410
+
2411
+ var updateRequestState = function updateRequestState(obj) {
2412
+ setRequestState(_objectSpread2(_objectSpread2({}, BaseRequest), obj));
2384
2413
  };
2385
2414
 
2386
- var CommunicationPreferences = function CommunicationPreferences(_ref) {
2387
- var header = _ref.header,
2388
- requestInstance = _ref.requestInstance,
2389
- updateNotificationsApi = _ref.updateNotificationsApi,
2390
- preferenceData = _ref.preferenceData,
2391
- btnClassName = _ref.btnClassName;
2392
-
2393
- var _useForm = useForm(),
2394
- handleSubmit = _useForm.handleSubmit,
2395
- control = _useForm.control,
2396
- setValue = _useForm.setValue;
2397
-
2398
- var _useState = React.useState(_objectSpread2({}, BaseRequest)),
2399
- _useState2 = _slicedToArray(_useState, 2),
2400
- requestState = _useState2[0],
2401
- setRequestState = _useState2[1];
2402
-
2403
- var _useState3 = React.useState(false),
2404
- _useState4 = _slicedToArray(_useState3, 2),
2405
- isEditing = _useState4[0],
2406
- setIsEditing = _useState4[1]; //
2407
-
2408
-
2409
- var communicationOptions = [{
2410
- label: 'WhatsApp',
2411
- value: 'WHATSAPP'
2412
- }, {
2413
- label: 'Email',
2414
- value: 'EMAIL'
2415
- }];
2416
-
2417
- var updateRequestState = function updateRequestState(obj) {
2418
- setRequestState(_objectSpread2(_objectSpread2({}, BaseRequest), obj));
2419
- };
2420
-
2421
- var onSubmit = function onSubmit(form_data) {
2415
+ var onSubmit = function onSubmit(form_data) {
2416
+ updateRequestState({
2417
+ loading: true
2418
+ });
2419
+ simpleRequest(requestInstance, updateNotificationsApi, method.POST, form_data, function () {
2422
2420
  updateRequestState({
2423
- loading: true
2421
+ success: true,
2422
+ loading: false
2424
2423
  });
2425
- simpleRequest(requestInstance, updateNotificationsApi, method.POST, form_data, function () {
2426
- updateRequestState({
2427
- success: true,
2428
- loading: false
2429
- });
2430
- success('Communication Preferences Updated.');
2431
- setTimeout(function () {
2432
- window.location.reload();
2433
- }, 2000);
2434
- }, function (data) {
2435
- updateRequestState({
2436
- failed: true,
2437
- loading: false
2438
- });
2439
- var errorMessages = Object.keys(data).map(function (key) {
2440
- return data[key];
2441
- }).flat();
2442
- error(errorMessages.map(function (message, key) {
2443
- return /*#__PURE__*/React__default.createElement("div", {
2444
- key: "error-".concat(key)
2445
- }, message);
2446
- }));
2424
+ success('Communication Preferences Updated.');
2425
+ setTimeout(function () {
2426
+ window.location.reload();
2427
+ }, 2000);
2428
+ }, function (data) {
2429
+ updateRequestState({
2430
+ failed: true,
2431
+ loading: false
2447
2432
  });
2448
- };
2449
-
2450
- return /*#__PURE__*/React__default.createElement(React.Fragment, null, requestState.loading && /*#__PURE__*/React__default.createElement(EllipsisLoader, null), header, /*#__PURE__*/React__default.createElement(CommunicationPreferenceContainer, null, /*#__PURE__*/React__default.createElement("form", {
2451
- onSubmit: handleSubmit(onSubmit)
2452
- }, /*#__PURE__*/React__default.createElement(CommunicationPreferenceSection$1, {
2453
- control: control,
2454
- name: "default_communication",
2455
- options: communicationOptions,
2456
- isDisabled: !isEditing,
2457
- defaultValue: preferenceData.default_communication,
2458
- setValue: setValue
2459
- }), isEditing ? /*#__PURE__*/React__default.createElement(EditButtonRow, null, /*#__PURE__*/React__default.createElement(SubmitButton, {
2460
- type: "submit",
2461
- value: "Save",
2462
- className: "".concat(btnClassName !== null && btnClassName !== void 0 ? btnClassName : 'btn--luxity')
2463
- }), /*#__PURE__*/React__default.createElement("button", {
2464
- type: "button",
2465
- className: "".concat(btnClassName !== null && btnClassName !== void 0 ? btnClassName : 'btn--luxity'),
2466
- onClick: function onClick() {
2467
- setIsEditing(!isEditing);
2468
- }
2469
- }, "Cancel")) : /*#__PURE__*/React__default.createElement(EditButtonRow, null, /*#__PURE__*/React__default.createElement("button", {
2470
- type: "button",
2471
- className: "".concat(btnClassName !== null && btnClassName !== void 0 ? btnClassName : 'btn--luxity'),
2472
- onClick: function onClick() {
2473
- setIsEditing(!isEditing);
2474
- }
2475
- }, "Edit")))));
2433
+ var errorMessages = Object.keys(data).map(function (key) {
2434
+ return data[key];
2435
+ }).flat();
2436
+ error(errorMessages.map(function (message, key) {
2437
+ return /*#__PURE__*/React.createElement("div", {
2438
+ key: "error-".concat(key)
2439
+ }, message);
2440
+ }));
2441
+ });
2476
2442
  };
2477
2443
 
2478
- var index = themed(CommunicationPreferences);
2444
+ return /*#__PURE__*/React.createElement(Fragment, null, requestState.loading && /*#__PURE__*/React.createElement(EllipsisLoader, null), header, /*#__PURE__*/React.createElement(CommunicationPreferenceContainer, null, /*#__PURE__*/React.createElement("form", {
2445
+ onSubmit: handleSubmit(onSubmit)
2446
+ }, /*#__PURE__*/React.createElement(CommunicationPreferenceSection$1, {
2447
+ control: control,
2448
+ name: "default_communication",
2449
+ options: communicationOptions,
2450
+ isDisabled: !isEditing,
2451
+ defaultValue: preferenceData.default_communication,
2452
+ setValue: setValue
2453
+ }), isEditing ? /*#__PURE__*/React.createElement(EditButtonRow, null, /*#__PURE__*/React.createElement(SubmitButton, {
2454
+ type: "submit",
2455
+ value: "Save",
2456
+ className: "".concat(btnClassName !== null && btnClassName !== void 0 ? btnClassName : 'btn--luxity')
2457
+ }), /*#__PURE__*/React.createElement("button", {
2458
+ type: "button",
2459
+ className: "".concat(btnClassName !== null && btnClassName !== void 0 ? btnClassName : 'btn--luxity'),
2460
+ onClick: function onClick() {
2461
+ setIsEditing(!isEditing);
2462
+ }
2463
+ }, "Cancel")) : /*#__PURE__*/React.createElement(EditButtonRow, null, /*#__PURE__*/React.createElement("button", {
2464
+ type: "button",
2465
+ className: "".concat(btnClassName !== null && btnClassName !== void 0 ? btnClassName : 'btn--luxity'),
2466
+ onClick: function onClick() {
2467
+ setIsEditing(!isEditing);
2468
+ }
2469
+ }, "Edit")))));
2470
+ };
2479
2471
 
2480
- return index;
2472
+ var index = themed(CommunicationPreferences);
2481
2473
 
2482
- })));
2474
+ export default index;