@bonlineza/luxity-lib 2.29.0 → 2.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/bundle.js CHANGED
@@ -11152,6 +11152,9 @@
11152
11152
  }
11153
11153
  };
11154
11154
 
11155
+ React.useEffect(function () {
11156
+ searchInputRef.current.focus();
11157
+ }, []);
11155
11158
  return /*#__PURE__*/React__default.createElement(SearchContainer, {
11156
11159
  className: "header__search-container"
11157
11160
  }, /*#__PURE__*/React__default.createElement(SearchIcon, {
@@ -11883,9 +11886,2198 @@
11883
11886
 
11884
11887
  var index$4 = themed(RareStepFooter);
11885
11888
 
11889
+ var isCheckBoxInput = (element) => element.type === 'checkbox';
11890
+
11891
+ var isDateObject = (value) => value instanceof Date;
11892
+
11893
+ var isNullOrUndefined = (value) => value == null;
11894
+
11895
+ const isObjectType = (value) => typeof value === 'object';
11896
+ var isObject = (value) => !isNullOrUndefined(value) &&
11897
+ !Array.isArray(value) &&
11898
+ isObjectType(value) &&
11899
+ !isDateObject(value);
11900
+
11901
+ var getEventValue = (event) => isObject(event) && event.target
11902
+ ? isCheckBoxInput(event.target)
11903
+ ? event.target.checked
11904
+ : event.target.value
11905
+ : event;
11906
+
11907
+ var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
11908
+
11909
+ var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
11910
+
11911
+ var isPlainObject = (tempObject) => {
11912
+ const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
11913
+ return (isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf'));
11914
+ };
11915
+
11916
+ var isWeb = typeof window !== 'undefined' &&
11917
+ typeof window.HTMLElement !== 'undefined' &&
11918
+ typeof document !== 'undefined';
11919
+
11920
+ function cloneObject(data) {
11921
+ let copy;
11922
+ const isArray = Array.isArray(data);
11923
+ if (data instanceof Date) {
11924
+ copy = new Date(data);
11925
+ }
11926
+ else if (data instanceof Set) {
11927
+ copy = new Set(data);
11928
+ }
11929
+ else if (!(isWeb && (data instanceof Blob || data instanceof FileList)) &&
11930
+ (isArray || isObject(data))) {
11931
+ copy = isArray ? [] : {};
11932
+ if (!isArray && !isPlainObject(data)) {
11933
+ copy = data;
11934
+ }
11935
+ else {
11936
+ for (const key in data) {
11937
+ if (data.hasOwnProperty(key)) {
11938
+ copy[key] = cloneObject(data[key]);
11939
+ }
11940
+ }
11941
+ }
11942
+ }
11943
+ else {
11944
+ return data;
11945
+ }
11946
+ return copy;
11947
+ }
11948
+
11949
+ var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
11950
+
11951
+ var isUndefined = (val) => val === undefined;
11952
+
11953
+ var get = (obj, path, defaultValue) => {
11954
+ if (!path || !isObject(obj)) {
11955
+ return defaultValue;
11956
+ }
11957
+ const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], obj);
11958
+ return isUndefined(result) || result === obj
11959
+ ? isUndefined(obj[path])
11960
+ ? defaultValue
11961
+ : obj[path]
11962
+ : result;
11963
+ };
11964
+
11965
+ const EVENTS = {
11966
+ BLUR: 'blur',
11967
+ FOCUS_OUT: 'focusout',
11968
+ CHANGE: 'change',
11969
+ };
11970
+ const VALIDATION_MODE = {
11971
+ onBlur: 'onBlur',
11972
+ onChange: 'onChange',
11973
+ onSubmit: 'onSubmit',
11974
+ onTouched: 'onTouched',
11975
+ all: 'all',
11976
+ };
11977
+ const INPUT_VALIDATION_RULES = {
11978
+ max: 'max',
11979
+ min: 'min',
11980
+ maxLength: 'maxLength',
11981
+ minLength: 'minLength',
11982
+ pattern: 'pattern',
11983
+ required: 'required',
11984
+ validate: 'validate',
11985
+ };
11986
+
11987
+ const HookFormContext = React__default.createContext(null);
11988
+ /**
11989
+ * 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}.
11990
+ *
11991
+ * @remarks
11992
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
11993
+ *
11994
+ * @returns return all useForm methods
11995
+ *
11996
+ * @example
11997
+ * ```tsx
11998
+ * function App() {
11999
+ * const methods = useForm();
12000
+ * const onSubmit = data => console.log(data);
12001
+ *
12002
+ * return (
12003
+ * <FormProvider {...methods} >
12004
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
12005
+ * <NestedInput />
12006
+ * <input type="submit" />
12007
+ * </form>
12008
+ * </FormProvider>
12009
+ * );
12010
+ * }
12011
+ *
12012
+ * function NestedInput() {
12013
+ * const { register } = useFormContext(); // retrieve all hook methods
12014
+ * return <input {...register("test")} />;
12015
+ * }
12016
+ * ```
12017
+ */
12018
+ const useFormContext = () => React__default.useContext(HookFormContext);
12019
+
12020
+ var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
12021
+ const result = {
12022
+ defaultValues: control._defaultValues,
12023
+ };
12024
+ for (const key in formState) {
12025
+ Object.defineProperty(result, key, {
12026
+ get: () => {
12027
+ const _key = key;
12028
+ if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
12029
+ control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
12030
+ }
12031
+ localProxyFormState && (localProxyFormState[_key] = true);
12032
+ return formState[_key];
12033
+ },
12034
+ });
12035
+ }
12036
+ return result;
12037
+ };
12038
+
12039
+ var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
12040
+
12041
+ var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
12042
+ updateFormState(formStateData);
12043
+ const { name, ...formState } = formStateData;
12044
+ return (isEmptyObject(formState) ||
12045
+ Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
12046
+ Object.keys(formState).find((key) => _proxyFormState[key] ===
12047
+ (!isRoot || VALIDATION_MODE.all)));
12048
+ };
12049
+
12050
+ var convertToArrayPayload = (value) => (Array.isArray(value) ? value : [value]);
12051
+
12052
+ var shouldSubscribeByName = (name, signalName, exact) => exact && signalName
12053
+ ? name === signalName ||
12054
+ (Array.isArray(name) &&
12055
+ name.some((currentName) => currentName && exact && currentName === signalName))
12056
+ : !name ||
12057
+ !signalName ||
12058
+ name === signalName ||
12059
+ convertToArrayPayload(name).some((currentName) => currentName &&
12060
+ (currentName.startsWith(signalName) ||
12061
+ signalName.startsWith(currentName)));
12062
+
12063
+ function useSubscribe(props) {
12064
+ const _props = React__default.useRef(props);
12065
+ _props.current = props;
12066
+ React__default.useEffect(() => {
12067
+ const subscription = !props.disabled &&
12068
+ _props.current.subject &&
12069
+ _props.current.subject.subscribe({
12070
+ next: _props.current.next,
12071
+ });
12072
+ return () => {
12073
+ subscription && subscription.unsubscribe();
12074
+ };
12075
+ }, [props.disabled]);
12076
+ }
12077
+
12078
+ /**
12079
+ * 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.
12080
+ *
12081
+ * @remarks
12082
+ * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
12083
+ *
12084
+ * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
12085
+ *
12086
+ * @example
12087
+ * ```tsx
12088
+ * function App() {
12089
+ * const { register, handleSubmit, control } = useForm({
12090
+ * defaultValues: {
12091
+ * firstName: "firstName"
12092
+ * }});
12093
+ * const { dirtyFields } = useFormState({
12094
+ * control
12095
+ * });
12096
+ * const onSubmit = (data) => console.log(data);
12097
+ *
12098
+ * return (
12099
+ * <form onSubmit={handleSubmit(onSubmit)}>
12100
+ * <input {...register("firstName")} placeholder="First Name" />
12101
+ * {dirtyFields.firstName && <p>Field is dirty.</p>}
12102
+ * <input type="submit" />
12103
+ * </form>
12104
+ * );
12105
+ * }
12106
+ * ```
12107
+ */
12108
+ function useFormState(props) {
12109
+ const methods = useFormContext();
12110
+ const { control = methods.control, disabled, name, exact } = props || {};
12111
+ const [formState, updateFormState] = React__default.useState(control._formState);
12112
+ const _mounted = React__default.useRef(true);
12113
+ const _localProxyFormState = React__default.useRef({
12114
+ isDirty: false,
12115
+ isLoading: false,
12116
+ dirtyFields: false,
12117
+ touchedFields: false,
12118
+ isValidating: false,
12119
+ isValid: false,
12120
+ errors: false,
12121
+ });
12122
+ const _name = React__default.useRef(name);
12123
+ _name.current = name;
12124
+ useSubscribe({
12125
+ disabled,
12126
+ next: (value) => _mounted.current &&
12127
+ shouldSubscribeByName(_name.current, value.name, exact) &&
12128
+ shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) &&
12129
+ updateFormState({
12130
+ ...control._formState,
12131
+ ...value,
12132
+ }),
12133
+ subject: control._subjects.state,
12134
+ });
12135
+ React__default.useEffect(() => {
12136
+ _mounted.current = true;
12137
+ _localProxyFormState.current.isValid && control._updateValid(true);
12138
+ return () => {
12139
+ _mounted.current = false;
12140
+ };
12141
+ }, [control]);
12142
+ return getProxyFormState(formState, control, _localProxyFormState.current, false);
12143
+ }
12144
+
12145
+ var isString = (value) => typeof value === 'string';
12146
+
12147
+ var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
12148
+ if (isString(names)) {
12149
+ isGlobal && _names.watch.add(names);
12150
+ return get(formValues, names, defaultValue);
12151
+ }
12152
+ if (Array.isArray(names)) {
12153
+ return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
12154
+ }
12155
+ isGlobal && (_names.watchAll = true);
12156
+ return formValues;
12157
+ };
12158
+
12159
+ /**
12160
+ * Custom hook to subscribe to field change and isolate re-rendering at the component level.
12161
+ *
12162
+ * @remarks
12163
+ *
12164
+ * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
12165
+ *
12166
+ * @example
12167
+ * ```tsx
12168
+ * const { watch } = useForm();
12169
+ * const values = useWatch({
12170
+ * name: "fieldName"
12171
+ * control,
12172
+ * })
12173
+ * ```
12174
+ */
12175
+ function useWatch(props) {
12176
+ const methods = useFormContext();
12177
+ const { control = methods.control, name, defaultValue, disabled, exact, } = props || {};
12178
+ const _name = React__default.useRef(name);
12179
+ _name.current = name;
12180
+ useSubscribe({
12181
+ disabled,
12182
+ subject: control._subjects.values,
12183
+ next: (formState) => {
12184
+ if (shouldSubscribeByName(_name.current, formState.name, exact)) {
12185
+ updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
12186
+ }
12187
+ },
12188
+ });
12189
+ const [value, updateValue] = React__default.useState(control._getWatch(name, defaultValue));
12190
+ React__default.useEffect(() => control._removeUnmounted());
12191
+ return value;
12192
+ }
12193
+
12194
+ var isKey = (value) => /^\w*$/.test(value);
12195
+
12196
+ var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
12197
+
12198
+ function set(object, path, value) {
12199
+ let index = -1;
12200
+ const tempPath = isKey(path) ? [path] : stringToPath(path);
12201
+ const length = tempPath.length;
12202
+ const lastIndex = length - 1;
12203
+ while (++index < length) {
12204
+ const key = tempPath[index];
12205
+ let newValue = value;
12206
+ if (index !== lastIndex) {
12207
+ const objValue = object[key];
12208
+ newValue =
12209
+ isObject(objValue) || Array.isArray(objValue)
12210
+ ? objValue
12211
+ : !isNaN(+tempPath[index + 1])
12212
+ ? []
12213
+ : {};
12214
+ }
12215
+ object[key] = newValue;
12216
+ object = object[key];
12217
+ }
12218
+ return object;
12219
+ }
12220
+
12221
+ /**
12222
+ * 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.
12223
+ *
12224
+ * @remarks
12225
+ * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
12226
+ *
12227
+ * @param props - the path name to the form field value, and validation rules.
12228
+ *
12229
+ * @returns field properties, field and form state. {@link UseControllerReturn}
12230
+ *
12231
+ * @example
12232
+ * ```tsx
12233
+ * function Input(props) {
12234
+ * const { field, fieldState, formState } = useController(props);
12235
+ * return (
12236
+ * <div>
12237
+ * <input {...field} placeholder={props.name} />
12238
+ * <p>{fieldState.isTouched && "Touched"}</p>
12239
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
12240
+ * </div>
12241
+ * );
12242
+ * }
12243
+ * ```
12244
+ */
12245
+ function useController(props) {
12246
+ const methods = useFormContext();
12247
+ const { name, disabled, control = methods.control, shouldUnregister } = props;
12248
+ const isArrayField = isNameInFieldArray(control._names.array, name);
12249
+ const value = useWatch({
12250
+ control,
12251
+ name,
12252
+ defaultValue: get(control._formValues, name, get(control._defaultValues, name, props.defaultValue)),
12253
+ exact: true,
12254
+ });
12255
+ const formState = useFormState({
12256
+ control,
12257
+ name,
12258
+ });
12259
+ const _registerProps = React__default.useRef(control.register(name, {
12260
+ ...props.rules,
12261
+ value,
12262
+ }));
12263
+ _registerProps.current = control.register(name, props.rules);
12264
+ React__default.useEffect(() => {
12265
+ const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
12266
+ const updateMounted = (name, value) => {
12267
+ const field = get(control._fields, name);
12268
+ if (field) {
12269
+ field._f.mount = value;
12270
+ }
12271
+ };
12272
+ updateMounted(name, true);
12273
+ if (_shouldUnregisterField) {
12274
+ const value = cloneObject(get(control._options.defaultValues, name));
12275
+ set(control._defaultValues, name, value);
12276
+ if (isUndefined(get(control._formValues, name))) {
12277
+ set(control._formValues, name, value);
12278
+ }
12279
+ }
12280
+ return () => {
12281
+ (isArrayField
12282
+ ? _shouldUnregisterField && !control._state.action
12283
+ : _shouldUnregisterField)
12284
+ ? control.unregister(name)
12285
+ : updateMounted(name, false);
12286
+ };
12287
+ }, [name, control, isArrayField, shouldUnregister]);
12288
+ React__default.useEffect(() => {
12289
+ control._updateDisabledField({
12290
+ disabled,
12291
+ fields: control._fields,
12292
+ name,
12293
+ });
12294
+ }, [disabled, name, control]);
12295
+ return {
12296
+ field: {
12297
+ name,
12298
+ value,
12299
+ disabled,
12300
+ onChange: React__default.useCallback((event) => _registerProps.current.onChange({
12301
+ target: {
12302
+ value: getEventValue(event),
12303
+ name: name,
12304
+ },
12305
+ type: EVENTS.CHANGE,
12306
+ }), [name]),
12307
+ onBlur: React__default.useCallback(() => _registerProps.current.onBlur({
12308
+ target: {
12309
+ value: get(control._formValues, name),
12310
+ name: name,
12311
+ },
12312
+ type: EVENTS.BLUR,
12313
+ }), [name, control]),
12314
+ ref: (elm) => {
12315
+ const field = get(control._fields, name);
12316
+ if (field && elm) {
12317
+ field._f.ref = {
12318
+ focus: () => elm.focus(),
12319
+ select: () => elm.select(),
12320
+ setCustomValidity: (message) => elm.setCustomValidity(message),
12321
+ reportValidity: () => elm.reportValidity(),
12322
+ };
12323
+ }
12324
+ },
12325
+ },
12326
+ formState,
12327
+ fieldState: Object.defineProperties({}, {
12328
+ invalid: {
12329
+ enumerable: true,
12330
+ get: () => !!get(formState.errors, name),
12331
+ },
12332
+ isDirty: {
12333
+ enumerable: true,
12334
+ get: () => !!get(formState.dirtyFields, name),
12335
+ },
12336
+ isTouched: {
12337
+ enumerable: true,
12338
+ get: () => !!get(formState.touchedFields, name),
12339
+ },
12340
+ error: {
12341
+ enumerable: true,
12342
+ get: () => get(formState.errors, name),
12343
+ },
12344
+ }),
12345
+ };
12346
+ }
12347
+
12348
+ var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria
12349
+ ? {
12350
+ ...errors[name],
12351
+ types: {
12352
+ ...(errors[name] && errors[name].types ? errors[name].types : {}),
12353
+ [type]: message || true,
12354
+ },
12355
+ }
12356
+ : {};
12357
+
12358
+ const focusFieldBy = (fields, callback, fieldsNames) => {
12359
+ for (const key of fieldsNames || Object.keys(fields)) {
12360
+ const field = get(fields, key);
12361
+ if (field) {
12362
+ const { _f, ...currentField } = field;
12363
+ if (_f && callback(_f.name)) {
12364
+ if (_f.ref.focus) {
12365
+ _f.ref.focus();
12366
+ break;
12367
+ }
12368
+ else if (_f.refs && _f.refs[0].focus) {
12369
+ _f.refs[0].focus();
12370
+ break;
12371
+ }
12372
+ }
12373
+ else if (isObject(currentField)) {
12374
+ focusFieldBy(currentField, callback);
12375
+ }
12376
+ }
12377
+ }
12378
+ };
12379
+
12380
+ var getValidationModes = (mode) => ({
12381
+ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
12382
+ isOnBlur: mode === VALIDATION_MODE.onBlur,
12383
+ isOnChange: mode === VALIDATION_MODE.onChange,
12384
+ isOnAll: mode === VALIDATION_MODE.all,
12385
+ isOnTouch: mode === VALIDATION_MODE.onTouched,
12386
+ });
12387
+
12388
+ var isWatched = (name, _names, isBlurEvent) => !isBlurEvent &&
12389
+ (_names.watchAll ||
12390
+ _names.watch.has(name) ||
12391
+ [..._names.watch].some((watchName) => name.startsWith(watchName) &&
12392
+ /^\.\w+/.test(name.slice(watchName.length))));
12393
+
12394
+ var updateFieldArrayRootError = (errors, error, name) => {
12395
+ const fieldArrayErrors = compact(get(errors, name));
12396
+ set(fieldArrayErrors, 'root', error[name]);
12397
+ set(errors, name, fieldArrayErrors);
12398
+ return errors;
12399
+ };
12400
+
12401
+ var isBoolean = (value) => typeof value === 'boolean';
12402
+
12403
+ var isFileInput = (element) => element.type === 'file';
12404
+
12405
+ var isFunction = (value) => typeof value === 'function';
12406
+
12407
+ var isHTMLElement = (value) => {
12408
+ if (!isWeb) {
12409
+ return false;
12410
+ }
12411
+ const owner = value ? value.ownerDocument : 0;
12412
+ return (value instanceof
12413
+ (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement));
12414
+ };
12415
+
12416
+ var isMessage = (value) => isString(value);
12417
+
12418
+ var isRadioInput = (element) => element.type === 'radio';
12419
+
12420
+ var isRegex = (value) => value instanceof RegExp;
12421
+
12422
+ const defaultResult = {
12423
+ value: false,
12424
+ isValid: false,
12425
+ };
12426
+ const validResult = { value: true, isValid: true };
12427
+ var getCheckboxValue = (options) => {
12428
+ if (Array.isArray(options)) {
12429
+ if (options.length > 1) {
12430
+ const values = options
12431
+ .filter((option) => option && option.checked && !option.disabled)
12432
+ .map((option) => option.value);
12433
+ return { value: values, isValid: !!values.length };
12434
+ }
12435
+ return options[0].checked && !options[0].disabled
12436
+ ? // @ts-expect-error expected to work in the browser
12437
+ options[0].attributes && !isUndefined(options[0].attributes.value)
12438
+ ? isUndefined(options[0].value) || options[0].value === ''
12439
+ ? validResult
12440
+ : { value: options[0].value, isValid: true }
12441
+ : validResult
12442
+ : defaultResult;
12443
+ }
12444
+ return defaultResult;
12445
+ };
12446
+
12447
+ const defaultReturn = {
12448
+ isValid: false,
12449
+ value: null,
12450
+ };
12451
+ var getRadioValue = (options) => Array.isArray(options)
12452
+ ? options.reduce((previous, option) => option && option.checked && !option.disabled
12453
+ ? {
12454
+ isValid: true,
12455
+ value: option.value,
12456
+ }
12457
+ : previous, defaultReturn)
12458
+ : defaultReturn;
12459
+
12460
+ function getValidateError(result, ref, type = 'validate') {
12461
+ if (isMessage(result) ||
12462
+ (Array.isArray(result) && result.every(isMessage)) ||
12463
+ (isBoolean(result) && !result)) {
12464
+ return {
12465
+ type,
12466
+ message: isMessage(result) ? result : '',
12467
+ ref,
12468
+ };
12469
+ }
12470
+ }
12471
+
12472
+ var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData)
12473
+ ? validationData
12474
+ : {
12475
+ value: validationData,
12476
+ message: '',
12477
+ };
12478
+
12479
+ var validateField = async (field, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
12480
+ const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled, } = field._f;
12481
+ const inputValue = get(formValues, name);
12482
+ if (!mount || disabled) {
12483
+ return {};
12484
+ }
12485
+ const inputRef = refs ? refs[0] : ref;
12486
+ const setCustomValidity = (message) => {
12487
+ if (shouldUseNativeValidation && inputRef.reportValidity) {
12488
+ inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
12489
+ inputRef.reportValidity();
12490
+ }
12491
+ };
12492
+ const error = {};
12493
+ const isRadio = isRadioInput(ref);
12494
+ const isCheckBox = isCheckBoxInput(ref);
12495
+ const isRadioOrCheckbox = isRadio || isCheckBox;
12496
+ const isEmpty = ((valueAsNumber || isFileInput(ref)) &&
12497
+ isUndefined(ref.value) &&
12498
+ isUndefined(inputValue)) ||
12499
+ (isHTMLElement(ref) && ref.value === '') ||
12500
+ inputValue === '' ||
12501
+ (Array.isArray(inputValue) && !inputValue.length);
12502
+ const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
12503
+ const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
12504
+ const message = exceedMax ? maxLengthMessage : minLengthMessage;
12505
+ error[name] = {
12506
+ type: exceedMax ? maxType : minType,
12507
+ message,
12508
+ ref,
12509
+ ...appendErrorsCurry(exceedMax ? maxType : minType, message),
12510
+ };
12511
+ };
12512
+ if (isFieldArray
12513
+ ? !Array.isArray(inputValue) || !inputValue.length
12514
+ : required &&
12515
+ ((!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue))) ||
12516
+ (isBoolean(inputValue) && !inputValue) ||
12517
+ (isCheckBox && !getCheckboxValue(refs).isValid) ||
12518
+ (isRadio && !getRadioValue(refs).isValid))) {
12519
+ const { value, message } = isMessage(required)
12520
+ ? { value: !!required, message: required }
12521
+ : getValueAndMessage(required);
12522
+ if (value) {
12523
+ error[name] = {
12524
+ type: INPUT_VALIDATION_RULES.required,
12525
+ message,
12526
+ ref: inputRef,
12527
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message),
12528
+ };
12529
+ if (!validateAllFieldCriteria) {
12530
+ setCustomValidity(message);
12531
+ return error;
12532
+ }
12533
+ }
12534
+ }
12535
+ if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
12536
+ let exceedMax;
12537
+ let exceedMin;
12538
+ const maxOutput = getValueAndMessage(max);
12539
+ const minOutput = getValueAndMessage(min);
12540
+ if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
12541
+ const valueNumber = ref.valueAsNumber ||
12542
+ (inputValue ? +inputValue : inputValue);
12543
+ if (!isNullOrUndefined(maxOutput.value)) {
12544
+ exceedMax = valueNumber > maxOutput.value;
12545
+ }
12546
+ if (!isNullOrUndefined(minOutput.value)) {
12547
+ exceedMin = valueNumber < minOutput.value;
12548
+ }
12549
+ }
12550
+ else {
12551
+ const valueDate = ref.valueAsDate || new Date(inputValue);
12552
+ const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
12553
+ const isTime = ref.type == 'time';
12554
+ const isWeek = ref.type == 'week';
12555
+ if (isString(maxOutput.value) && inputValue) {
12556
+ exceedMax = isTime
12557
+ ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value)
12558
+ : isWeek
12559
+ ? inputValue > maxOutput.value
12560
+ : valueDate > new Date(maxOutput.value);
12561
+ }
12562
+ if (isString(minOutput.value) && inputValue) {
12563
+ exceedMin = isTime
12564
+ ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value)
12565
+ : isWeek
12566
+ ? inputValue < minOutput.value
12567
+ : valueDate < new Date(minOutput.value);
12568
+ }
12569
+ }
12570
+ if (exceedMax || exceedMin) {
12571
+ getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
12572
+ if (!validateAllFieldCriteria) {
12573
+ setCustomValidity(error[name].message);
12574
+ return error;
12575
+ }
12576
+ }
12577
+ }
12578
+ if ((maxLength || minLength) &&
12579
+ !isEmpty &&
12580
+ (isString(inputValue) || (isFieldArray && Array.isArray(inputValue)))) {
12581
+ const maxLengthOutput = getValueAndMessage(maxLength);
12582
+ const minLengthOutput = getValueAndMessage(minLength);
12583
+ const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
12584
+ inputValue.length > +maxLengthOutput.value;
12585
+ const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
12586
+ inputValue.length < +minLengthOutput.value;
12587
+ if (exceedMax || exceedMin) {
12588
+ getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
12589
+ if (!validateAllFieldCriteria) {
12590
+ setCustomValidity(error[name].message);
12591
+ return error;
12592
+ }
12593
+ }
12594
+ }
12595
+ if (pattern && !isEmpty && isString(inputValue)) {
12596
+ const { value: patternValue, message } = getValueAndMessage(pattern);
12597
+ if (isRegex(patternValue) && !inputValue.match(patternValue)) {
12598
+ error[name] = {
12599
+ type: INPUT_VALIDATION_RULES.pattern,
12600
+ message,
12601
+ ref,
12602
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message),
12603
+ };
12604
+ if (!validateAllFieldCriteria) {
12605
+ setCustomValidity(message);
12606
+ return error;
12607
+ }
12608
+ }
12609
+ }
12610
+ if (validate) {
12611
+ if (isFunction(validate)) {
12612
+ const result = await validate(inputValue, formValues);
12613
+ const validateError = getValidateError(result, inputRef);
12614
+ if (validateError) {
12615
+ error[name] = {
12616
+ ...validateError,
12617
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message),
12618
+ };
12619
+ if (!validateAllFieldCriteria) {
12620
+ setCustomValidity(validateError.message);
12621
+ return error;
12622
+ }
12623
+ }
12624
+ }
12625
+ else if (isObject(validate)) {
12626
+ let validationResult = {};
12627
+ for (const key in validate) {
12628
+ if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
12629
+ break;
12630
+ }
12631
+ const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
12632
+ if (validateError) {
12633
+ validationResult = {
12634
+ ...validateError,
12635
+ ...appendErrorsCurry(key, validateError.message),
12636
+ };
12637
+ setCustomValidity(validateError.message);
12638
+ if (validateAllFieldCriteria) {
12639
+ error[name] = validationResult;
12640
+ }
12641
+ }
12642
+ }
12643
+ if (!isEmptyObject(validationResult)) {
12644
+ error[name] = {
12645
+ ref: inputRef,
12646
+ ...validationResult,
12647
+ };
12648
+ if (!validateAllFieldCriteria) {
12649
+ return error;
12650
+ }
12651
+ }
12652
+ }
12653
+ }
12654
+ setCustomValidity(true);
12655
+ return error;
12656
+ };
12657
+
12658
+ function baseGet(object, updatePath) {
12659
+ const length = updatePath.slice(0, -1).length;
12660
+ let index = 0;
12661
+ while (index < length) {
12662
+ object = isUndefined(object) ? index++ : object[updatePath[index++]];
12663
+ }
12664
+ return object;
12665
+ }
12666
+ function isEmptyArray(obj) {
12667
+ for (const key in obj) {
12668
+ if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
12669
+ return false;
12670
+ }
12671
+ }
12672
+ return true;
12673
+ }
12674
+ function unset(object, path) {
12675
+ const paths = Array.isArray(path)
12676
+ ? path
12677
+ : isKey(path)
12678
+ ? [path]
12679
+ : stringToPath(path);
12680
+ const childObject = paths.length === 1 ? object : baseGet(object, paths);
12681
+ const index = paths.length - 1;
12682
+ const key = paths[index];
12683
+ if (childObject) {
12684
+ delete childObject[key];
12685
+ }
12686
+ if (index !== 0 &&
12687
+ ((isObject(childObject) && isEmptyObject(childObject)) ||
12688
+ (Array.isArray(childObject) && isEmptyArray(childObject)))) {
12689
+ unset(object, paths.slice(0, -1));
12690
+ }
12691
+ return object;
12692
+ }
12693
+
12694
+ function createSubject() {
12695
+ let _observers = [];
12696
+ const next = (value) => {
12697
+ for (const observer of _observers) {
12698
+ observer.next && observer.next(value);
12699
+ }
12700
+ };
12701
+ const subscribe = (observer) => {
12702
+ _observers.push(observer);
12703
+ return {
12704
+ unsubscribe: () => {
12705
+ _observers = _observers.filter((o) => o !== observer);
12706
+ },
12707
+ };
12708
+ };
12709
+ const unsubscribe = () => {
12710
+ _observers = [];
12711
+ };
12712
+ return {
12713
+ get observers() {
12714
+ return _observers;
12715
+ },
12716
+ next,
12717
+ subscribe,
12718
+ unsubscribe,
12719
+ };
12720
+ }
12721
+
12722
+ var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
12723
+
12724
+ function deepEqual(object1, object2) {
12725
+ if (isPrimitive(object1) || isPrimitive(object2)) {
12726
+ return object1 === object2;
12727
+ }
12728
+ if (isDateObject(object1) && isDateObject(object2)) {
12729
+ return object1.getTime() === object2.getTime();
12730
+ }
12731
+ const keys1 = Object.keys(object1);
12732
+ const keys2 = Object.keys(object2);
12733
+ if (keys1.length !== keys2.length) {
12734
+ return false;
12735
+ }
12736
+ for (const key of keys1) {
12737
+ const val1 = object1[key];
12738
+ if (!keys2.includes(key)) {
12739
+ return false;
12740
+ }
12741
+ if (key !== 'ref') {
12742
+ const val2 = object2[key];
12743
+ if ((isDateObject(val1) && isDateObject(val2)) ||
12744
+ (isObject(val1) && isObject(val2)) ||
12745
+ (Array.isArray(val1) && Array.isArray(val2))
12746
+ ? !deepEqual(val1, val2)
12747
+ : val1 !== val2) {
12748
+ return false;
12749
+ }
12750
+ }
12751
+ }
12752
+ return true;
12753
+ }
12754
+
12755
+ var isMultipleSelect = (element) => element.type === `select-multiple`;
12756
+
12757
+ var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
12758
+
12759
+ var live = (ref) => isHTMLElement(ref) && ref.isConnected;
12760
+
12761
+ var objectHasFunction = (data) => {
12762
+ for (const key in data) {
12763
+ if (isFunction(data[key])) {
12764
+ return true;
12765
+ }
12766
+ }
12767
+ return false;
12768
+ };
12769
+
12770
+ function markFieldsDirty(data, fields = {}) {
12771
+ const isParentNodeArray = Array.isArray(data);
12772
+ if (isObject(data) || isParentNodeArray) {
12773
+ for (const key in data) {
12774
+ if (Array.isArray(data[key]) ||
12775
+ (isObject(data[key]) && !objectHasFunction(data[key]))) {
12776
+ fields[key] = Array.isArray(data[key]) ? [] : {};
12777
+ markFieldsDirty(data[key], fields[key]);
12778
+ }
12779
+ else if (!isNullOrUndefined(data[key])) {
12780
+ fields[key] = true;
12781
+ }
12782
+ }
12783
+ }
12784
+ return fields;
12785
+ }
12786
+ function getDirtyFieldsFromDefaultValues(data, formValues, dirtyFieldsFromValues) {
12787
+ const isParentNodeArray = Array.isArray(data);
12788
+ if (isObject(data) || isParentNodeArray) {
12789
+ for (const key in data) {
12790
+ if (Array.isArray(data[key]) ||
12791
+ (isObject(data[key]) && !objectHasFunction(data[key]))) {
12792
+ if (isUndefined(formValues) ||
12793
+ isPrimitive(dirtyFieldsFromValues[key])) {
12794
+ dirtyFieldsFromValues[key] = Array.isArray(data[key])
12795
+ ? markFieldsDirty(data[key], [])
12796
+ : { ...markFieldsDirty(data[key]) };
12797
+ }
12798
+ else {
12799
+ getDirtyFieldsFromDefaultValues(data[key], isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
12800
+ }
12801
+ }
12802
+ else {
12803
+ dirtyFieldsFromValues[key] = !deepEqual(data[key], formValues[key]);
12804
+ }
12805
+ }
12806
+ }
12807
+ return dirtyFieldsFromValues;
12808
+ }
12809
+ var getDirtyFields = (defaultValues, formValues) => getDirtyFieldsFromDefaultValues(defaultValues, formValues, markFieldsDirty(formValues));
12810
+
12811
+ var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value)
12812
+ ? value
12813
+ : valueAsNumber
12814
+ ? value === ''
12815
+ ? NaN
12816
+ : value
12817
+ ? +value
12818
+ : value
12819
+ : valueAsDate && isString(value)
12820
+ ? new Date(value)
12821
+ : setValueAs
12822
+ ? setValueAs(value)
12823
+ : value;
12824
+
12825
+ function getFieldValue(_f) {
12826
+ const ref = _f.ref;
12827
+ if (_f.refs ? _f.refs.every((ref) => ref.disabled) : ref.disabled) {
12828
+ return;
12829
+ }
12830
+ if (isFileInput(ref)) {
12831
+ return ref.files;
12832
+ }
12833
+ if (isRadioInput(ref)) {
12834
+ return getRadioValue(_f.refs).value;
12835
+ }
12836
+ if (isMultipleSelect(ref)) {
12837
+ return [...ref.selectedOptions].map(({ value }) => value);
12838
+ }
12839
+ if (isCheckBoxInput(ref)) {
12840
+ return getCheckboxValue(_f.refs).value;
12841
+ }
12842
+ return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
12843
+ }
12844
+
12845
+ var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
12846
+ const fields = {};
12847
+ for (const name of fieldsNames) {
12848
+ const field = get(_fields, name);
12849
+ field && set(fields, name, field._f);
12850
+ }
12851
+ return {
12852
+ criteriaMode,
12853
+ names: [...fieldsNames],
12854
+ fields,
12855
+ shouldUseNativeValidation,
12856
+ };
12857
+ };
12858
+
12859
+ var getRuleValue = (rule) => isUndefined(rule)
12860
+ ? rule
12861
+ : isRegex(rule)
12862
+ ? rule.source
12863
+ : isObject(rule)
12864
+ ? isRegex(rule.value)
12865
+ ? rule.value.source
12866
+ : rule.value
12867
+ : rule;
12868
+
12869
+ var hasValidation = (options) => options.mount &&
12870
+ (options.required ||
12871
+ options.min ||
12872
+ options.max ||
12873
+ options.maxLength ||
12874
+ options.minLength ||
12875
+ options.pattern ||
12876
+ options.validate);
12877
+
12878
+ function schemaErrorLookup(errors, _fields, name) {
12879
+ const error = get(errors, name);
12880
+ if (error || isKey(name)) {
12881
+ return {
12882
+ error,
12883
+ name,
12884
+ };
12885
+ }
12886
+ const names = name.split('.');
12887
+ while (names.length) {
12888
+ const fieldName = names.join('.');
12889
+ const field = get(_fields, fieldName);
12890
+ const foundError = get(errors, fieldName);
12891
+ if (field && !Array.isArray(field) && name !== fieldName) {
12892
+ return { name };
12893
+ }
12894
+ if (foundError && foundError.type) {
12895
+ return {
12896
+ name: fieldName,
12897
+ error: foundError,
12898
+ };
12899
+ }
12900
+ names.pop();
12901
+ }
12902
+ return {
12903
+ name,
12904
+ };
12905
+ }
12906
+
12907
+ var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
12908
+ if (mode.isOnAll) {
12909
+ return false;
12910
+ }
12911
+ else if (!isSubmitted && mode.isOnTouch) {
12912
+ return !(isTouched || isBlurEvent);
12913
+ }
12914
+ else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) {
12915
+ return !isBlurEvent;
12916
+ }
12917
+ else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) {
12918
+ return isBlurEvent;
12919
+ }
12920
+ return true;
12921
+ };
12922
+
12923
+ var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
12924
+
12925
+ const defaultOptions = {
12926
+ mode: VALIDATION_MODE.onSubmit,
12927
+ reValidateMode: VALIDATION_MODE.onChange,
12928
+ shouldFocusError: true,
12929
+ };
12930
+ function createFormControl(props = {}, flushRootRender) {
12931
+ let _options = {
12932
+ ...defaultOptions,
12933
+ ...props,
12934
+ };
12935
+ let _formState = {
12936
+ submitCount: 0,
12937
+ isDirty: false,
12938
+ isLoading: isFunction(_options.defaultValues),
12939
+ isValidating: false,
12940
+ isSubmitted: false,
12941
+ isSubmitting: false,
12942
+ isSubmitSuccessful: false,
12943
+ isValid: false,
12944
+ touchedFields: {},
12945
+ dirtyFields: {},
12946
+ errors: {},
12947
+ };
12948
+ let _fields = {};
12949
+ let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values)
12950
+ ? cloneObject(_options.defaultValues || _options.values) || {}
12951
+ : {};
12952
+ let _formValues = _options.shouldUnregister
12953
+ ? {}
12954
+ : cloneObject(_defaultValues);
12955
+ let _state = {
12956
+ action: false,
12957
+ mount: false,
12958
+ watch: false,
12959
+ };
12960
+ let _names = {
12961
+ mount: new Set(),
12962
+ unMount: new Set(),
12963
+ array: new Set(),
12964
+ watch: new Set(),
12965
+ };
12966
+ let delayErrorCallback;
12967
+ let timer = 0;
12968
+ const _proxyFormState = {
12969
+ isDirty: false,
12970
+ dirtyFields: false,
12971
+ touchedFields: false,
12972
+ isValidating: false,
12973
+ isValid: false,
12974
+ errors: false,
12975
+ };
12976
+ const _subjects = {
12977
+ values: createSubject(),
12978
+ array: createSubject(),
12979
+ state: createSubject(),
12980
+ };
12981
+ const shouldCaptureDirtyFields = props.resetOptions && props.resetOptions.keepDirtyValues;
12982
+ const validationModeBeforeSubmit = getValidationModes(_options.mode);
12983
+ const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
12984
+ const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
12985
+ const debounce = (callback) => (wait) => {
12986
+ clearTimeout(timer);
12987
+ timer = setTimeout(callback, wait);
12988
+ };
12989
+ const _updateValid = async (shouldUpdateValid) => {
12990
+ if (_proxyFormState.isValid || shouldUpdateValid) {
12991
+ const isValid = _options.resolver
12992
+ ? isEmptyObject((await _executeSchema()).errors)
12993
+ : await executeBuiltInValidation(_fields, true);
12994
+ if (isValid !== _formState.isValid) {
12995
+ _subjects.state.next({
12996
+ isValid,
12997
+ });
12998
+ }
12999
+ }
13000
+ };
13001
+ const _updateIsValidating = (value) => _proxyFormState.isValidating &&
13002
+ _subjects.state.next({
13003
+ isValidating: value,
13004
+ });
13005
+ const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
13006
+ if (args && method) {
13007
+ _state.action = true;
13008
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
13009
+ const fieldValues = method(get(_fields, name), args.argA, args.argB);
13010
+ shouldSetValues && set(_fields, name, fieldValues);
13011
+ }
13012
+ if (shouldUpdateFieldsAndState &&
13013
+ Array.isArray(get(_formState.errors, name))) {
13014
+ const errors = method(get(_formState.errors, name), args.argA, args.argB);
13015
+ shouldSetValues && set(_formState.errors, name, errors);
13016
+ unsetEmptyArray(_formState.errors, name);
13017
+ }
13018
+ if (_proxyFormState.touchedFields &&
13019
+ shouldUpdateFieldsAndState &&
13020
+ Array.isArray(get(_formState.touchedFields, name))) {
13021
+ const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
13022
+ shouldSetValues && set(_formState.touchedFields, name, touchedFields);
13023
+ }
13024
+ if (_proxyFormState.dirtyFields) {
13025
+ _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
13026
+ }
13027
+ _subjects.state.next({
13028
+ name,
13029
+ isDirty: _getDirty(name, values),
13030
+ dirtyFields: _formState.dirtyFields,
13031
+ errors: _formState.errors,
13032
+ isValid: _formState.isValid,
13033
+ });
13034
+ }
13035
+ else {
13036
+ set(_formValues, name, values);
13037
+ }
13038
+ };
13039
+ const updateErrors = (name, error) => {
13040
+ set(_formState.errors, name, error);
13041
+ _subjects.state.next({
13042
+ errors: _formState.errors,
13043
+ });
13044
+ };
13045
+ const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
13046
+ const field = get(_fields, name);
13047
+ if (field) {
13048
+ const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
13049
+ isUndefined(defaultValue) ||
13050
+ (ref && ref.defaultChecked) ||
13051
+ shouldSkipSetValueAs
13052
+ ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f))
13053
+ : setFieldValue(name, defaultValue);
13054
+ _state.mount && _updateValid();
13055
+ }
13056
+ };
13057
+ const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
13058
+ let shouldUpdateField = false;
13059
+ let isPreviousDirty = false;
13060
+ const output = {
13061
+ name,
13062
+ };
13063
+ if (!isBlurEvent || shouldDirty) {
13064
+ if (_proxyFormState.isDirty) {
13065
+ isPreviousDirty = _formState.isDirty;
13066
+ _formState.isDirty = output.isDirty = _getDirty();
13067
+ shouldUpdateField = isPreviousDirty !== output.isDirty;
13068
+ }
13069
+ const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
13070
+ isPreviousDirty = get(_formState.dirtyFields, name);
13071
+ isCurrentFieldPristine
13072
+ ? unset(_formState.dirtyFields, name)
13073
+ : set(_formState.dirtyFields, name, true);
13074
+ output.dirtyFields = _formState.dirtyFields;
13075
+ shouldUpdateField =
13076
+ shouldUpdateField ||
13077
+ (_proxyFormState.dirtyFields &&
13078
+ isPreviousDirty !== !isCurrentFieldPristine);
13079
+ }
13080
+ if (isBlurEvent) {
13081
+ const isPreviousFieldTouched = get(_formState.touchedFields, name);
13082
+ if (!isPreviousFieldTouched) {
13083
+ set(_formState.touchedFields, name, isBlurEvent);
13084
+ output.touchedFields = _formState.touchedFields;
13085
+ shouldUpdateField =
13086
+ shouldUpdateField ||
13087
+ (_proxyFormState.touchedFields &&
13088
+ isPreviousFieldTouched !== isBlurEvent);
13089
+ }
13090
+ }
13091
+ shouldUpdateField && shouldRender && _subjects.state.next(output);
13092
+ return shouldUpdateField ? output : {};
13093
+ };
13094
+ const shouldRenderByError = (name, isValid, error, fieldState) => {
13095
+ const previousFieldError = get(_formState.errors, name);
13096
+ const shouldUpdateValid = _proxyFormState.isValid &&
13097
+ isBoolean(isValid) &&
13098
+ _formState.isValid !== isValid;
13099
+ if (props.delayError && error) {
13100
+ delayErrorCallback = debounce(() => updateErrors(name, error));
13101
+ delayErrorCallback(props.delayError);
13102
+ }
13103
+ else {
13104
+ clearTimeout(timer);
13105
+ delayErrorCallback = null;
13106
+ error
13107
+ ? set(_formState.errors, name, error)
13108
+ : unset(_formState.errors, name);
13109
+ }
13110
+ if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) ||
13111
+ !isEmptyObject(fieldState) ||
13112
+ shouldUpdateValid) {
13113
+ const updatedFormState = {
13114
+ ...fieldState,
13115
+ ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
13116
+ errors: _formState.errors,
13117
+ name,
13118
+ };
13119
+ _formState = {
13120
+ ..._formState,
13121
+ ...updatedFormState,
13122
+ };
13123
+ _subjects.state.next(updatedFormState);
13124
+ }
13125
+ _updateIsValidating(false);
13126
+ };
13127
+ const _executeSchema = async (name) => _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
13128
+ const executeSchemaAndUpdateState = async (names) => {
13129
+ const { errors } = await _executeSchema(names);
13130
+ if (names) {
13131
+ for (const name of names) {
13132
+ const error = get(errors, name);
13133
+ error
13134
+ ? set(_formState.errors, name, error)
13135
+ : unset(_formState.errors, name);
13136
+ }
13137
+ }
13138
+ else {
13139
+ _formState.errors = errors;
13140
+ }
13141
+ return errors;
13142
+ };
13143
+ const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = {
13144
+ valid: true,
13145
+ }) => {
13146
+ for (const name in fields) {
13147
+ const field = fields[name];
13148
+ if (field) {
13149
+ const { _f, ...fieldValue } = field;
13150
+ if (_f) {
13151
+ const isFieldArrayRoot = _names.array.has(_f.name);
13152
+ const fieldError = await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
13153
+ if (fieldError[_f.name]) {
13154
+ context.valid = false;
13155
+ if (shouldOnlyCheckValid) {
13156
+ break;
13157
+ }
13158
+ }
13159
+ !shouldOnlyCheckValid &&
13160
+ (get(fieldError, _f.name)
13161
+ ? isFieldArrayRoot
13162
+ ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name)
13163
+ : set(_formState.errors, _f.name, fieldError[_f.name])
13164
+ : unset(_formState.errors, _f.name));
13165
+ }
13166
+ fieldValue &&
13167
+ (await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context));
13168
+ }
13169
+ }
13170
+ return context.valid;
13171
+ };
13172
+ const _removeUnmounted = () => {
13173
+ for (const name of _names.unMount) {
13174
+ const field = get(_fields, name);
13175
+ field &&
13176
+ (field._f.refs
13177
+ ? field._f.refs.every((ref) => !live(ref))
13178
+ : !live(field._f.ref)) &&
13179
+ unregister(name);
13180
+ }
13181
+ _names.unMount = new Set();
13182
+ };
13183
+ const _getDirty = (name, data) => (name && data && set(_formValues, name, data),
13184
+ !deepEqual(getValues(), _defaultValues));
13185
+ const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
13186
+ ...(_state.mount
13187
+ ? _formValues
13188
+ : isUndefined(defaultValue)
13189
+ ? _defaultValues
13190
+ : isString(names)
13191
+ ? { [names]: defaultValue }
13192
+ : defaultValue),
13193
+ }, isGlobal, defaultValue);
13194
+ const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
13195
+ const setFieldValue = (name, value, options = {}) => {
13196
+ const field = get(_fields, name);
13197
+ let fieldValue = value;
13198
+ if (field) {
13199
+ const fieldReference = field._f;
13200
+ if (fieldReference) {
13201
+ !fieldReference.disabled &&
13202
+ set(_formValues, name, getFieldValueAs(value, fieldReference));
13203
+ fieldValue =
13204
+ isHTMLElement(fieldReference.ref) && isNullOrUndefined(value)
13205
+ ? ''
13206
+ : value;
13207
+ if (isMultipleSelect(fieldReference.ref)) {
13208
+ [...fieldReference.ref.options].forEach((optionRef) => (optionRef.selected = fieldValue.includes(optionRef.value)));
13209
+ }
13210
+ else if (fieldReference.refs) {
13211
+ if (isCheckBoxInput(fieldReference.ref)) {
13212
+ fieldReference.refs.length > 1
13213
+ ? fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) &&
13214
+ (checkboxRef.checked = Array.isArray(fieldValue)
13215
+ ? !!fieldValue.find((data) => data === checkboxRef.value)
13216
+ : fieldValue === checkboxRef.value))
13217
+ : fieldReference.refs[0] &&
13218
+ (fieldReference.refs[0].checked = !!fieldValue);
13219
+ }
13220
+ else {
13221
+ fieldReference.refs.forEach((radioRef) => (radioRef.checked = radioRef.value === fieldValue));
13222
+ }
13223
+ }
13224
+ else if (isFileInput(fieldReference.ref)) {
13225
+ fieldReference.ref.value = '';
13226
+ }
13227
+ else {
13228
+ fieldReference.ref.value = fieldValue;
13229
+ if (!fieldReference.ref.type) {
13230
+ _subjects.values.next({
13231
+ name,
13232
+ values: { ..._formValues },
13233
+ });
13234
+ }
13235
+ }
13236
+ }
13237
+ }
13238
+ (options.shouldDirty || options.shouldTouch) &&
13239
+ updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
13240
+ options.shouldValidate && trigger(name);
13241
+ };
13242
+ const setValues = (name, value, options) => {
13243
+ for (const fieldKey in value) {
13244
+ const fieldValue = value[fieldKey];
13245
+ const fieldName = `${name}.${fieldKey}`;
13246
+ const field = get(_fields, fieldName);
13247
+ (_names.array.has(name) ||
13248
+ !isPrimitive(fieldValue) ||
13249
+ (field && !field._f)) &&
13250
+ !isDateObject(fieldValue)
13251
+ ? setValues(fieldName, fieldValue, options)
13252
+ : setFieldValue(fieldName, fieldValue, options);
13253
+ }
13254
+ };
13255
+ const setValue = (name, value, options = {}) => {
13256
+ const field = get(_fields, name);
13257
+ const isFieldArray = _names.array.has(name);
13258
+ const cloneValue = cloneObject(value);
13259
+ set(_formValues, name, cloneValue);
13260
+ if (isFieldArray) {
13261
+ _subjects.array.next({
13262
+ name,
13263
+ values: { ..._formValues },
13264
+ });
13265
+ if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) &&
13266
+ options.shouldDirty) {
13267
+ _subjects.state.next({
13268
+ name,
13269
+ dirtyFields: getDirtyFields(_defaultValues, _formValues),
13270
+ isDirty: _getDirty(name, cloneValue),
13271
+ });
13272
+ }
13273
+ }
13274
+ else {
13275
+ field && !field._f && !isNullOrUndefined(cloneValue)
13276
+ ? setValues(name, cloneValue, options)
13277
+ : setFieldValue(name, cloneValue, options);
13278
+ }
13279
+ isWatched(name, _names) && _subjects.state.next({ ..._formState });
13280
+ _subjects.values.next({
13281
+ name,
13282
+ values: { ..._formValues },
13283
+ });
13284
+ !_state.mount && flushRootRender();
13285
+ };
13286
+ const onChange = async (event) => {
13287
+ const target = event.target;
13288
+ let name = target.name;
13289
+ let isFieldValueUpdated = true;
13290
+ const field = get(_fields, name);
13291
+ const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
13292
+ if (field) {
13293
+ let error;
13294
+ let isValid;
13295
+ const fieldValue = getCurrentFieldValue();
13296
+ const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
13297
+ const shouldSkipValidation = (!hasValidation(field._f) &&
13298
+ !_options.resolver &&
13299
+ !get(_formState.errors, name) &&
13300
+ !field._f.deps) ||
13301
+ skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
13302
+ const watched = isWatched(name, _names, isBlurEvent);
13303
+ set(_formValues, name, fieldValue);
13304
+ if (isBlurEvent) {
13305
+ field._f.onBlur && field._f.onBlur(event);
13306
+ delayErrorCallback && delayErrorCallback(0);
13307
+ }
13308
+ else if (field._f.onChange) {
13309
+ field._f.onChange(event);
13310
+ }
13311
+ const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
13312
+ const shouldRender = !isEmptyObject(fieldState) || watched;
13313
+ !isBlurEvent &&
13314
+ _subjects.values.next({
13315
+ name,
13316
+ type: event.type,
13317
+ values: { ..._formValues },
13318
+ });
13319
+ if (shouldSkipValidation) {
13320
+ _proxyFormState.isValid && _updateValid();
13321
+ return (shouldRender &&
13322
+ _subjects.state.next({ name, ...(watched ? {} : fieldState) }));
13323
+ }
13324
+ !isBlurEvent && watched && _subjects.state.next({ ..._formState });
13325
+ _updateIsValidating(true);
13326
+ if (_options.resolver) {
13327
+ const { errors } = await _executeSchema([name]);
13328
+ const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
13329
+ const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
13330
+ error = errorLookupResult.error;
13331
+ name = errorLookupResult.name;
13332
+ isValid = isEmptyObject(errors);
13333
+ }
13334
+ else {
13335
+ error = (await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
13336
+ isFieldValueUpdated =
13337
+ isNaN(fieldValue) ||
13338
+ fieldValue === get(_formValues, name, fieldValue);
13339
+ if (isFieldValueUpdated) {
13340
+ if (error) {
13341
+ isValid = false;
13342
+ }
13343
+ else if (_proxyFormState.isValid) {
13344
+ isValid = await executeBuiltInValidation(_fields, true);
13345
+ }
13346
+ }
13347
+ }
13348
+ if (isFieldValueUpdated) {
13349
+ field._f.deps &&
13350
+ trigger(field._f.deps);
13351
+ shouldRenderByError(name, isValid, error, fieldState);
13352
+ }
13353
+ }
13354
+ };
13355
+ const trigger = async (name, options = {}) => {
13356
+ let isValid;
13357
+ let validationResult;
13358
+ const fieldNames = convertToArrayPayload(name);
13359
+ _updateIsValidating(true);
13360
+ if (_options.resolver) {
13361
+ const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
13362
+ isValid = isEmptyObject(errors);
13363
+ validationResult = name
13364
+ ? !fieldNames.some((name) => get(errors, name))
13365
+ : isValid;
13366
+ }
13367
+ else if (name) {
13368
+ validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
13369
+ const field = get(_fields, fieldName);
13370
+ return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
13371
+ }))).every(Boolean);
13372
+ !(!validationResult && !_formState.isValid) && _updateValid();
13373
+ }
13374
+ else {
13375
+ validationResult = isValid = await executeBuiltInValidation(_fields);
13376
+ }
13377
+ _subjects.state.next({
13378
+ ...(!isString(name) ||
13379
+ (_proxyFormState.isValid && isValid !== _formState.isValid)
13380
+ ? {}
13381
+ : { name }),
13382
+ ...(_options.resolver || !name ? { isValid } : {}),
13383
+ errors: _formState.errors,
13384
+ isValidating: false,
13385
+ });
13386
+ options.shouldFocus &&
13387
+ !validationResult &&
13388
+ focusFieldBy(_fields, (key) => key && get(_formState.errors, key), name ? fieldNames : _names.mount);
13389
+ return validationResult;
13390
+ };
13391
+ const getValues = (fieldNames) => {
13392
+ const values = {
13393
+ ..._defaultValues,
13394
+ ...(_state.mount ? _formValues : {}),
13395
+ };
13396
+ return isUndefined(fieldNames)
13397
+ ? values
13398
+ : isString(fieldNames)
13399
+ ? get(values, fieldNames)
13400
+ : fieldNames.map((name) => get(values, name));
13401
+ };
13402
+ const getFieldState = (name, formState) => ({
13403
+ invalid: !!get((formState || _formState).errors, name),
13404
+ isDirty: !!get((formState || _formState).dirtyFields, name),
13405
+ isTouched: !!get((formState || _formState).touchedFields, name),
13406
+ error: get((formState || _formState).errors, name),
13407
+ });
13408
+ const clearErrors = (name) => {
13409
+ name &&
13410
+ convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
13411
+ _subjects.state.next({
13412
+ errors: name ? _formState.errors : {},
13413
+ });
13414
+ };
13415
+ const setError = (name, error, options) => {
13416
+ const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
13417
+ set(_formState.errors, name, {
13418
+ ...error,
13419
+ ref,
13420
+ });
13421
+ _subjects.state.next({
13422
+ name,
13423
+ errors: _formState.errors,
13424
+ isValid: false,
13425
+ });
13426
+ options && options.shouldFocus && ref && ref.focus && ref.focus();
13427
+ };
13428
+ const watch = (name, defaultValue) => isFunction(name)
13429
+ ? _subjects.values.subscribe({
13430
+ next: (payload) => name(_getWatch(undefined, defaultValue), payload),
13431
+ })
13432
+ : _getWatch(name, defaultValue, true);
13433
+ const unregister = (name, options = {}) => {
13434
+ for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
13435
+ _names.mount.delete(fieldName);
13436
+ _names.array.delete(fieldName);
13437
+ if (!options.keepValue) {
13438
+ unset(_fields, fieldName);
13439
+ unset(_formValues, fieldName);
13440
+ }
13441
+ !options.keepError && unset(_formState.errors, fieldName);
13442
+ !options.keepDirty && unset(_formState.dirtyFields, fieldName);
13443
+ !options.keepTouched && unset(_formState.touchedFields, fieldName);
13444
+ !_options.shouldUnregister &&
13445
+ !options.keepDefaultValue &&
13446
+ unset(_defaultValues, fieldName);
13447
+ }
13448
+ _subjects.values.next({
13449
+ values: { ..._formValues },
13450
+ });
13451
+ _subjects.state.next({
13452
+ ..._formState,
13453
+ ...(!options.keepDirty ? {} : { isDirty: _getDirty() }),
13454
+ });
13455
+ !options.keepIsValid && _updateValid();
13456
+ };
13457
+ const _updateDisabledField = ({ disabled, name, field, fields, }) => {
13458
+ if (isBoolean(disabled)) {
13459
+ const value = disabled
13460
+ ? undefined
13461
+ : get(_formValues, name, getFieldValue(field ? field._f : get(fields, name)._f));
13462
+ set(_formValues, name, value);
13463
+ updateTouchAndDirty(name, value, false, false, true);
13464
+ }
13465
+ };
13466
+ const register = (name, options = {}) => {
13467
+ let field = get(_fields, name);
13468
+ const disabledIsDefined = isBoolean(options.disabled);
13469
+ set(_fields, name, {
13470
+ ...(field || {}),
13471
+ _f: {
13472
+ ...(field && field._f ? field._f : { ref: { name } }),
13473
+ name,
13474
+ mount: true,
13475
+ ...options,
13476
+ },
13477
+ });
13478
+ _names.mount.add(name);
13479
+ if (field) {
13480
+ _updateDisabledField({
13481
+ field,
13482
+ disabled: options.disabled,
13483
+ name,
13484
+ });
13485
+ }
13486
+ else {
13487
+ updateValidAndValue(name, true, options.value);
13488
+ }
13489
+ return {
13490
+ ...(disabledIsDefined ? { disabled: options.disabled } : {}),
13491
+ ...(_options.progressive
13492
+ ? {
13493
+ required: !!options.required,
13494
+ min: getRuleValue(options.min),
13495
+ max: getRuleValue(options.max),
13496
+ minLength: getRuleValue(options.minLength),
13497
+ maxLength: getRuleValue(options.maxLength),
13498
+ pattern: getRuleValue(options.pattern),
13499
+ }
13500
+ : {}),
13501
+ name,
13502
+ onChange,
13503
+ onBlur: onChange,
13504
+ ref: (ref) => {
13505
+ if (ref) {
13506
+ register(name, options);
13507
+ field = get(_fields, name);
13508
+ const fieldRef = isUndefined(ref.value)
13509
+ ? ref.querySelectorAll
13510
+ ? ref.querySelectorAll('input,select,textarea')[0] || ref
13511
+ : ref
13512
+ : ref;
13513
+ const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
13514
+ const refs = field._f.refs || [];
13515
+ if (radioOrCheckbox
13516
+ ? refs.find((option) => option === fieldRef)
13517
+ : fieldRef === field._f.ref) {
13518
+ return;
13519
+ }
13520
+ set(_fields, name, {
13521
+ _f: {
13522
+ ...field._f,
13523
+ ...(radioOrCheckbox
13524
+ ? {
13525
+ refs: [
13526
+ ...refs.filter(live),
13527
+ fieldRef,
13528
+ ...(Array.isArray(get(_defaultValues, name)) ? [{}] : []),
13529
+ ],
13530
+ ref: { type: fieldRef.type, name },
13531
+ }
13532
+ : { ref: fieldRef }),
13533
+ },
13534
+ });
13535
+ updateValidAndValue(name, false, undefined, fieldRef);
13536
+ }
13537
+ else {
13538
+ field = get(_fields, name, {});
13539
+ if (field._f) {
13540
+ field._f.mount = false;
13541
+ }
13542
+ (_options.shouldUnregister || options.shouldUnregister) &&
13543
+ !(isNameInFieldArray(_names.array, name) && _state.action) &&
13544
+ _names.unMount.add(name);
13545
+ }
13546
+ },
13547
+ };
13548
+ };
13549
+ const _focusError = () => _options.shouldFocusError &&
13550
+ focusFieldBy(_fields, (key) => key && get(_formState.errors, key), _names.mount);
13551
+ const handleSubmit = (onValid, onInvalid) => async (e) => {
13552
+ if (e) {
13553
+ e.preventDefault && e.preventDefault();
13554
+ e.persist && e.persist();
13555
+ }
13556
+ let fieldValues = cloneObject(_formValues);
13557
+ _subjects.state.next({
13558
+ isSubmitting: true,
13559
+ });
13560
+ if (_options.resolver) {
13561
+ const { errors, values } = await _executeSchema();
13562
+ _formState.errors = errors;
13563
+ fieldValues = values;
13564
+ }
13565
+ else {
13566
+ await executeBuiltInValidation(_fields);
13567
+ }
13568
+ unset(_formState.errors, 'root');
13569
+ if (isEmptyObject(_formState.errors)) {
13570
+ _subjects.state.next({
13571
+ errors: {},
13572
+ });
13573
+ await onValid(fieldValues, e);
13574
+ }
13575
+ else {
13576
+ if (onInvalid) {
13577
+ await onInvalid({ ..._formState.errors }, e);
13578
+ }
13579
+ _focusError();
13580
+ setTimeout(_focusError);
13581
+ }
13582
+ _subjects.state.next({
13583
+ isSubmitted: true,
13584
+ isSubmitting: false,
13585
+ isSubmitSuccessful: isEmptyObject(_formState.errors),
13586
+ submitCount: _formState.submitCount + 1,
13587
+ errors: _formState.errors,
13588
+ });
13589
+ };
13590
+ const resetField = (name, options = {}) => {
13591
+ if (get(_fields, name)) {
13592
+ if (isUndefined(options.defaultValue)) {
13593
+ setValue(name, get(_defaultValues, name));
13594
+ }
13595
+ else {
13596
+ setValue(name, options.defaultValue);
13597
+ set(_defaultValues, name, options.defaultValue);
13598
+ }
13599
+ if (!options.keepTouched) {
13600
+ unset(_formState.touchedFields, name);
13601
+ }
13602
+ if (!options.keepDirty) {
13603
+ unset(_formState.dirtyFields, name);
13604
+ _formState.isDirty = options.defaultValue
13605
+ ? _getDirty(name, get(_defaultValues, name))
13606
+ : _getDirty();
13607
+ }
13608
+ if (!options.keepError) {
13609
+ unset(_formState.errors, name);
13610
+ _proxyFormState.isValid && _updateValid();
13611
+ }
13612
+ _subjects.state.next({ ..._formState });
13613
+ }
13614
+ };
13615
+ const _reset = (formValues, keepStateOptions = {}) => {
13616
+ const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
13617
+ const cloneUpdatedValues = cloneObject(updatedValues);
13618
+ const values = formValues && !isEmptyObject(formValues)
13619
+ ? cloneUpdatedValues
13620
+ : _defaultValues;
13621
+ if (!keepStateOptions.keepDefaultValues) {
13622
+ _defaultValues = updatedValues;
13623
+ }
13624
+ if (!keepStateOptions.keepValues) {
13625
+ if (keepStateOptions.keepDirtyValues || shouldCaptureDirtyFields) {
13626
+ for (const fieldName of _names.mount) {
13627
+ get(_formState.dirtyFields, fieldName)
13628
+ ? set(values, fieldName, get(_formValues, fieldName))
13629
+ : setValue(fieldName, get(values, fieldName));
13630
+ }
13631
+ }
13632
+ else {
13633
+ if (isWeb && isUndefined(formValues)) {
13634
+ for (const name of _names.mount) {
13635
+ const field = get(_fields, name);
13636
+ if (field && field._f) {
13637
+ const fieldReference = Array.isArray(field._f.refs)
13638
+ ? field._f.refs[0]
13639
+ : field._f.ref;
13640
+ if (isHTMLElement(fieldReference)) {
13641
+ const form = fieldReference.closest('form');
13642
+ if (form) {
13643
+ form.reset();
13644
+ break;
13645
+ }
13646
+ }
13647
+ }
13648
+ }
13649
+ }
13650
+ _fields = {};
13651
+ }
13652
+ _formValues = props.shouldUnregister
13653
+ ? keepStateOptions.keepDefaultValues
13654
+ ? cloneObject(_defaultValues)
13655
+ : {}
13656
+ : cloneObject(values);
13657
+ _subjects.array.next({
13658
+ values: { ...values },
13659
+ });
13660
+ _subjects.values.next({
13661
+ values: { ...values },
13662
+ });
13663
+ }
13664
+ _names = {
13665
+ mount: new Set(),
13666
+ unMount: new Set(),
13667
+ array: new Set(),
13668
+ watch: new Set(),
13669
+ watchAll: false,
13670
+ focus: '',
13671
+ };
13672
+ !_state.mount && flushRootRender();
13673
+ _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid;
13674
+ _state.watch = !!props.shouldUnregister;
13675
+ _subjects.state.next({
13676
+ submitCount: keepStateOptions.keepSubmitCount
13677
+ ? _formState.submitCount
13678
+ : 0,
13679
+ isDirty: keepStateOptions.keepDirty
13680
+ ? _formState.isDirty
13681
+ : !!(keepStateOptions.keepDefaultValues &&
13682
+ !deepEqual(formValues, _defaultValues)),
13683
+ isSubmitted: keepStateOptions.keepIsSubmitted
13684
+ ? _formState.isSubmitted
13685
+ : false,
13686
+ dirtyFields: keepStateOptions.keepDirtyValues
13687
+ ? _formState.dirtyFields
13688
+ : keepStateOptions.keepDefaultValues && formValues
13689
+ ? getDirtyFields(_defaultValues, formValues)
13690
+ : {},
13691
+ touchedFields: keepStateOptions.keepTouched
13692
+ ? _formState.touchedFields
13693
+ : {},
13694
+ errors: keepStateOptions.keepErrors ? _formState.errors : {},
13695
+ isSubmitting: false,
13696
+ isSubmitSuccessful: false,
13697
+ });
13698
+ };
13699
+ const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues)
13700
+ ? formValues(_formValues)
13701
+ : formValues, keepStateOptions);
13702
+ const setFocus = (name, options = {}) => {
13703
+ const field = get(_fields, name);
13704
+ const fieldReference = field && field._f;
13705
+ if (fieldReference) {
13706
+ const fieldRef = fieldReference.refs
13707
+ ? fieldReference.refs[0]
13708
+ : fieldReference.ref;
13709
+ if (fieldRef.focus) {
13710
+ fieldRef.focus();
13711
+ options.shouldSelect && fieldRef.select();
13712
+ }
13713
+ }
13714
+ };
13715
+ const _updateFormState = (updatedFormState) => {
13716
+ _formState = {
13717
+ ..._formState,
13718
+ ...updatedFormState,
13719
+ };
13720
+ };
13721
+ const _resetDefaultValues = () => isFunction(_options.defaultValues) &&
13722
+ _options.defaultValues().then((values) => {
13723
+ reset(values, _options.resetOptions);
13724
+ _subjects.state.next({
13725
+ isLoading: false,
13726
+ });
13727
+ });
13728
+ return {
13729
+ control: {
13730
+ register,
13731
+ unregister,
13732
+ getFieldState,
13733
+ handleSubmit,
13734
+ setError,
13735
+ _executeSchema,
13736
+ _getWatch,
13737
+ _getDirty,
13738
+ _updateValid,
13739
+ _removeUnmounted,
13740
+ _updateFieldArray,
13741
+ _updateDisabledField,
13742
+ _getFieldArray,
13743
+ _reset,
13744
+ _resetDefaultValues,
13745
+ _updateFormState,
13746
+ _subjects,
13747
+ _proxyFormState,
13748
+ get _fields() {
13749
+ return _fields;
13750
+ },
13751
+ get _formValues() {
13752
+ return _formValues;
13753
+ },
13754
+ get _state() {
13755
+ return _state;
13756
+ },
13757
+ set _state(value) {
13758
+ _state = value;
13759
+ },
13760
+ get _defaultValues() {
13761
+ return _defaultValues;
13762
+ },
13763
+ get _names() {
13764
+ return _names;
13765
+ },
13766
+ set _names(value) {
13767
+ _names = value;
13768
+ },
13769
+ get _formState() {
13770
+ return _formState;
13771
+ },
13772
+ set _formState(value) {
13773
+ _formState = value;
13774
+ },
13775
+ get _options() {
13776
+ return _options;
13777
+ },
13778
+ set _options(value) {
13779
+ _options = {
13780
+ ..._options,
13781
+ ...value,
13782
+ };
13783
+ },
13784
+ },
13785
+ trigger,
13786
+ register,
13787
+ handleSubmit,
13788
+ watch,
13789
+ setValue,
13790
+ getValues,
13791
+ reset,
13792
+ resetField,
13793
+ clearErrors,
13794
+ unregister,
13795
+ setError,
13796
+ setFocus,
13797
+ getFieldState,
13798
+ };
13799
+ }
13800
+
13801
+ /**
13802
+ * Custom hook to manage the entire form.
13803
+ *
13804
+ * @remarks
13805
+ * [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)
13806
+ *
13807
+ * @param props - form configuration and validation parameters.
13808
+ *
13809
+ * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
13810
+ *
13811
+ * @example
13812
+ * ```tsx
13813
+ * function App() {
13814
+ * const { register, handleSubmit, watch, formState: { errors } } = useForm();
13815
+ * const onSubmit = data => console.log(data);
13816
+ *
13817
+ * console.log(watch("example"));
13818
+ *
13819
+ * return (
13820
+ * <form onSubmit={handleSubmit(onSubmit)}>
13821
+ * <input defaultValue="test" {...register("example")} />
13822
+ * <input {...register("exampleRequired", { required: true })} />
13823
+ * {errors.exampleRequired && <span>This field is required</span>}
13824
+ * <button>Submit</button>
13825
+ * </form>
13826
+ * );
13827
+ * }
13828
+ * ```
13829
+ */
13830
+ function useForm(props = {}) {
13831
+ const _formControl = React__default.useRef();
13832
+ const _values = React__default.useRef();
13833
+ const [formState, updateFormState] = React__default.useState({
13834
+ isDirty: false,
13835
+ isValidating: false,
13836
+ isLoading: isFunction(props.defaultValues),
13837
+ isSubmitted: false,
13838
+ isSubmitting: false,
13839
+ isSubmitSuccessful: false,
13840
+ isValid: false,
13841
+ submitCount: 0,
13842
+ dirtyFields: {},
13843
+ touchedFields: {},
13844
+ errors: {},
13845
+ defaultValues: isFunction(props.defaultValues)
13846
+ ? undefined
13847
+ : props.defaultValues,
13848
+ });
13849
+ if (!_formControl.current) {
13850
+ _formControl.current = {
13851
+ ...createFormControl(props, () => updateFormState((formState) => ({ ...formState }))),
13852
+ formState,
13853
+ };
13854
+ }
13855
+ const control = _formControl.current.control;
13856
+ control._options = props;
13857
+ useSubscribe({
13858
+ subject: control._subjects.state,
13859
+ next: (value) => {
13860
+ if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
13861
+ updateFormState({ ...control._formState });
13862
+ }
13863
+ },
13864
+ });
13865
+ React__default.useEffect(() => {
13866
+ if (props.values && !deepEqual(props.values, _values.current)) {
13867
+ control._reset(props.values, control._options.resetOptions);
13868
+ _values.current = props.values;
13869
+ }
13870
+ else {
13871
+ control._resetDefaultValues();
13872
+ }
13873
+ }, [props.values, control]);
13874
+ React__default.useEffect(() => {
13875
+ if (!control._state.mount) {
13876
+ control._updateValid();
13877
+ control._state.mount = true;
13878
+ }
13879
+ if (control._state.watch) {
13880
+ control._state.watch = false;
13881
+ control._subjects.state.next({ ...control._formState });
13882
+ }
13883
+ control._removeUnmounted();
13884
+ });
13885
+ _formControl.current.formState = getProxyFormState(formState, control);
13886
+ return _formControl.current;
13887
+ }
13888
+
13889
+ var _excluded$8 = ["ref"];
13890
+
13891
+ var _templateObject$Q, _templateObject2$d, _templateObject3$8, _templateObject4$7, _templateObject5$5;
13892
+ var OptionsRow = styled__default.div(_templateObject$Q || (_templateObject$Q = _taggedTemplateLiteral(["\n display: flex;\n flex-wrap: nowrap;\n flex-direction: row;\n"])));
13893
+ var OptionsRowDescription = styled__default.div(_templateObject2$d || (_templateObject2$d = _taggedTemplateLiteral(["\n flex-basis: 30%;\n margin-right: 10px;\n"])));
13894
+ var Options = styled__default.div(_templateObject3$8 || (_templateObject3$8 = _taggedTemplateLiteral(["\n display: flex;\n flex-wrap: nowrap;\n flex-direction: row;\n flex-basis: 60%;\n"])));
13895
+ var OptionRadioInputContainer = styled__default.span(_templateObject4$7 || (_templateObject4$7 = _taggedTemplateLiteral(["\n flex-basis: 50%;\n"])));
13896
+ var OptionRadioInput = styled__default.input(_templateObject5$5 || (_templateObject5$5 = _taggedTemplateLiteral(["\n margin-right: 5px;\n"])));
13897
+
13898
+ var CommunicationPreferenceOptionsRenderer = function CommunicationPreferenceOptionsRenderer(_ref) {
13899
+ var description = _ref.description,
13900
+ control = _ref.control,
13901
+ name = _ref.name,
13902
+ is_disabled = _ref.is_disabled,
13903
+ options = _ref.options,
13904
+ defaultValue = _ref.defaultValue,
13905
+ setValue = _ref.setValue;
13906
+
13907
+ var _useController = useController({
13908
+ name: name,
13909
+ control: control,
13910
+ defaultValue: defaultValue
13911
+ }),
13912
+ _useController$field = _useController.field,
13913
+ ref = _useController$field.ref,
13914
+ inputProps = _objectWithoutProperties(_useController$field, _excluded$8),
13915
+ _useController$fieldS = _useController.fieldState,
13916
+ invalid = _useController$fieldS.invalid,
13917
+ error = _useController$fieldS.error;
13918
+
13919
+ React.useEffect(function () {
13920
+ if (defaultValue) {
13921
+ setValue(name, defaultValue);
13922
+ }
13923
+ }, [defaultValue, name, setValue]);
13924
+ return /*#__PURE__*/React__default.createElement(OptionsRow, null, /*#__PURE__*/React__default.createElement(OptionsRowDescription, null, description), is_disabled ? /*#__PURE__*/React__default.createElement(Options, null, options.map(function (option) {
13925
+ return /*#__PURE__*/React__default.createElement(OptionRadioInputContainer, {
13926
+ key: option.value
13927
+ }, /*#__PURE__*/React__default.createElement(OptionRadioInput, _extends({
13928
+ type: "radio",
13929
+ ref: ref
13930
+ }, inputProps, {
13931
+ value: option.value,
13932
+ checked: inputProps.value === option.value.toString(),
13933
+ disabled: true
13934
+ })), option.label);
13935
+ })) : /*#__PURE__*/React__default.createElement(Options, null, options.map(function (option) {
13936
+ return /*#__PURE__*/React__default.createElement(OptionRadioInputContainer, {
13937
+ key: option.value
13938
+ }, /*#__PURE__*/React__default.createElement(OptionRadioInput, _extends({
13939
+ type: "radio",
13940
+ ref: ref
13941
+ }, inputProps, {
13942
+ value: option.value,
13943
+ checked: inputProps.value === option.value.toString()
13944
+ })), option.label);
13945
+ })), invalid && /*#__PURE__*/React__default.createElement("span", {
13946
+ className: "form__error"
13947
+ }, error === null || error === void 0 ? void 0 : error.message));
13948
+ };
13949
+
13950
+ var _templateObject$R, _templateObject2$e;
13951
+ var SectionContainer = styled__default.div(_templateObject$R || (_templateObject$R = _taggedTemplateLiteral(["\n border-top: flex 1px solid ", ";\n border-top-width: calc(100% - 50px);\n padding: 5px 10px;\n"])), function (props) {
13952
+ return props.theme.colors.primary;
13953
+ });
13954
+ var SectionHeading = styled__default.div(_templateObject2$e || (_templateObject2$e = _taggedTemplateLiteral(["\n padding: 5px 10px;\n"])));
13955
+
13956
+ var CommunicationPreferenceSection = function CommunicationPreferenceSection(_ref) {
13957
+ var section_heading = _ref.section_heading,
13958
+ description = _ref.description,
13959
+ control = _ref.control,
13960
+ name = _ref.name,
13961
+ is_disabled = _ref.is_disabled,
13962
+ options = _ref.options,
13963
+ defaultValue = _ref.defaultValue,
13964
+ setValue = _ref.setValue;
13965
+ return /*#__PURE__*/React__default.createElement(SectionContainer, null, /*#__PURE__*/React__default.createElement(SectionHeading, null, section_heading), /*#__PURE__*/React__default.createElement(CommunicationPreferenceOptionsRenderer, {
13966
+ description: description,
13967
+ control: control,
13968
+ name: name,
13969
+ is_disabled: is_disabled,
13970
+ options: options,
13971
+ defaultValue: defaultValue,
13972
+ setValue: setValue
13973
+ }));
13974
+ };
13975
+
13976
+ var CommunicationPreferenceSection$1 = themed(CommunicationPreferenceSection);
13977
+
13978
+ var _templateObject$S, _templateObject2$f, _templateObject3$9;
13979
+ var CommunicationPreferenceContainer = styled__default.div(_templateObject$S || (_templateObject$S = _taggedTemplateLiteral(["\n border: solid 1px #d1d5dbff;\n"])));
13980
+ var EditButtonRow = styled__default.div(_templateObject2$f || (_templateObject2$f = _taggedTemplateLiteral(["\n display: flex;\n justify-content: end;\n padding: 10px 5px;\n"])));
13981
+ var SubmitButton = styled__default.input(_templateObject3$9 || (_templateObject3$9 = _taggedTemplateLiteral(["\n flex-basis: 15%;\n"])));
13982
+ var BaseRequest = {
13983
+ loading: false,
13984
+ success: false,
13985
+ failed: false
13986
+ };
13987
+
13988
+ var CommunicationPreferences = function CommunicationPreferences(_ref) {
13989
+ var header = _ref.header,
13990
+ requestInstance = _ref.requestInstance,
13991
+ updateNotificationsApi = _ref.updateNotificationsApi,
13992
+ preferenceData = _ref.preferenceData;
13993
+
13994
+ var _useForm = useForm(),
13995
+ handleSubmit = _useForm.handleSubmit,
13996
+ control = _useForm.control,
13997
+ setValue = _useForm.setValue;
13998
+
13999
+ var _useState = React.useState(_objectSpread2({}, BaseRequest)),
14000
+ _useState2 = _slicedToArray(_useState, 2),
14001
+ requestState = _useState2[0],
14002
+ setRequestState = _useState2[1];
14003
+
14004
+ var _useState3 = React.useState(false),
14005
+ _useState4 = _slicedToArray(_useState3, 2),
14006
+ isEditing = _useState4[0],
14007
+ setIsEditing = _useState4[1]; //
14008
+
14009
+
14010
+ var communicationOptions = [{
14011
+ label: 'WhatsApp',
14012
+ value: 'WHATSAPP'
14013
+ }, {
14014
+ label: 'Email',
14015
+ value: 'EMAIL'
14016
+ }];
14017
+
14018
+ var updateRequestState = function updateRequestState(obj) {
14019
+ setRequestState(_objectSpread2(_objectSpread2({}, BaseRequest), obj));
14020
+ };
14021
+
14022
+ var onSubmit = function onSubmit(form_data) {
14023
+ updateRequestState({
14024
+ loading: true
14025
+ });
14026
+ simpleRequest(requestInstance, updateNotificationsApi, method.POST, form_data, function () {
14027
+ updateRequestState({
14028
+ success: true,
14029
+ loading: false
14030
+ });
14031
+ success('Communication Preferences Updated.');
14032
+ setTimeout(function () {
14033
+ window.location.reload();
14034
+ }, 2000);
14035
+ }, function (data) {
14036
+ updateRequestState({
14037
+ failed: true,
14038
+ loading: false
14039
+ });
14040
+ var errorMessages = Object.keys(data).map(function (key) {
14041
+ return data[key];
14042
+ }).flat();
14043
+ error(errorMessages.map(function (message, key) {
14044
+ return /*#__PURE__*/React__default.createElement("div", {
14045
+ key: "error-".concat(key)
14046
+ }, message);
14047
+ }));
14048
+ });
14049
+ };
14050
+
14051
+ 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", {
14052
+ onSubmit: handleSubmit(onSubmit)
14053
+ }, /*#__PURE__*/React__default.createElement(CommunicationPreferenceSection$1, {
14054
+ section_heading: "Default",
14055
+ description: "How would you prefer to receive communication: ",
14056
+ control: control,
14057
+ name: "default_communication",
14058
+ options: communicationOptions,
14059
+ is_disabled: !isEditing,
14060
+ defaultValue: preferenceData.default_communication,
14061
+ setValue: setValue
14062
+ }), isEditing && /*#__PURE__*/React__default.createElement(EditButtonRow, null, /*#__PURE__*/React__default.createElement(SubmitButton, {
14063
+ type: "submit",
14064
+ value: "Save",
14065
+ className: "btn--luxity"
14066
+ })))), /*#__PURE__*/React__default.createElement(EditButtonRow, null, /*#__PURE__*/React__default.createElement("button", {
14067
+ type: "button",
14068
+ className: "btn--luxity",
14069
+ onClick: function onClick() {
14070
+ setIsEditing(!isEditing);
14071
+ }
14072
+ }, isEditing ? 'Cancel' : 'Edit')));
14073
+ };
14074
+
14075
+ var index$5 = themed(CommunicationPreferences);
14076
+
11886
14077
  exports.Accordion = index;
11887
14078
  exports.Checkbox = LuxityCheckbox;
11888
14079
  exports.CheckboxFormWrapper = FormWrapper;
14080
+ exports.CommunicationPreferences = index$5;
11889
14081
  exports.CountryCodeSelect = CountryCodeSelect;
11890
14082
  exports.CurrencyInputFormatter = CurrencyInputFormatter;
11891
14083
  exports.InterestCatSelector = CategoryInterestSelector;