@awell-health/ui-library 0.1.64 → 0.1.65

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/dist/index.js CHANGED
@@ -35035,22 +35035,92 @@ Check the top-level render call using <` + t + ">.");
35035
35035
 
35036
35036
  var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
35037
35037
 
35038
+ var isPlainObject = (tempObject) => {
35039
+ const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
35040
+ return isObject(prototypeCopy) && prototypeCopy.hasOwnProperty('isPrototypeOf');
35041
+ };
35042
+
35043
+ var isWeb = typeof window !== 'undefined' &&
35044
+ typeof window.HTMLElement !== 'undefined' &&
35045
+ typeof document !== 'undefined';
35046
+
35047
+ function cloneObject(data) {
35048
+ let copy;
35049
+ const isArray = Array.isArray(data);
35050
+ if (data instanceof Date) {
35051
+ copy = new Date(data);
35052
+ } else
35053
+ if (data instanceof Set) {
35054
+ copy = new Set(data);
35055
+ } else
35056
+ if (!(isWeb && (data instanceof Blob || data instanceof FileList)) && (
35057
+ isArray || isObject(data))) {
35058
+ copy = isArray ? [] : {};
35059
+ if (!isArray && !isPlainObject(data)) {
35060
+ copy = data;
35061
+ } else
35062
+ {
35063
+ for (const key in data) {
35064
+ if (data.hasOwnProperty(key)) {
35065
+ copy[key] = cloneObject(data[key]);
35066
+ }
35067
+ }
35068
+ }
35069
+ } else
35070
+ {
35071
+ return data;
35072
+ }
35073
+ return copy;
35074
+ }
35075
+
35038
35076
  var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
35039
35077
 
35040
35078
  var isUndefined = (val) => val === undefined;
35041
35079
 
35042
- var get = (obj, path, defaultValue) => {
35043
- if (!path || !isObject(obj)) {
35080
+ var get = (object, path, defaultValue) => {
35081
+ if (!path || !isObject(object)) {
35044
35082
  return defaultValue;
35045
35083
  }
35046
- const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], obj);
35047
- return isUndefined(result) || result === obj ?
35048
- isUndefined(obj[path]) ?
35084
+ const result = compact(path.split(/[,[\].]+?/)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], object);
35085
+ return isUndefined(result) || result === object ?
35086
+ isUndefined(object[path]) ?
35049
35087
  defaultValue :
35050
- obj[path] :
35088
+ object[path] :
35051
35089
  result;
35052
35090
  };
35053
35091
 
35092
+ var isBoolean = (value) => typeof value === 'boolean';
35093
+
35094
+ var isKey = (value) => /^\w*$/.test(value);
35095
+
35096
+ var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
35097
+
35098
+ var set = (object, path, value) => {
35099
+ let index = -1;
35100
+ const tempPath = isKey(path) ? [path] : stringToPath(path);
35101
+ const length = tempPath.length;
35102
+ const lastIndex = length - 1;
35103
+ while (++index < length) {
35104
+ const key = tempPath[index];
35105
+ let newValue = value;
35106
+ if (index !== lastIndex) {
35107
+ const objValue = object[key];
35108
+ newValue =
35109
+ isObject(objValue) || Array.isArray(objValue) ?
35110
+ objValue :
35111
+ !isNaN(+tempPath[index + 1]) ?
35112
+ [] :
35113
+ {};
35114
+ }
35115
+ if (key === '__proto__') {
35116
+ return;
35117
+ }
35118
+ object[key] = newValue;
35119
+ object = object[key];
35120
+ }
35121
+ return object;
35122
+ };
35123
+
35054
35124
  const EVENTS = {
35055
35125
  BLUR: 'blur',
35056
35126
  FOCUS_OUT: 'focusout',
@@ -35074,46 +35144,48 @@ Check the top-level render call using <` + t + ">.");
35074
35144
 
35075
35145
 
35076
35146
  const HookFormContext = /*#__PURE__*/React__default["default"].createContext(null);
35077
- /**
35078
- * 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}.
35079
- *
35080
- * @remarks
35081
- * [API](https://react-hook-form.com/api/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
35082
- *
35083
- * @returns return all useForm methods
35084
- *
35085
- * @example
35086
- * ```tsx
35087
- * function App() {
35088
- * const methods = useForm();
35089
- * const onSubmit = data => console.log(data);
35090
- *
35091
- * return (
35092
- * <FormProvider {...methods} >
35093
- * <form onSubmit={methods.handleSubmit(onSubmit)}>
35094
- * <NestedInput />
35095
- * <input type="submit" />
35096
- * </form>
35097
- * </FormProvider>
35098
- * );
35099
- * }
35100
- *
35101
- * function NestedInput() {
35102
- * const { register } = useFormContext(); // retrieve all hook methods
35103
- * return <input {...register("test")} />;
35104
- * }
35105
- * ```
35147
+ /**
35148
+ * 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}.
35149
+ *
35150
+ * @remarks
35151
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
35152
+ *
35153
+ * @returns return all useForm methods
35154
+ *
35155
+ * @example
35156
+ * ```tsx
35157
+ * function App() {
35158
+ * const methods = useForm();
35159
+ * const onSubmit = data => console.log(data);
35160
+ *
35161
+ * return (
35162
+ * <FormProvider {...methods} >
35163
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
35164
+ * <NestedInput />
35165
+ * <input type="submit" />
35166
+ * </form>
35167
+ * </FormProvider>
35168
+ * );
35169
+ * }
35170
+ *
35171
+ * function NestedInput() {
35172
+ * const { register } = useFormContext(); // retrieve all hook methods
35173
+ * return <input {...register("test")} />;
35174
+ * }
35175
+ * ```
35106
35176
  */
35107
35177
  const useFormContext = () => React__default["default"].useContext(HookFormContext);
35108
35178
 
35109
- var getProxyFormState = (formState, _proxyFormState, localProxyFormState, isRoot = true) => {
35110
- const result = {};
35179
+ var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
35180
+ const result = {
35181
+ defaultValues: control._defaultValues };
35182
+
35111
35183
  for (const key in formState) {
35112
35184
  Object.defineProperty(result, key, {
35113
35185
  get: () => {
35114
35186
  const _key = key;
35115
- if (_proxyFormState[_key] !== VALIDATION_MODE.all) {
35116
- _proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
35187
+ if (control._proxyFormState[_key] !== VALIDATION_MODE.all) {
35188
+ control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
35117
35189
  }
35118
35190
  localProxyFormState && (localProxyFormState[_key] = true);
35119
35191
  return formState[_key];
@@ -35125,7 +35197,8 @@ Check the top-level render call using <` + t + ">.");
35125
35197
 
35126
35198
  var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
35127
35199
 
35128
- var shouldRenderFormState = (formStateData, _proxyFormState, isRoot) => {
35200
+ var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
35201
+ updateFormState(formStateData);
35129
35202
  const { name, ...formState } = formStateData;
35130
35203
  return isEmptyObject(formState) ||
35131
35204
  Object.keys(formState).length >= Object.keys(_proxyFormState).length ||
@@ -35135,12 +35208,12 @@ Check the top-level render call using <` + t + ">.");
35135
35208
 
35136
35209
  var convertToArrayPayload = (value) => Array.isArray(value) ? value : [value];
35137
35210
 
35138
- var shouldSubscribeByName = (name, signalName, exact) => exact && signalName ?
35139
- name === signalName :
35140
- !name ||
35211
+ var shouldSubscribeByName = (name, signalName, exact) => !name ||
35141
35212
  !signalName ||
35142
35213
  name === signalName ||
35143
35214
  convertToArrayPayload(name).some((currentName) => currentName && (
35215
+ exact ?
35216
+ currentName === signalName :
35144
35217
  currentName.startsWith(signalName) ||
35145
35218
  signalName.startsWith(currentName)));
35146
35219
 
@@ -35148,187 +35221,161 @@ Check the top-level render call using <` + t + ">.");
35148
35221
  const _props = React__default["default"].useRef(props);
35149
35222
  _props.current = props;
35150
35223
  React__default["default"].useEffect(() => {
35151
- const tearDown = (subscription) => {
35152
- if (subscription) {
35153
- subscription.unsubscribe();
35154
- }
35155
- };
35156
35224
  const subscription = !props.disabled &&
35225
+ _props.current.subject &&
35157
35226
  _props.current.subject.subscribe({
35158
- next: _props.current.callback });
35227
+ next: _props.current.next });
35159
35228
 
35160
- return () => tearDown(subscription);
35229
+ return () => {
35230
+ subscription && subscription.unsubscribe();
35231
+ };
35161
35232
  }, [props.disabled]);
35162
35233
  }
35163
35234
 
35164
- /**
35165
- * 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.
35166
- *
35167
- * @remarks
35168
- * [API](https://react-hook-form.com/api/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
35169
- *
35170
- * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
35171
- *
35172
- * @example
35173
- * ```tsx
35174
- * function App() {
35175
- * const { register, handleSubmit, control } = useForm({
35176
- * defaultValues: {
35177
- * firstName: "firstName"
35178
- * }});
35179
- * const { dirtyFields } = useFormState({
35180
- * control
35181
- * });
35182
- * const onSubmit = (data) => console.log(data);
35183
- *
35184
- * return (
35185
- * <form onSubmit={handleSubmit(onSubmit)}>
35186
- * <input {...register("firstName")} placeholder="First Name" />
35187
- * {dirtyFields.firstName && <p>Field is dirty.</p>}
35188
- * <input type="submit" />
35189
- * </form>
35190
- * );
35191
- * }
35192
- * ```
35235
+ /**
35236
+ * 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.
35237
+ *
35238
+ * @remarks
35239
+ * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
35240
+ *
35241
+ * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
35242
+ *
35243
+ * @example
35244
+ * ```tsx
35245
+ * function App() {
35246
+ * const { register, handleSubmit, control } = useForm({
35247
+ * defaultValues: {
35248
+ * firstName: "firstName"
35249
+ * }});
35250
+ * const { dirtyFields } = useFormState({
35251
+ * control
35252
+ * });
35253
+ * const onSubmit = (data) => console.log(data);
35254
+ *
35255
+ * return (
35256
+ * <form onSubmit={handleSubmit(onSubmit)}>
35257
+ * <input {...register("firstName")} placeholder="First Name" />
35258
+ * {dirtyFields.firstName && <p>Field is dirty.</p>}
35259
+ * <input type="submit" />
35260
+ * </form>
35261
+ * );
35262
+ * }
35263
+ * ```
35193
35264
  */
35194
35265
  function useFormState(props) {
35195
35266
  const methods = useFormContext();
35196
35267
  const { control = methods.control, disabled, name, exact } = props || {};
35197
35268
  const [formState, updateFormState] = React__default["default"].useState(control._formState);
35269
+ const _mounted = React__default["default"].useRef(true);
35198
35270
  const _localProxyFormState = React__default["default"].useRef({
35199
35271
  isDirty: false,
35272
+ isLoading: false,
35200
35273
  dirtyFields: false,
35201
35274
  touchedFields: false,
35275
+ validatingFields: false,
35202
35276
  isValidating: false,
35203
35277
  isValid: false,
35204
35278
  errors: false });
35205
35279
 
35206
35280
  const _name = React__default["default"].useRef(name);
35207
- const _mounted = React__default["default"].useRef(true);
35208
35281
  _name.current = name;
35209
- const callback = React__default["default"].useCallback((value) => _mounted.current &&
35210
- shouldSubscribeByName(_name.current, value.name, exact) &&
35211
- shouldRenderFormState(value, _localProxyFormState.current) &&
35212
- updateFormState({
35213
- ...control._formState,
35214
- ...value }),
35215
- [control, exact]);
35216
35282
  useSubscribe({
35217
35283
  disabled,
35218
- callback,
35284
+ next: (value) => _mounted.current &&
35285
+ shouldSubscribeByName(_name.current, value.name, exact) &&
35286
+ shouldRenderFormState(value, _localProxyFormState.current, control._updateFormState) &&
35287
+ updateFormState({
35288
+ ...control._formState,
35289
+ ...value }),
35290
+
35219
35291
  subject: control._subjects.state });
35220
35292
 
35221
35293
  React__default["default"].useEffect(() => {
35222
35294
  _mounted.current = true;
35295
+ _localProxyFormState.current.isValid && control._updateValid(true);
35223
35296
  return () => {
35224
35297
  _mounted.current = false;
35225
35298
  };
35226
- }, []);
35227
- return getProxyFormState(formState, control._proxyFormState, _localProxyFormState.current, false);
35299
+ }, [control]);
35300
+ return getProxyFormState(formState, control, _localProxyFormState.current, false);
35228
35301
  }
35229
35302
 
35230
35303
  var isString = (value) => typeof value === 'string';
35231
35304
 
35232
- var generateWatchOutput = (names, _names, formValues, isGlobal) => {
35233
- const isArray = Array.isArray(names);
35305
+ var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
35234
35306
  if (isString(names)) {
35235
35307
  isGlobal && _names.watch.add(names);
35236
- return get(formValues, names);
35308
+ return get(formValues, names, defaultValue);
35237
35309
  }
35238
- if (isArray) {
35239
- return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName),
35240
- get(formValues, fieldName)));
35310
+ if (Array.isArray(names)) {
35311
+ return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
35241
35312
  }
35242
35313
  isGlobal && (_names.watchAll = true);
35243
35314
  return formValues;
35244
35315
  };
35245
35316
 
35246
- var isFunction = (value) => typeof value === 'function';
35247
-
35248
- var objectHasFunction = (data) => {
35249
- for (const key in data) {
35250
- if (isFunction(data[key])) {
35251
- return true;
35252
- }
35253
- }
35254
- return false;
35255
- };
35256
-
35257
- /**
35258
- * Custom hook to subscribe to field change and isolate re-rendering at the component level.
35259
- *
35260
- * @remarks
35261
- *
35262
- * [API](https://react-hook-form.com/api/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
35263
- *
35264
- * @example
35265
- * ```tsx
35266
- * const { watch } = useForm();
35267
- * const values = useWatch({
35268
- * name: "fieldName"
35269
- * control,
35270
- * })
35271
- * ```
35317
+ /**
35318
+ * Custom hook to subscribe to field change and isolate re-rendering at the component level.
35319
+ *
35320
+ * @remarks
35321
+ *
35322
+ * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
35323
+ *
35324
+ * @example
35325
+ * ```tsx
35326
+ * const { control } = useForm();
35327
+ * const values = useWatch({
35328
+ * name: "fieldName"
35329
+ * control,
35330
+ * })
35331
+ * ```
35272
35332
  */
35273
35333
  function useWatch(props) {
35274
35334
  const methods = useFormContext();
35275
35335
  const { control = methods.control, name, defaultValue, disabled, exact } = props || {};
35276
35336
  const _name = React__default["default"].useRef(name);
35277
35337
  _name.current = name;
35278
- const callback = React__default["default"].useCallback((formState) => {
35279
- if (shouldSubscribeByName(_name.current, formState.name, exact)) {
35280
- const fieldValues = generateWatchOutput(_name.current, control._names, formState.values || control._formValues);
35281
- updateValue(isUndefined(_name.current) ||
35282
- isObject(fieldValues) && !objectHasFunction(fieldValues) ?
35283
- { ...fieldValues } :
35284
- Array.isArray(fieldValues) ?
35285
- [...fieldValues] :
35286
- isUndefined(fieldValues) ?
35287
- defaultValue :
35288
- fieldValues);
35289
- }
35290
- }, [control, exact, defaultValue]);
35291
35338
  useSubscribe({
35292
35339
  disabled,
35293
- subject: control._subjects.watch,
35294
- callback });
35340
+ subject: control._subjects.values,
35341
+ next: (formState) => {
35342
+ if (shouldSubscribeByName(_name.current, formState.name, exact)) {
35343
+ updateValue(cloneObject(generateWatchOutput(_name.current, control._names, formState.values || control._formValues, false, defaultValue)));
35344
+ }
35345
+ } });
35295
35346
 
35296
- const [value, updateValue] = React__default["default"].useState(isUndefined(defaultValue) ?
35297
- control._getWatch(name) :
35298
- defaultValue);
35299
- React__default["default"].useEffect(() => {
35300
- control._removeUnmounted();
35301
- });
35347
+ const [value, updateValue] = React__default["default"].useState(control._getWatch(name, defaultValue));
35348
+ React__default["default"].useEffect(() => control._removeUnmounted());
35302
35349
  return value;
35303
35350
  }
35304
35351
 
35305
- /**
35306
- * 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.
35307
- *
35308
- * @remarks
35309
- * [API](https://react-hook-form.com/api/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
35310
- *
35311
- * @param props - the path name to the form field value, and validation rules.
35312
- *
35313
- * @returns field properties, field and form state. {@link UseControllerReturn}
35314
- *
35315
- * @example
35316
- * ```tsx
35317
- * function Input(props) {
35318
- * const { field, fieldState, formState } = useController(props);
35319
- * return (
35320
- * <div>
35321
- * <input {...field} placeholder={props.name} />
35322
- * <p>{fieldState.isTouched && "Touched"}</p>
35323
- * <p>{formState.isSubmitted ? "submitted" : ""}</p>
35324
- * </div>
35325
- * );
35326
- * }
35327
- * ```
35352
+ /**
35353
+ * 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.
35354
+ *
35355
+ * @remarks
35356
+ * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
35357
+ *
35358
+ * @param props - the path name to the form field value, and validation rules.
35359
+ *
35360
+ * @returns field properties, field and form state. {@link UseControllerReturn}
35361
+ *
35362
+ * @example
35363
+ * ```tsx
35364
+ * function Input(props) {
35365
+ * const { field, fieldState, formState } = useController(props);
35366
+ * return (
35367
+ * <div>
35368
+ * <input {...field} placeholder={props.name} />
35369
+ * <p>{fieldState.isTouched && "Touched"}</p>
35370
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
35371
+ * </div>
35372
+ * );
35373
+ * }
35374
+ * ```
35328
35375
  */
35329
35376
  function useController(props) {
35330
35377
  const methods = useFormContext();
35331
- const { name, control = methods.control, shouldUnregister } = props;
35378
+ const { name, disabled, control = methods.control, shouldUnregister } = props;
35332
35379
  const isArrayField = isNameInFieldArray(control._names.array, name);
35333
35380
  const value = useWatch({
35334
35381
  control,
@@ -35342,50 +35389,67 @@ Check the top-level render call using <` + t + ">.");
35342
35389
 
35343
35390
  const _registerProps = React__default["default"].useRef(control.register(name, {
35344
35391
  ...props.rules,
35345
- value }));
35392
+ value,
35393
+ ...(isBoolean(props.disabled) ? { disabled: props.disabled } : {}) }));
35346
35394
 
35347
35395
  React__default["default"].useEffect(() => {
35396
+ const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
35348
35397
  const updateMounted = (name, value) => {
35349
35398
  const field = get(control._fields, name);
35350
- if (field) {
35399
+ if (field && field._f) {
35351
35400
  field._f.mount = value;
35352
35401
  }
35353
35402
  };
35354
35403
  updateMounted(name, true);
35404
+ if (_shouldUnregisterField) {
35405
+ const value = cloneObject(get(control._options.defaultValues, name));
35406
+ set(control._defaultValues, name, value);
35407
+ if (isUndefined(get(control._formValues, name))) {
35408
+ set(control._formValues, name, value);
35409
+ }
35410
+ }
35355
35411
  return () => {
35356
- const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
35357
35412
  (isArrayField ?
35358
- _shouldUnregisterField && !control._stateFlags.action :
35413
+ _shouldUnregisterField && !control._state.action :
35359
35414
  _shouldUnregisterField) ?
35360
35415
  control.unregister(name) :
35361
35416
  updateMounted(name, false);
35362
35417
  };
35363
35418
  }, [name, control, isArrayField, shouldUnregister]);
35419
+ React__default["default"].useEffect(() => {
35420
+ if (get(control._fields, name)) {
35421
+ control._updateDisabledField({
35422
+ disabled,
35423
+ fields: control._fields,
35424
+ name,
35425
+ value: get(control._fields, name)._f.value });
35426
+
35427
+ }
35428
+ }, [disabled, name, control]);
35364
35429
  return {
35365
35430
  field: {
35366
35431
  name,
35367
35432
  value,
35368
- onChange: React__default["default"].useCallback((event) => {
35369
- _registerProps.current.onChange({
35370
- target: {
35371
- value: getEventValue(event),
35372
- name: name },
35373
-
35374
- type: EVENTS.CHANGE });
35375
-
35376
- }, [name]),
35377
- onBlur: React__default["default"].useCallback(() => {
35378
- _registerProps.current.onBlur({
35379
- target: {
35380
- value: get(control._formValues, name),
35381
- name: name },
35382
-
35383
- type: EVENTS.BLUR });
35384
-
35385
- }, [name, control]),
35386
- ref: React__default["default"].useCallback((elm) => {
35433
+ ...(isBoolean(disabled) || formState.disabled ?
35434
+ { disabled: formState.disabled || disabled } :
35435
+ {}),
35436
+ onChange: React__default["default"].useCallback((event) => _registerProps.current.onChange({
35437
+ target: {
35438
+ value: getEventValue(event),
35439
+ name: name },
35440
+
35441
+ type: EVENTS.CHANGE }),
35442
+ [name]),
35443
+ onBlur: React__default["default"].useCallback(() => _registerProps.current.onBlur({
35444
+ target: {
35445
+ value: get(control._formValues, name),
35446
+ name: name },
35447
+
35448
+ type: EVENTS.BLUR }),
35449
+ [name, control]),
35450
+ ref: (elm) => {
35387
35451
  const field = get(control._fields, name);
35388
- if (elm && field && elm.focus) {
35452
+ if (field && elm) {
35389
35453
  field._f.ref = {
35390
35454
  focus: () => elm.focus(),
35391
35455
  select: () => elm.select(),
@@ -35393,67 +35457,75 @@ Check the top-level render call using <` + t + ">.");
35393
35457
  reportValidity: () => elm.reportValidity() };
35394
35458
 
35395
35459
  }
35396
- }, [name, control._fields]) },
35460
+ } },
35397
35461
 
35398
35462
  formState,
35399
35463
  fieldState: Object.defineProperties({}, {
35400
35464
  invalid: {
35465
+ enumerable: true,
35401
35466
  get: () => !!get(formState.errors, name) },
35402
35467
 
35403
35468
  isDirty: {
35469
+ enumerable: true,
35404
35470
  get: () => !!get(formState.dirtyFields, name) },
35405
35471
 
35406
35472
  isTouched: {
35473
+ enumerable: true,
35407
35474
  get: () => !!get(formState.touchedFields, name) },
35408
35475
 
35476
+ isValidating: {
35477
+ enumerable: true,
35478
+ get: () => !!get(formState.validatingFields, name) },
35479
+
35409
35480
  error: {
35481
+ enumerable: true,
35410
35482
  get: () => get(formState.errors, name) } }) };
35411
35483
 
35412
35484
 
35413
35485
 
35414
35486
  }
35415
35487
 
35416
- /**
35417
- * Component based on `useController` hook to work with controlled component.
35418
- *
35419
- * @remarks
35420
- * [API](https://react-hook-form.com/api/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)
35421
- *
35422
- * @param props - the path name to the form field value, and validation rules.
35423
- *
35424
- * @returns provide field handler functions, field and form state.
35425
- *
35426
- * @example
35427
- * ```tsx
35428
- * function App() {
35429
- * const { control } = useForm<FormValues>({
35430
- * defaultValues: {
35431
- * test: ""
35432
- * }
35433
- * });
35434
- *
35435
- * return (
35436
- * <form>
35437
- * <Controller
35438
- * control={control}
35439
- * name="test"
35440
- * render={({ field: { onChange, onBlur, value, ref }, formState, fieldState }) => (
35441
- * <>
35442
- * <input
35443
- * onChange={onChange} // send value to hook form
35444
- * onBlur={onBlur} // notify when input is touched
35445
- * value={value} // return updated value
35446
- * ref={ref} // set ref for focus management
35447
- * />
35448
- * <p>{formState.isSubmitted ? "submitted" : ""}</p>
35449
- * <p>{fieldState.isTouched ? "touched" : ""}</p>
35450
- * </>
35451
- * )}
35452
- * />
35453
- * </form>
35454
- * );
35455
- * }
35456
- * ```
35488
+ /**
35489
+ * Component based on `useController` hook to work with controlled component.
35490
+ *
35491
+ * @remarks
35492
+ * [API](https://react-hook-form.com/docs/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)
35493
+ *
35494
+ * @param props - the path name to the form field value, and validation rules.
35495
+ *
35496
+ * @returns provide field handler functions, field and form state.
35497
+ *
35498
+ * @example
35499
+ * ```tsx
35500
+ * function App() {
35501
+ * const { control } = useForm<FormValues>({
35502
+ * defaultValues: {
35503
+ * test: ""
35504
+ * }
35505
+ * });
35506
+ *
35507
+ * return (
35508
+ * <form>
35509
+ * <Controller
35510
+ * control={control}
35511
+ * name="test"
35512
+ * render={({ field: { onChange, onBlur, value, ref }, formState, fieldState }) => (
35513
+ * <>
35514
+ * <input
35515
+ * onChange={onChange} // send value to hook form
35516
+ * onBlur={onBlur} // notify when input is touched
35517
+ * value={value} // return updated value
35518
+ * ref={ref} // set ref for focus management
35519
+ * />
35520
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
35521
+ * <p>{fieldState.isTouched ? "touched" : ""}</p>
35522
+ * </>
35523
+ * )}
35524
+ * />
35525
+ * </form>
35526
+ * );
35527
+ * }
35528
+ * ```
35457
35529
  */
35458
35530
  const Controller = (props) => props.render(useController(props));
35459
35531
 
@@ -35467,72 +35539,64 @@ Check the top-level render call using <` + t + ">.");
35467
35539
 
35468
35540
  {};
35469
35541
 
35470
- var isKey = (value) => /^\w*$/.test(value);
35542
+ var getValidationModes = (mode) => ({
35543
+ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
35544
+ isOnBlur: mode === VALIDATION_MODE.onBlur,
35545
+ isOnChange: mode === VALIDATION_MODE.onChange,
35546
+ isOnAll: mode === VALIDATION_MODE.all,
35547
+ isOnTouch: mode === VALIDATION_MODE.onTouched });
35471
35548
 
35472
- var stringToPath = (input) => compact(input.replace(/["|']|\]/g, '').split(/\.|\[/));
35473
35549
 
35474
- function set(object, path, value) {
35475
- let index = -1;
35476
- const tempPath = isKey(path) ? [path] : stringToPath(path);
35477
- const length = tempPath.length;
35478
- const lastIndex = length - 1;
35479
- while (++index < length) {
35480
- const key = tempPath[index];
35481
- let newValue = value;
35482
- if (index !== lastIndex) {
35483
- const objValue = object[key];
35484
- newValue =
35485
- isObject(objValue) || Array.isArray(objValue) ?
35486
- objValue :
35487
- !isNaN(+tempPath[index + 1]) ?
35488
- [] :
35489
- {};
35490
- }
35491
- object[key] = newValue;
35492
- object = object[key];
35493
- }
35494
- return object;
35495
- }
35550
+ var isWatched = (name, _names, isBlurEvent) => !isBlurEvent && (
35551
+ _names.watchAll ||
35552
+ _names.watch.has(name) ||
35553
+ [..._names.watch].some((watchName) => name.startsWith(watchName) &&
35554
+ /^\.\w+/.test(name.slice(watchName.length))));
35496
35555
 
35497
- const focusFieldBy = (fields, callback, fieldsNames) => {
35556
+ const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
35498
35557
  for (const key of fieldsNames || Object.keys(fields)) {
35499
35558
  const field = get(fields, key);
35500
35559
  if (field) {
35501
35560
  const { _f, ...currentField } = field;
35502
- if (_f && callback(_f.name)) {
35503
- if (_f.ref.focus && isUndefined(_f.ref.focus())) {
35561
+ if (_f) {
35562
+ if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) {
35504
35563
  break;
35505
35564
  } else
35506
- if (_f.refs) {
35507
- _f.refs[0].focus();
35565
+ if (_f.ref && action(_f.ref, _f.name) && !abortEarly) {
35508
35566
  break;
35567
+ } else
35568
+ {
35569
+ iterateFieldsByAction(currentField, action);
35509
35570
  }
35510
35571
  } else
35511
35572
  if (isObject(currentField)) {
35512
- focusFieldBy(currentField, callback);
35573
+ iterateFieldsByAction(currentField, action);
35513
35574
  }
35514
35575
  }
35515
35576
  }
35516
35577
  };
35517
35578
 
35518
- var isWatched = (name, _names, isBlurEvent) => !isBlurEvent && (
35519
- _names.watchAll ||
35520
- _names.watch.has(name) ||
35521
- [..._names.watch].some((watchName) => name.startsWith(watchName) &&
35522
- /^\.\w+/.test(name.slice(watchName.length))));
35523
-
35524
35579
  var updateFieldArrayRootError = (errors, error, name) => {
35525
- const fieldArrayErrors = compact(get(errors, name));
35580
+ const fieldArrayErrors = convertToArrayPayload(get(errors, name));
35526
35581
  set(fieldArrayErrors, 'root', error[name]);
35527
35582
  set(errors, name, fieldArrayErrors);
35528
35583
  return errors;
35529
35584
  };
35530
35585
 
35531
- var isBoolean = (value) => typeof value === 'boolean';
35532
-
35533
35586
  var isFileInput = (element) => element.type === 'file';
35534
35587
 
35535
- var isMessage = (value) => isString(value) || /*#__PURE__*/React__default["default"].isValidElement(value);
35588
+ var isFunction = (value) => typeof value === 'function';
35589
+
35590
+ var isHTMLElement = (value) => {
35591
+ if (!isWeb) {
35592
+ return false;
35593
+ }
35594
+ const owner = value ? value.ownerDocument : 0;
35595
+ return value instanceof (
35596
+ owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement);
35597
+ };
35598
+
35599
+ var isMessage = (value) => isString(value);
35536
35600
 
35537
35601
  var isRadioInput = (element) => element.type === 'radio';
35538
35602
 
@@ -35595,15 +35659,16 @@ Check the top-level render call using <` + t + ">.");
35595
35659
  message: '' };
35596
35660
 
35597
35661
 
35598
- var validateField = async (field, inputValue, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
35662
+ var validateField = async (field, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
35599
35663
  const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount, disabled } = field._f;
35664
+ const inputValue = get(formValues, name);
35600
35665
  if (!mount || disabled) {
35601
35666
  return {};
35602
35667
  }
35603
35668
  const inputRef = refs ? refs[0] : ref;
35604
35669
  const setCustomValidity = (message) => {
35605
35670
  if (shouldUseNativeValidation && inputRef.reportValidity) {
35606
- inputRef.setCustomValidity(isBoolean(message) ? '' : message || ' ');
35671
+ inputRef.setCustomValidity(isBoolean(message) ? '' : message || '');
35607
35672
  inputRef.reportValidity();
35608
35673
  }
35609
35674
  };
@@ -35611,7 +35676,10 @@ Check the top-level render call using <` + t + ">.");
35611
35676
  const isRadio = isRadioInput(ref);
35612
35677
  const isCheckBox = isCheckBoxInput(ref);
35613
35678
  const isRadioOrCheckbox = isRadio || isCheckBox;
35614
- const isEmpty = (valueAsNumber || isFileInput(ref)) && !ref.value ||
35679
+ const isEmpty = (valueAsNumber || isFileInput(ref)) &&
35680
+ isUndefined(ref.value) &&
35681
+ isUndefined(inputValue) ||
35682
+ isHTMLElement(ref) && ref.value === '' ||
35615
35683
  inputValue === '' ||
35616
35684
  Array.isArray(inputValue) && !inputValue.length;
35617
35685
  const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
@@ -35653,7 +35721,8 @@ Check the top-level render call using <` + t + ">.");
35653
35721
  const maxOutput = getValueAndMessage(max);
35654
35722
  const minOutput = getValueAndMessage(min);
35655
35723
  if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
35656
- const valueNumber = ref.valueAsNumber || +inputValue;
35724
+ const valueNumber = ref.valueAsNumber || (
35725
+ inputValue ? +inputValue : inputValue);
35657
35726
  if (!isNullOrUndefined(maxOutput.value)) {
35658
35727
  exceedMax = valueNumber > maxOutput.value;
35659
35728
  }
@@ -35663,11 +35732,22 @@ Check the top-level render call using <` + t + ">.");
35663
35732
  } else
35664
35733
  {
35665
35734
  const valueDate = ref.valueAsDate || new Date(inputValue);
35666
- if (isString(maxOutput.value)) {
35667
- exceedMax = valueDate > new Date(maxOutput.value);
35668
- }
35669
- if (isString(minOutput.value)) {
35670
- exceedMin = valueDate < new Date(minOutput.value);
35735
+ const convertTimeToDate = (time) => new Date(new Date().toDateString() + ' ' + time);
35736
+ const isTime = ref.type == 'time';
35737
+ const isWeek = ref.type == 'week';
35738
+ if (isString(maxOutput.value) && inputValue) {
35739
+ exceedMax = isTime ?
35740
+ convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value) :
35741
+ isWeek ?
35742
+ inputValue > maxOutput.value :
35743
+ valueDate > new Date(maxOutput.value);
35744
+ }
35745
+ if (isString(minOutput.value) && inputValue) {
35746
+ exceedMin = isTime ?
35747
+ convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value) :
35748
+ isWeek ?
35749
+ inputValue < minOutput.value :
35750
+ valueDate < new Date(minOutput.value);
35671
35751
  }
35672
35752
  }
35673
35753
  if (exceedMax || exceedMin) {
@@ -35684,9 +35764,9 @@ Check the top-level render call using <` + t + ">.");
35684
35764
  const maxLengthOutput = getValueAndMessage(maxLength);
35685
35765
  const minLengthOutput = getValueAndMessage(minLength);
35686
35766
  const exceedMax = !isNullOrUndefined(maxLengthOutput.value) &&
35687
- inputValue.length > maxLengthOutput.value;
35767
+ inputValue.length > +maxLengthOutput.value;
35688
35768
  const exceedMin = !isNullOrUndefined(minLengthOutput.value) &&
35689
- inputValue.length < minLengthOutput.value;
35769
+ inputValue.length < +minLengthOutput.value;
35690
35770
  if (exceedMax || exceedMin) {
35691
35771
  getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
35692
35772
  if (!validateAllFieldCriteria) {
@@ -35712,7 +35792,7 @@ Check the top-level render call using <` + t + ">.");
35712
35792
  }
35713
35793
  if (validate) {
35714
35794
  if (isFunction(validate)) {
35715
- const result = await validate(inputValue);
35795
+ const result = await validate(inputValue, formValues);
35716
35796
  const validateError = getValidateError(result, inputRef);
35717
35797
  if (validateError) {
35718
35798
  error[name] = {
@@ -35731,7 +35811,7 @@ Check the top-level render call using <` + t + ">.");
35731
35811
  if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) {
35732
35812
  break;
35733
35813
  }
35734
- const validateError = getValidateError(await validate[key](inputValue), inputRef, key);
35814
+ const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
35735
35815
  if (validateError) {
35736
35816
  validationResult = {
35737
35817
  ...validateError,
@@ -35758,43 +35838,6 @@ Check the top-level render call using <` + t + ">.");
35758
35838
  return error;
35759
35839
  };
35760
35840
 
35761
- var isWeb = typeof window !== 'undefined' &&
35762
- typeof window.HTMLElement !== 'undefined' &&
35763
- typeof document !== 'undefined';
35764
-
35765
- function cloneObject(data) {
35766
- let copy;
35767
- const isArray = Array.isArray(data);
35768
- if (data instanceof Date) {
35769
- copy = new Date(data);
35770
- } else
35771
- if (data instanceof Set) {
35772
- copy = new Set(data);
35773
- } else
35774
- if (!(isWeb && (data instanceof Blob || data instanceof FileList)) && (
35775
- isArray || isObject(data))) {
35776
- copy = isArray ? [] : {};
35777
- for (const key in data) {
35778
- if (isFunction(data[key])) {
35779
- copy = data;
35780
- break;
35781
- }
35782
- copy[key] = cloneObject(data[key]);
35783
- }
35784
- } else
35785
- {
35786
- return data;
35787
- }
35788
- return copy;
35789
- }
35790
-
35791
- var getValidationModes = (mode) => ({
35792
- isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
35793
- isOnBlur: mode === VALIDATION_MODE.onBlur,
35794
- isOnChange: mode === VALIDATION_MODE.onChange,
35795
- isOnAll: mode === VALIDATION_MODE.all,
35796
- isOnTouch: mode === VALIDATION_MODE.onTouched });
35797
-
35798
35841
  function baseGet(object, updatePath) {
35799
35842
  const length = updatePath.slice(0, -1).length;
35800
35843
  let index = 0;
@@ -35805,47 +35848,37 @@ Check the top-level render call using <` + t + ">.");
35805
35848
  }
35806
35849
  function isEmptyArray(obj) {
35807
35850
  for (const key in obj) {
35808
- if (!isUndefined(obj[key])) {
35851
+ if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) {
35809
35852
  return false;
35810
35853
  }
35811
35854
  }
35812
35855
  return true;
35813
35856
  }
35814
35857
  function unset(object, path) {
35815
- const updatePath = isKey(path) ? [path] : stringToPath(path);
35816
- const childObject = updatePath.length == 1 ? object : baseGet(object, updatePath);
35817
- const key = updatePath[updatePath.length - 1];
35818
- let previousObjRef;
35858
+ const paths = Array.isArray(path) ?
35859
+ path :
35860
+ isKey(path) ?
35861
+ [path] :
35862
+ stringToPath(path);
35863
+ const childObject = paths.length === 1 ? object : baseGet(object, paths);
35864
+ const index = paths.length - 1;
35865
+ const key = paths[index];
35819
35866
  if (childObject) {
35820
35867
  delete childObject[key];
35821
35868
  }
35822
- for (let k = 0; k < updatePath.slice(0, -1).length; k++) {
35823
- let index = -1;
35824
- let objectRef;
35825
- const currentPaths = updatePath.slice(0, -(k + 1));
35826
- const currentPathsLength = currentPaths.length - 1;
35827
- if (k > 0) {
35828
- previousObjRef = object;
35829
- }
35830
- while (++index < currentPaths.length) {
35831
- const item = currentPaths[index];
35832
- objectRef = objectRef ? objectRef[item] : object[item];
35833
- if (currentPathsLength === index && (
35834
- isObject(objectRef) && isEmptyObject(objectRef) ||
35835
- Array.isArray(objectRef) && isEmptyArray(objectRef))) {
35836
- previousObjRef ? delete previousObjRef[item] : delete object[item];
35837
- }
35838
- previousObjRef = objectRef;
35839
- }
35869
+ if (index !== 0 && (
35870
+ isObject(childObject) && isEmptyObject(childObject) ||
35871
+ Array.isArray(childObject) && isEmptyArray(childObject))) {
35872
+ unset(object, paths.slice(0, -1));
35840
35873
  }
35841
35874
  return object;
35842
35875
  }
35843
35876
 
35844
- function createSubject() {
35877
+ var createSubject = () => {
35845
35878
  let _observers = [];
35846
35879
  const next = (value) => {
35847
35880
  for (const observer of _observers) {
35848
- observer.next(value);
35881
+ observer.next && observer.next(value);
35849
35882
  }
35850
35883
  };
35851
35884
  const subscribe = (observer) => {
@@ -35867,7 +35900,7 @@ Check the top-level render call using <` + t + ">.");
35867
35900
  subscribe,
35868
35901
  unsubscribe };
35869
35902
 
35870
- }
35903
+ };
35871
35904
 
35872
35905
  var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
35873
35906
 
@@ -35902,18 +35935,21 @@ Check the top-level render call using <` + t + ">.");
35902
35935
  return true;
35903
35936
  }
35904
35937
 
35905
- var isHTMLElement = (value) => {
35906
- const owner = value ? value.ownerDocument : 0;
35907
- const ElementClass = owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement;
35908
- return value instanceof ElementClass;
35909
- };
35910
-
35911
35938
  var isMultipleSelect = (element) => element.type === `select-multiple`;
35912
35939
 
35913
35940
  var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
35914
35941
 
35915
35942
  var live = (ref) => isHTMLElement(ref) && ref.isConnected;
35916
35943
 
35944
+ var objectHasFunction = (data) => {
35945
+ for (const key in data) {
35946
+ if (isFunction(data[key])) {
35947
+ return true;
35948
+ }
35949
+ }
35950
+ return false;
35951
+ };
35952
+
35917
35953
  function markFieldsDirty(data, fields = {}) {
35918
35954
  const isParentNodeArray = Array.isArray(data);
35919
35955
  if (isObject(data) || isParentNodeArray) {
@@ -35958,9 +35994,11 @@ Check the top-level render call using <` + t + ">.");
35958
35994
  var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value) ?
35959
35995
  value :
35960
35996
  valueAsNumber ?
35961
- value === '' || isNullOrUndefined(value) ?
35997
+ value === '' ?
35962
35998
  NaN :
35999
+ value ?
35963
36000
  +value :
36001
+ value :
35964
36002
  valueAsDate && isString(value) ?
35965
36003
  new Date(value) :
35966
36004
  setValueAs ?
@@ -36002,7 +36040,7 @@ Check the top-level render call using <` + t + ">.");
36002
36040
  };
36003
36041
 
36004
36042
  var getRuleValue = (rule) => isUndefined(rule) ?
36005
- undefined :
36043
+ rule :
36006
36044
  isRegex(rule) ?
36007
36045
  rule.source :
36008
36046
  isObject(rule) ?
@@ -36078,23 +36116,28 @@ Check the top-level render call using <` + t + ">.");
36078
36116
  ...props };
36079
36117
 
36080
36118
  let _formState = {
36119
+ submitCount: 0,
36081
36120
  isDirty: false,
36121
+ isLoading: isFunction(_options.defaultValues),
36082
36122
  isValidating: false,
36083
- dirtyFields: {},
36084
36123
  isSubmitted: false,
36085
- submitCount: 0,
36086
- touchedFields: {},
36087
36124
  isSubmitting: false,
36088
36125
  isSubmitSuccessful: false,
36089
36126
  isValid: false,
36090
- errors: {} };
36127
+ touchedFields: {},
36128
+ dirtyFields: {},
36129
+ validatingFields: {},
36130
+ errors: _options.errors || {},
36131
+ disabled: _options.disabled || false };
36091
36132
 
36092
36133
  let _fields = {};
36093
- let _defaultValues = cloneObject(_options.defaultValues) || {};
36134
+ let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values) ?
36135
+ cloneObject(_options.defaultValues || _options.values) || {} :
36136
+ {};
36094
36137
  let _formValues = _options.shouldUnregister ?
36095
36138
  {} :
36096
36139
  cloneObject(_defaultValues);
36097
- let _stateFlags = {
36140
+ let _state = {
36098
36141
  action: false,
36099
36142
  mount: false,
36100
36143
  watch: false };
@@ -36107,17 +36150,17 @@ Check the top-level render call using <` + t + ">.");
36107
36150
 
36108
36151
  let delayErrorCallback;
36109
36152
  let timer = 0;
36110
- let validateFields = {};
36111
36153
  const _proxyFormState = {
36112
36154
  isDirty: false,
36113
36155
  dirtyFields: false,
36156
+ validatingFields: false,
36114
36157
  touchedFields: false,
36115
36158
  isValidating: false,
36116
36159
  isValid: false,
36117
36160
  errors: false };
36118
36161
 
36119
36162
  const _subjects = {
36120
- watch: createSubject(),
36163
+ values: createSubject(),
36121
36164
  array: createSubject(),
36122
36165
  state: createSubject() };
36123
36166
 
@@ -36126,32 +36169,43 @@ Check the top-level render call using <` + t + ">.");
36126
36169
  const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
36127
36170
  const debounce = (callback) => (wait) => {
36128
36171
  clearTimeout(timer);
36129
- timer = window.setTimeout(callback, wait);
36172
+ timer = setTimeout(callback, wait);
36130
36173
  };
36131
- const _updateValid = async (shouldSkipRender) => {
36132
- let isValid = false;
36133
- if (_proxyFormState.isValid) {
36134
- isValid = _options.resolver ?
36174
+ const _updateValid = async (shouldUpdateValid) => {
36175
+ if (_proxyFormState.isValid || shouldUpdateValid) {
36176
+ const isValid = _options.resolver ?
36135
36177
  isEmptyObject((await _executeSchema()).errors) :
36136
36178
  await executeBuiltInValidation(_fields, true);
36137
- if (!shouldSkipRender && isValid !== _formState.isValid) {
36138
- _formState.isValid = isValid;
36179
+ if (isValid !== _formState.isValid) {
36139
36180
  _subjects.state.next({
36140
36181
  isValid });
36141
36182
 
36142
36183
  }
36143
36184
  }
36144
- return isValid;
36185
+ };
36186
+ const _updateIsValidating = (names, isValidating) => {
36187
+ if (_proxyFormState.isValidating || _proxyFormState.validatingFields) {
36188
+ (names || Array.from(_names.mount)).forEach((name) => {
36189
+ if (name) {
36190
+ isValidating ?
36191
+ set(_formState.validatingFields, name, isValidating) :
36192
+ unset(_formState.validatingFields, name);
36193
+ }
36194
+ });
36195
+ _subjects.state.next({
36196
+ validatingFields: _formState.validatingFields,
36197
+ isValidating: !isEmptyObject(_formState.validatingFields) });
36198
+
36199
+ }
36145
36200
  };
36146
36201
  const _updateFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
36147
36202
  if (args && method) {
36148
- _stateFlags.action = true;
36203
+ _state.action = true;
36149
36204
  if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
36150
36205
  const fieldValues = method(get(_fields, name), args.argA, args.argB);
36151
36206
  shouldSetValues && set(_fields, name, fieldValues);
36152
36207
  }
36153
- if (_proxyFormState.errors &&
36154
- shouldUpdateFieldsAndState &&
36208
+ if (shouldUpdateFieldsAndState &&
36155
36209
  Array.isArray(get(_formState.errors, name))) {
36156
36210
  const errors = method(get(_formState.errors, name), args.argA, args.argB);
36157
36211
  shouldSetValues && set(_formState.errors, name, errors);
@@ -36167,6 +36221,7 @@ Check the top-level render call using <` + t + ">.");
36167
36221
  _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
36168
36222
  }
36169
36223
  _subjects.state.next({
36224
+ name,
36170
36225
  isDirty: _getDirty(name, values),
36171
36226
  dirtyFields: _formState.dirtyFields,
36172
36227
  errors: _formState.errors,
@@ -36182,6 +36237,13 @@ Check the top-level render call using <` + t + ">.");
36182
36237
  _subjects.state.next({
36183
36238
  errors: _formState.errors });
36184
36239
 
36240
+ };
36241
+ const _setErrors = (errors) => {
36242
+ _formState.errors = errors;
36243
+ _subjects.state.next({
36244
+ errors: _formState.errors,
36245
+ isValid: false });
36246
+
36185
36247
  };
36186
36248
  const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
36187
36249
  const field = get(_fields, name);
@@ -36192,45 +36254,54 @@ Check the top-level render call using <` + t + ">.");
36192
36254
  shouldSkipSetValueAs ?
36193
36255
  set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f)) :
36194
36256
  setFieldValue(name, defaultValue);
36195
- _stateFlags.mount && _updateValid();
36257
+ _state.mount && _updateValid();
36196
36258
  }
36197
36259
  };
36198
36260
  const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
36199
- let isFieldDirty = false;
36261
+ let shouldUpdateField = false;
36262
+ let isPreviousDirty = false;
36200
36263
  const output = {
36201
36264
  name };
36202
36265
 
36203
- const isPreviousFieldTouched = get(_formState.touchedFields, name);
36204
- if (_proxyFormState.isDirty) {
36205
- const isPreviousFormDirty = _formState.isDirty;
36206
- _formState.isDirty = output.isDirty = _getDirty();
36207
- isFieldDirty = isPreviousFormDirty !== output.isDirty;
36208
- }
36209
- if (_proxyFormState.dirtyFields && (!isBlurEvent || shouldDirty)) {
36210
- const isPreviousFieldDirty = get(_formState.dirtyFields, name);
36211
- const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
36212
- isCurrentFieldPristine ?
36266
+ const disabledField = !!(get(_fields, name) &&
36267
+ get(_fields, name)._f &&
36268
+ get(_fields, name)._f.disabled);
36269
+ if (!isBlurEvent || shouldDirty) {
36270
+ if (_proxyFormState.isDirty) {
36271
+ isPreviousDirty = _formState.isDirty;
36272
+ _formState.isDirty = output.isDirty = _getDirty();
36273
+ shouldUpdateField = isPreviousDirty !== output.isDirty;
36274
+ }
36275
+ const isCurrentFieldPristine = disabledField || deepEqual(get(_defaultValues, name), fieldValue);
36276
+ isPreviousDirty = !!(!disabledField && get(_formState.dirtyFields, name));
36277
+ isCurrentFieldPristine || disabledField ?
36213
36278
  unset(_formState.dirtyFields, name) :
36214
36279
  set(_formState.dirtyFields, name, true);
36215
36280
  output.dirtyFields = _formState.dirtyFields;
36216
- isFieldDirty =
36217
- isFieldDirty ||
36218
- isPreviousFieldDirty !== get(_formState.dirtyFields, name);
36219
- }
36220
- if (isBlurEvent && !isPreviousFieldTouched) {
36221
- set(_formState.touchedFields, name, isBlurEvent);
36222
- output.touchedFields = _formState.touchedFields;
36223
- isFieldDirty =
36224
- isFieldDirty ||
36225
- _proxyFormState.touchedFields &&
36226
- isPreviousFieldTouched !== isBlurEvent;
36227
- }
36228
- isFieldDirty && shouldRender && _subjects.state.next(output);
36229
- return isFieldDirty ? output : {};
36281
+ shouldUpdateField =
36282
+ shouldUpdateField ||
36283
+ _proxyFormState.dirtyFields &&
36284
+ isPreviousDirty !== !isCurrentFieldPristine;
36285
+ }
36286
+ if (isBlurEvent) {
36287
+ const isPreviousFieldTouched = get(_formState.touchedFields, name);
36288
+ if (!isPreviousFieldTouched) {
36289
+ set(_formState.touchedFields, name, isBlurEvent);
36290
+ output.touchedFields = _formState.touchedFields;
36291
+ shouldUpdateField =
36292
+ shouldUpdateField ||
36293
+ _proxyFormState.touchedFields &&
36294
+ isPreviousFieldTouched !== isBlurEvent;
36295
+ }
36296
+ }
36297
+ shouldUpdateField && shouldRender && _subjects.state.next(output);
36298
+ return shouldUpdateField ? output : {};
36230
36299
  };
36231
- const shouldRenderByError = async (name, isValid, error, fieldState) => {
36300
+ const shouldRenderByError = (name, isValid, error, fieldState) => {
36232
36301
  const previousFieldError = get(_formState.errors, name);
36233
- const shouldUpdateValid = _proxyFormState.isValid && _formState.isValid !== isValid;
36302
+ const shouldUpdateValid = _proxyFormState.isValid &&
36303
+ isBoolean(isValid) &&
36304
+ _formState.isValid !== isValid;
36234
36305
  if (props.delayError && error) {
36235
36306
  delayErrorCallback = debounce(() => updateErrors(name, error));
36236
36307
  delayErrorCallback(props.delayError);
@@ -36247,7 +36318,7 @@ Check the top-level render call using <` + t + ">.");
36247
36318
  shouldUpdateValid) {
36248
36319
  const updatedFormState = {
36249
36320
  ...fieldState,
36250
- ...(shouldUpdateValid ? { isValid } : {}),
36321
+ ...(shouldUpdateValid && isBoolean(isValid) ? { isValid } : {}),
36251
36322
  errors: _formState.errors,
36252
36323
  name };
36253
36324
 
@@ -36257,20 +36328,15 @@ Check the top-level render call using <` + t + ">.");
36257
36328
 
36258
36329
  _subjects.state.next(updatedFormState);
36259
36330
  }
36260
- validateFields[name]--;
36261
- if (_proxyFormState.isValidating &&
36262
- !Object.values(validateFields).some((v) => v)) {
36263
- _subjects.state.next({
36264
- isValidating: false });
36265
-
36266
- validateFields = {};
36267
- }
36268
36331
  };
36269
- const _executeSchema = async (name) => _options.resolver ?
36270
- await _options.resolver({ ..._formValues }, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation)) :
36271
- {};
36332
+ const _executeSchema = async (name) => {
36333
+ _updateIsValidating(name, true);
36334
+ const result = await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
36335
+ _updateIsValidating(name);
36336
+ return result;
36337
+ };
36272
36338
  const executeSchemaAndUpdateState = async (names) => {
36273
- const { errors } = await _executeSchema();
36339
+ const { errors } = await _executeSchema(names);
36274
36340
  if (names) {
36275
36341
  for (const name of names) {
36276
36342
  const error = get(errors, name);
@@ -36293,7 +36359,9 @@ Check the top-level render call using <` + t + ">.");
36293
36359
  const { _f, ...fieldValue } = field;
36294
36360
  if (_f) {
36295
36361
  const isFieldArrayRoot = _names.array.has(_f.name);
36296
- const fieldError = await validateField(field, get(_formValues, _f.name), shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation, isFieldArrayRoot);
36362
+ _updateIsValidating([name], true);
36363
+ const fieldError = await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
36364
+ _updateIsValidating([name]);
36297
36365
  if (fieldError[_f.name]) {
36298
36366
  context.valid = false;
36299
36367
  if (shouldOnlyCheckValid) {
@@ -36326,19 +36394,16 @@ Check the top-level render call using <` + t + ">.");
36326
36394
  };
36327
36395
  const _getDirty = (name, data) => (name && data && set(_formValues, name, data),
36328
36396
  !deepEqual(getValues(), _defaultValues));
36329
- const _getWatch = (names, defaultValue, isGlobal) => {
36330
- const fieldValues = {
36331
- ...(_stateFlags.mount ?
36332
- _formValues :
36333
- isUndefined(defaultValue) ?
36334
- _defaultValues :
36335
- isString(names) ?
36336
- { [names]: defaultValue } :
36337
- defaultValue) };
36338
-
36339
- return generateWatchOutput(names, _names, fieldValues, isGlobal);
36340
- };
36341
- const _getFieldArray = (name) => compact(get(_stateFlags.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
36397
+ const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, {
36398
+ ...(_state.mount ?
36399
+ _formValues :
36400
+ isUndefined(defaultValue) ?
36401
+ _defaultValues :
36402
+ isString(names) ?
36403
+ { [names]: defaultValue } :
36404
+ defaultValue) },
36405
+ isGlobal, defaultValue);
36406
+ const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, props.shouldUnregister ? get(_defaultValues, name, []) : []));
36342
36407
  const setFieldValue = (name, value, options = {}) => {
36343
36408
  const field = get(_fields, name);
36344
36409
  let fieldValue = value;
@@ -36348,16 +36413,16 @@ Check the top-level render call using <` + t + ">.");
36348
36413
  !fieldReference.disabled &&
36349
36414
  set(_formValues, name, getFieldValueAs(value, fieldReference));
36350
36415
  fieldValue =
36351
- isWeb && isHTMLElement(fieldReference.ref) && isNullOrUndefined(value) ?
36416
+ isHTMLElement(fieldReference.ref) && isNullOrUndefined(value) ?
36352
36417
  '' :
36353
36418
  value;
36354
36419
  if (isMultipleSelect(fieldReference.ref)) {
36355
- [...fieldReference.ref.options].forEach((selectRef) => selectRef.selected = fieldValue.includes(selectRef.value));
36420
+ [...fieldReference.ref.options].forEach((optionRef) => optionRef.selected = fieldValue.includes(optionRef.value));
36356
36421
  } else
36357
36422
  if (fieldReference.refs) {
36358
36423
  if (isCheckBoxInput(fieldReference.ref)) {
36359
36424
  fieldReference.refs.length > 1 ?
36360
- fieldReference.refs.forEach((checkboxRef) => !checkboxRef.disabled && (
36425
+ fieldReference.refs.forEach((checkboxRef) => (!checkboxRef.defaultChecked || !checkboxRef.disabled) && (
36361
36426
  checkboxRef.checked = Array.isArray(fieldValue) ?
36362
36427
  !!fieldValue.find((data) => data === checkboxRef.value) :
36363
36428
  fieldValue === checkboxRef.value)) :
@@ -36374,8 +36439,9 @@ Check the top-level render call using <` + t + ">.");
36374
36439
  {
36375
36440
  fieldReference.ref.value = fieldValue;
36376
36441
  if (!fieldReference.ref.type) {
36377
- _subjects.watch.next({
36378
- name });
36442
+ _subjects.values.next({
36443
+ name,
36444
+ values: { ..._formValues } });
36379
36445
 
36380
36446
  }
36381
36447
  }
@@ -36406,14 +36472,13 @@ Check the top-level render call using <` + t + ">.");
36406
36472
  if (isFieldArray) {
36407
36473
  _subjects.array.next({
36408
36474
  name,
36409
- values: _formValues });
36475
+ values: { ..._formValues } });
36410
36476
 
36411
36477
  if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields) &&
36412
36478
  options.shouldDirty) {
36413
- _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
36414
36479
  _subjects.state.next({
36415
36480
  name,
36416
- dirtyFields: _formState.dirtyFields,
36481
+ dirtyFields: getDirtyFields(_defaultValues, _formValues),
36417
36482
  isDirty: _getDirty(name, cloneValue) });
36418
36483
 
36419
36484
  }
@@ -36423,21 +36488,28 @@ Check the top-level render call using <` + t + ">.");
36423
36488
  setValues(name, cloneValue, options) :
36424
36489
  setFieldValue(name, cloneValue, options);
36425
36490
  }
36426
- isWatched(name, _names) && _subjects.state.next({});
36427
- _subjects.watch.next({
36428
- name });
36491
+ isWatched(name, _names) && _subjects.state.next({ ..._formState });
36492
+ _subjects.values.next({
36493
+ name: _state.mount ? name : undefined,
36494
+ values: { ..._formValues } });
36429
36495
 
36430
36496
  };
36431
36497
  const onChange = async (event) => {
36498
+ _state.mount = true;
36432
36499
  const target = event.target;
36433
36500
  let name = target.name;
36501
+ let isFieldValueUpdated = true;
36434
36502
  const field = get(_fields, name);
36503
+ const getCurrentFieldValue = () => target.type ? getFieldValue(field._f) : getEventValue(event);
36504
+ const _updateIsFieldValueUpdated = (fieldValue) => {
36505
+ isFieldValueUpdated =
36506
+ Number.isNaN(fieldValue) ||
36507
+ fieldValue === get(_formValues, name, fieldValue);
36508
+ };
36435
36509
  if (field) {
36436
36510
  let error;
36437
36511
  let isValid;
36438
- const fieldValue = target.type ?
36439
- getFieldValue(field._f) :
36440
- getEventValue(event);
36512
+ const fieldValue = getCurrentFieldValue();
36441
36513
  const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
36442
36514
  const shouldSkipValidation = !hasValidation(field._f) &&
36443
36515
  !_options.resolver &&
@@ -36456,43 +36528,60 @@ Check the top-level render call using <` + t + ">.");
36456
36528
  const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent, false);
36457
36529
  const shouldRender = !isEmptyObject(fieldState) || watched;
36458
36530
  !isBlurEvent &&
36459
- _subjects.watch.next({
36531
+ _subjects.values.next({
36460
36532
  name,
36461
- type: event.type });
36533
+ type: event.type,
36534
+ values: { ..._formValues } });
36462
36535
 
36463
36536
  if (shouldSkipValidation) {
36537
+ _proxyFormState.isValid && _updateValid();
36464
36538
  return shouldRender &&
36465
36539
  _subjects.state.next({ name, ...(watched ? {} : fieldState) });
36466
36540
  }
36467
- !isBlurEvent && watched && _subjects.state.next({});
36468
- validateFields[name] = validateFields[name] ? +1 : 1;
36469
- _subjects.state.next({
36470
- isValidating: true });
36471
-
36541
+ !isBlurEvent && watched && _subjects.state.next({ ..._formState });
36472
36542
  if (_options.resolver) {
36473
36543
  const { errors } = await _executeSchema([name]);
36474
- const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
36475
- const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
36476
- error = errorLookupResult.error;
36477
- name = errorLookupResult.name;
36478
- isValid = isEmptyObject(errors);
36544
+ _updateIsFieldValueUpdated(fieldValue);
36545
+ if (isFieldValueUpdated) {
36546
+ const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
36547
+ const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
36548
+ error = errorLookupResult.error;
36549
+ name = errorLookupResult.name;
36550
+ isValid = isEmptyObject(errors);
36551
+ }
36479
36552
  } else
36480
36553
  {
36481
- error = (await validateField(field, get(_formValues, name), shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
36482
- isValid = await _updateValid(true);
36554
+ _updateIsValidating([name], true);
36555
+ error = (await validateField(field, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
36556
+ _updateIsValidating([name]);
36557
+ _updateIsFieldValueUpdated(fieldValue);
36558
+ if (isFieldValueUpdated) {
36559
+ if (error) {
36560
+ isValid = false;
36561
+ } else
36562
+ if (_proxyFormState.isValid) {
36563
+ isValid = await executeBuiltInValidation(_fields, true);
36564
+ }
36565
+ }
36483
36566
  }
36484
- field._f.deps &&
36485
- trigger(field._f.deps);
36486
- shouldRenderByError(name, isValid, error, fieldState);
36567
+ if (isFieldValueUpdated) {
36568
+ field._f.deps &&
36569
+ trigger(field._f.deps);
36570
+ shouldRenderByError(name, isValid, error, fieldState);
36571
+ }
36572
+ }
36573
+ };
36574
+ const _focusInput = (ref, key) => {
36575
+ if (get(_formState.errors, key) && ref.focus) {
36576
+ ref.focus();
36577
+ return 1;
36487
36578
  }
36579
+ return;
36488
36580
  };
36489
36581
  const trigger = async (name, options = {}) => {
36490
36582
  let isValid;
36491
36583
  let validationResult;
36492
36584
  const fieldNames = convertToArrayPayload(name);
36493
- _subjects.state.next({
36494
- isValidating: true });
36495
-
36496
36585
  if (_options.resolver) {
36497
36586
  const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
36498
36587
  isValid = isEmptyObject(errors);
@@ -36515,19 +36604,17 @@ Check the top-level render call using <` + t + ">.");
36515
36604
  _proxyFormState.isValid && isValid !== _formState.isValid ?
36516
36605
  {} :
36517
36606
  { name }),
36518
- ...(_options.resolver ? { isValid } : {}),
36519
- errors: _formState.errors,
36520
- isValidating: false });
36607
+ ...(_options.resolver || !name ? { isValid } : {}),
36608
+ errors: _formState.errors });
36521
36609
 
36522
36610
  options.shouldFocus &&
36523
36611
  !validationResult &&
36524
- focusFieldBy(_fields, (key) => get(_formState.errors, key), name ? fieldNames : _names.mount);
36612
+ iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
36525
36613
  return validationResult;
36526
36614
  };
36527
36615
  const getValues = (fieldNames) => {
36528
36616
  const values = {
36529
- ..._defaultValues,
36530
- ...(_stateFlags.mount ? _formValues : {}) };
36617
+ ...(_state.mount ? _formValues : _defaultValues) };
36531
36618
 
36532
36619
  return isUndefined(fieldNames) ?
36533
36620
  values :
@@ -36538,20 +36625,24 @@ Check the top-level render call using <` + t + ">.");
36538
36625
  const getFieldState = (name, formState) => ({
36539
36626
  invalid: !!get((formState || _formState).errors, name),
36540
36627
  isDirty: !!get((formState || _formState).dirtyFields, name),
36541
- isTouched: !!get((formState || _formState).touchedFields, name),
36542
- error: get((formState || _formState).errors, name) });
36628
+ error: get((formState || _formState).errors, name),
36629
+ isValidating: !!get(_formState.validatingFields, name),
36630
+ isTouched: !!get((formState || _formState).touchedFields, name) });
36543
36631
 
36544
36632
  const clearErrors = (name) => {
36545
- name ?
36546
- convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName)) :
36547
- _formState.errors = {};
36633
+ name &&
36634
+ convertToArrayPayload(name).forEach((inputName) => unset(_formState.errors, inputName));
36548
36635
  _subjects.state.next({
36549
- errors: _formState.errors });
36636
+ errors: name ? _formState.errors : {} });
36550
36637
 
36551
36638
  };
36552
36639
  const setError = (name, error, options) => {
36553
36640
  const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
36641
+ const currentError = get(_formState.errors, name) || {};
36642
+ // Don't override existing error messages elsewhere in the object tree.
36643
+ const { ref: currentRef, message, type, ...restOfErrorTree } = currentError;
36554
36644
  set(_formState.errors, name, {
36645
+ ...restOfErrorTree,
36555
36646
  ...error,
36556
36647
  ref });
36557
36648
 
@@ -36563,38 +36654,52 @@ Check the top-level render call using <` + t + ">.");
36563
36654
  options && options.shouldFocus && ref && ref.focus && ref.focus();
36564
36655
  };
36565
36656
  const watch = (name, defaultValue) => isFunction(name) ?
36566
- _subjects.watch.subscribe({
36567
- next: (info) => name(_getWatch(undefined, defaultValue), info) }) :
36657
+ _subjects.values.subscribe({
36658
+ next: (payload) => name(_getWatch(undefined, defaultValue), payload) }) :
36568
36659
 
36569
36660
  _getWatch(name, defaultValue, true);
36570
36661
  const unregister = (name, options = {}) => {
36571
36662
  for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
36572
36663
  _names.mount.delete(fieldName);
36573
36664
  _names.array.delete(fieldName);
36574
- if (get(_fields, fieldName)) {
36575
- if (!options.keepValue) {
36576
- unset(_fields, fieldName);
36577
- unset(_formValues, fieldName);
36578
- }
36579
- !options.keepError && unset(_formState.errors, fieldName);
36580
- !options.keepDirty && unset(_formState.dirtyFields, fieldName);
36581
- !options.keepTouched && unset(_formState.touchedFields, fieldName);
36582
- !_options.shouldUnregister &&
36583
- !options.keepDefaultValue &&
36584
- unset(_defaultValues, fieldName);
36585
- }
36586
- }
36587
- _subjects.watch.next({});
36665
+ if (!options.keepValue) {
36666
+ unset(_fields, fieldName);
36667
+ unset(_formValues, fieldName);
36668
+ }
36669
+ !options.keepError && unset(_formState.errors, fieldName);
36670
+ !options.keepDirty && unset(_formState.dirtyFields, fieldName);
36671
+ !options.keepTouched && unset(_formState.touchedFields, fieldName);
36672
+ !options.keepIsValidating &&
36673
+ unset(_formState.validatingFields, fieldName);
36674
+ !_options.shouldUnregister &&
36675
+ !options.keepDefaultValue &&
36676
+ unset(_defaultValues, fieldName);
36677
+ }
36678
+ _subjects.values.next({
36679
+ values: { ..._formValues } });
36680
+
36588
36681
  _subjects.state.next({
36589
36682
  ..._formState,
36590
36683
  ...(!options.keepDirty ? {} : { isDirty: _getDirty() }) });
36591
36684
 
36592
36685
  !options.keepIsValid && _updateValid();
36593
36686
  };
36687
+ const _updateDisabledField = ({ disabled, name, field, fields, value }) => {
36688
+ if (isBoolean(disabled) && _state.mount || !!disabled) {
36689
+ const inputValue = disabled ?
36690
+ undefined :
36691
+ isUndefined(value) ?
36692
+ getFieldValue(field ? field._f : get(fields, name)._f) :
36693
+ value;
36694
+ set(_formValues, name, inputValue);
36695
+ updateTouchAndDirty(name, inputValue, false, false, true);
36696
+ }
36697
+ };
36594
36698
  const register = (name, options = {}) => {
36595
36699
  let field = get(_fields, name);
36596
36700
  const disabledIsDefined = isBoolean(options.disabled);
36597
36701
  set(_fields, name, {
36702
+ ...(field || {}),
36598
36703
  _f: {
36599
36704
  ...(field && field._f ? field._f : { ref: { name } }),
36600
36705
  name,
@@ -36603,15 +36708,20 @@ Check the top-level render call using <` + t + ">.");
36603
36708
 
36604
36709
 
36605
36710
  _names.mount.add(name);
36606
- field ?
36607
- disabledIsDefined &&
36608
- set(_formValues, name, options.disabled ?
36609
- undefined :
36610
- get(_formValues, name, getFieldValue(field._f))) :
36611
- updateValidAndValue(name, true, options.value);
36711
+ if (field) {
36712
+ _updateDisabledField({
36713
+ field,
36714
+ disabled: options.disabled,
36715
+ name,
36716
+ value: options.value });
36717
+
36718
+ } else
36719
+ {
36720
+ updateValidAndValue(name, true, options.value);
36721
+ }
36612
36722
  return {
36613
36723
  ...(disabledIsDefined ? { disabled: options.disabled } : {}),
36614
- ...(_options.shouldUseNativeValidation ?
36724
+ ...(_options.progressive ?
36615
36725
  {
36616
36726
  required: !!options.required,
36617
36727
  min: getRuleValue(options.min),
@@ -36648,9 +36758,7 @@ Check the top-level render call using <` + t + ">.");
36648
36758
  refs: [
36649
36759
  ...refs.filter(live),
36650
36760
  fieldRef,
36651
- ...(!!Array.isArray(get(_defaultValues, name)) ?
36652
- [{}] :
36653
- [])],
36761
+ ...(Array.isArray(get(_defaultValues, name)) ? [{}] : [])],
36654
36762
 
36655
36763
  ref: { type: fieldRef.type, name } } :
36656
36764
 
@@ -36665,69 +36773,86 @@ Check the top-level render call using <` + t + ">.");
36665
36773
  field._f.mount = false;
36666
36774
  }
36667
36775
  (_options.shouldUnregister || options.shouldUnregister) &&
36668
- !(isNameInFieldArray(_names.array, name) && _stateFlags.action) &&
36776
+ !(isNameInFieldArray(_names.array, name) && _state.action) &&
36669
36777
  _names.unMount.add(name);
36670
36778
  }
36671
36779
  } };
36672
36780
 
36673
36781
  };
36782
+ const _focusError = () => _options.shouldFocusError &&
36783
+ iterateFieldsByAction(_fields, _focusInput, _names.mount);
36784
+ const _disableForm = (disabled) => {
36785
+ if (isBoolean(disabled)) {
36786
+ _subjects.state.next({ disabled });
36787
+ iterateFieldsByAction(_fields, (ref, name) => {
36788
+ const currentField = get(_fields, name);
36789
+ if (currentField) {
36790
+ ref.disabled = currentField._f.disabled || disabled;
36791
+ if (Array.isArray(currentField._f.refs)) {
36792
+ currentField._f.refs.forEach((inputRef) => {
36793
+ inputRef.disabled = currentField._f.disabled || disabled;
36794
+ });
36795
+ }
36796
+ }
36797
+ }, 0, false);
36798
+ }
36799
+ };
36674
36800
  const handleSubmit = (onValid, onInvalid) => async (e) => {
36801
+ let onValidError = undefined;
36675
36802
  if (e) {
36676
36803
  e.preventDefault && e.preventDefault();
36677
36804
  e.persist && e.persist();
36678
36805
  }
36679
- let hasNoPromiseError = true;
36680
36806
  let fieldValues = cloneObject(_formValues);
36681
36807
  _subjects.state.next({
36682
36808
  isSubmitting: true });
36683
36809
 
36684
- try {
36685
- if (_options.resolver) {
36686
- const { errors, values } = await _executeSchema();
36687
- _formState.errors = errors;
36688
- fieldValues = values;
36689
- } else
36690
- {
36691
- await executeBuiltInValidation(_fields);
36692
- }
36693
- if (isEmptyObject(_formState.errors)) {
36694
- _subjects.state.next({
36695
- errors: {},
36696
- isSubmitting: true });
36810
+ if (_options.resolver) {
36811
+ const { errors, values } = await _executeSchema();
36812
+ _formState.errors = errors;
36813
+ fieldValues = values;
36814
+ } else
36815
+ {
36816
+ await executeBuiltInValidation(_fields);
36817
+ }
36818
+ unset(_formState.errors, 'root');
36819
+ if (isEmptyObject(_formState.errors)) {
36820
+ _subjects.state.next({
36821
+ errors: {} });
36697
36822
 
36823
+ try {
36698
36824
  await onValid(fieldValues, e);
36699
- } else
36700
- {
36701
- if (onInvalid) {
36702
- await onInvalid({ ..._formState.errors }, e);
36703
- }
36704
- _options.shouldFocusError &&
36705
- focusFieldBy(_fields, (key) => get(_formState.errors, key), _names.mount);
36706
36825
  }
36707
- }
36708
- catch (err) {
36709
- hasNoPromiseError = false;
36710
- throw err;
36711
- } finally
36826
+ catch (error) {
36827
+ onValidError = error;
36828
+ }
36829
+ } else
36712
36830
  {
36713
- _formState.isSubmitted = true;
36714
- _subjects.state.next({
36715
- isSubmitted: true,
36716
- isSubmitting: false,
36717
- isSubmitSuccessful: isEmptyObject(_formState.errors) && hasNoPromiseError,
36718
- submitCount: _formState.submitCount + 1,
36719
- errors: _formState.errors });
36831
+ if (onInvalid) {
36832
+ await onInvalid({ ..._formState.errors }, e);
36833
+ }
36834
+ _focusError();
36835
+ setTimeout(_focusError);
36836
+ }
36837
+ _subjects.state.next({
36838
+ isSubmitted: true,
36839
+ isSubmitting: false,
36840
+ isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,
36841
+ submitCount: _formState.submitCount + 1,
36842
+ errors: _formState.errors });
36720
36843
 
36844
+ if (onValidError) {
36845
+ throw onValidError;
36721
36846
  }
36722
36847
  };
36723
36848
  const resetField = (name, options = {}) => {
36724
36849
  if (get(_fields, name)) {
36725
36850
  if (isUndefined(options.defaultValue)) {
36726
- setValue(name, get(_defaultValues, name));
36851
+ setValue(name, cloneObject(get(_defaultValues, name)));
36727
36852
  } else
36728
36853
  {
36729
36854
  setValue(name, options.defaultValue);
36730
- set(_defaultValues, name, options.defaultValue);
36855
+ set(_defaultValues, name, cloneObject(options.defaultValue));
36731
36856
  }
36732
36857
  if (!options.keepTouched) {
36733
36858
  unset(_formState.touchedFields, name);
@@ -36735,7 +36860,7 @@ Check the top-level render call using <` + t + ">.");
36735
36860
  if (!options.keepDirty) {
36736
36861
  unset(_formState.dirtyFields, name);
36737
36862
  _formState.isDirty = options.defaultValue ?
36738
- _getDirty(name, get(_defaultValues, name)) :
36863
+ _getDirty(name, cloneObject(get(_defaultValues, name))) :
36739
36864
  _getDirty();
36740
36865
  }
36741
36866
  if (!options.keepError) {
@@ -36745,12 +36870,11 @@ Check the top-level render call using <` + t + ">.");
36745
36870
  _subjects.state.next({ ..._formState });
36746
36871
  }
36747
36872
  };
36748
- const reset = (formValues, keepStateOptions = {}) => {
36749
- const updatedValues = formValues || _defaultValues;
36873
+ const _reset = (formValues, keepStateOptions = {}) => {
36874
+ const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
36750
36875
  const cloneUpdatedValues = cloneObject(updatedValues);
36751
- const values = formValues && !isEmptyObject(formValues) ?
36752
- cloneUpdatedValues :
36753
- _defaultValues;
36876
+ const isEmptyResetValues = isEmptyObject(formValues);
36877
+ const values = isEmptyResetValues ? _defaultValues : cloneUpdatedValues;
36754
36878
  if (!keepStateOptions.keepDefaultValues) {
36755
36879
  _defaultValues = updatedValues;
36756
36880
  }
@@ -36770,13 +36894,13 @@ Check the top-level render call using <` + t + ">.");
36770
36894
  const fieldReference = Array.isArray(field._f.refs) ?
36771
36895
  field._f.refs[0] :
36772
36896
  field._f.ref;
36773
- try {
36774
- if (isHTMLElement(fieldReference)) {
36775
- fieldReference.closest('form').reset();
36897
+ if (isHTMLElement(fieldReference)) {
36898
+ const form = fieldReference.closest('form');
36899
+ if (form) {
36900
+ form.reset();
36776
36901
  break;
36777
36902
  }
36778
36903
  }
36779
- catch (_a) {}
36780
36904
  }
36781
36905
  }
36782
36906
  }
@@ -36786,82 +36910,123 @@ Check the top-level render call using <` + t + ">.");
36786
36910
  keepStateOptions.keepDefaultValues ?
36787
36911
  cloneObject(_defaultValues) :
36788
36912
  {} :
36789
- cloneUpdatedValues;
36913
+ cloneObject(values);
36790
36914
  _subjects.array.next({
36791
- values });
36915
+ values: { ...values } });
36792
36916
 
36793
- _subjects.watch.next({
36794
- values });
36917
+ _subjects.values.next({
36918
+ values: { ...values } });
36795
36919
 
36796
36920
  }
36797
36921
  _names = {
36798
- mount: new Set(),
36922
+ mount: keepStateOptions.keepDirtyValues ? _names.mount : new Set(),
36799
36923
  unMount: new Set(),
36800
36924
  array: new Set(),
36801
36925
  watch: new Set(),
36802
36926
  watchAll: false,
36803
36927
  focus: '' };
36804
36928
 
36805
- _stateFlags.mount =
36806
- !_proxyFormState.isValid || !!keepStateOptions.keepIsValid;
36807
- _stateFlags.watch = !!props.shouldUnregister;
36929
+ _state.mount =
36930
+ !_proxyFormState.isValid ||
36931
+ !!keepStateOptions.keepIsValid ||
36932
+ !!keepStateOptions.keepDirtyValues;
36933
+ _state.watch = !!props.shouldUnregister;
36808
36934
  _subjects.state.next({
36809
36935
  submitCount: keepStateOptions.keepSubmitCount ?
36810
36936
  _formState.submitCount :
36811
36937
  0,
36812
- isDirty: keepStateOptions.keepDirty || keepStateOptions.keepDirtyValues ?
36938
+ isDirty: isEmptyResetValues ?
36939
+ false :
36940
+ keepStateOptions.keepDirty ?
36813
36941
  _formState.isDirty :
36814
36942
  !!(keepStateOptions.keepDefaultValues &&
36815
36943
  !deepEqual(formValues, _defaultValues)),
36816
36944
  isSubmitted: keepStateOptions.keepIsSubmitted ?
36817
36945
  _formState.isSubmitted :
36818
36946
  false,
36819
- dirtyFields: keepStateOptions.keepDirty || keepStateOptions.keepDirtyValues ?
36947
+ dirtyFields: isEmptyResetValues ?
36948
+ {} :
36949
+ keepStateOptions.keepDirtyValues ?
36950
+ keepStateOptions.keepDefaultValues && _formValues ?
36951
+ getDirtyFields(_defaultValues, _formValues) :
36820
36952
  _formState.dirtyFields :
36821
36953
  keepStateOptions.keepDefaultValues && formValues ?
36822
36954
  getDirtyFields(_defaultValues, formValues) :
36955
+ keepStateOptions.keepDirty ?
36956
+ _formState.dirtyFields :
36823
36957
  {},
36824
36958
  touchedFields: keepStateOptions.keepTouched ?
36825
36959
  _formState.touchedFields :
36826
36960
  {},
36827
- errors: keepStateOptions.keepErrors ?
36828
- _formState.errors :
36829
- {},
36830
- isSubmitting: false,
36831
- isSubmitSuccessful: false });
36961
+ errors: keepStateOptions.keepErrors ? _formState.errors : {},
36962
+ isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful ?
36963
+ _formState.isSubmitSuccessful :
36964
+ false,
36965
+ isSubmitting: false });
36832
36966
 
36833
36967
  };
36968
+ const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues) ?
36969
+ formValues(_formValues) :
36970
+ formValues, keepStateOptions);
36834
36971
  const setFocus = (name, options = {}) => {
36835
- const field = get(_fields, name)._f;
36836
- const fieldRef = field.refs ? field.refs[0] : field.ref;
36837
- fieldRef.focus();
36838
- options.shouldSelect && fieldRef.select();
36972
+ const field = get(_fields, name);
36973
+ const fieldReference = field && field._f;
36974
+ if (fieldReference) {
36975
+ const fieldRef = fieldReference.refs ?
36976
+ fieldReference.refs[0] :
36977
+ fieldReference.ref;
36978
+ if (fieldRef.focus) {
36979
+ fieldRef.focus();
36980
+ options.shouldSelect && fieldRef.select();
36981
+ }
36982
+ }
36983
+ };
36984
+ const _updateFormState = (updatedFormState) => {
36985
+ _formState = {
36986
+ ..._formState,
36987
+ ...updatedFormState };
36988
+
36839
36989
  };
36990
+ const _resetDefaultValues = () => isFunction(_options.defaultValues) &&
36991
+ _options.defaultValues().then((values) => {
36992
+ reset(values, _options.resetOptions);
36993
+ _subjects.state.next({
36994
+ isLoading: false });
36995
+
36996
+ });
36840
36997
  return {
36841
36998
  control: {
36842
36999
  register,
36843
37000
  unregister,
36844
37001
  getFieldState,
37002
+ handleSubmit,
37003
+ setError,
36845
37004
  _executeSchema,
36846
37005
  _getWatch,
36847
37006
  _getDirty,
36848
37007
  _updateValid,
36849
37008
  _removeUnmounted,
36850
37009
  _updateFieldArray,
37010
+ _updateDisabledField,
36851
37011
  _getFieldArray,
37012
+ _reset,
37013
+ _resetDefaultValues,
37014
+ _updateFormState,
37015
+ _disableForm,
36852
37016
  _subjects,
36853
37017
  _proxyFormState,
37018
+ _setErrors,
36854
37019
  get _fields() {
36855
37020
  return _fields;
36856
37021
  },
36857
37022
  get _formValues() {
36858
37023
  return _formValues;
36859
37024
  },
36860
- get _stateFlags() {
36861
- return _stateFlags;
37025
+ get _state() {
37026
+ return _state;
36862
37027
  },
36863
- set _stateFlags(value) {
36864
- _stateFlags = value;
37028
+ set _state(value) {
37029
+ _state = value;
36865
37030
  },
36866
37031
  get _defaultValues() {
36867
37032
  return _defaultValues;
@@ -36904,84 +37069,116 @@ Check the top-level render call using <` + t + ">.");
36904
37069
 
36905
37070
  }
36906
37071
 
36907
- /**
36908
- * Custom hook to manage the entire form.
36909
- *
36910
- * @remarks
36911
- * [API](https://react-hook-form.com/api/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
36912
- *
36913
- * @param props - form configuration and validation parameters.
36914
- *
36915
- * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
36916
- *
36917
- * @example
36918
- * ```tsx
36919
- * function App() {
36920
- * const { register, handleSubmit, watch, formState: { errors } } = useForm();
36921
- * const onSubmit = data => console.log(data);
36922
- *
36923
- * console.log(watch("example"));
36924
- *
36925
- * return (
36926
- * <form onSubmit={handleSubmit(onSubmit)}>
36927
- * <input defaultValue="test" {...register("example")} />
36928
- * <input {...register("exampleRequired", { required: true })} />
36929
- * {errors.exampleRequired && <span>This field is required</span>}
36930
- * <input type="submit" />
36931
- * </form>
36932
- * );
36933
- * }
36934
- * ```
37072
+ /**
37073
+ * Custom hook to manage the entire form.
37074
+ *
37075
+ * @remarks
37076
+ * [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)
37077
+ *
37078
+ * @param props - form configuration and validation parameters.
37079
+ *
37080
+ * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
37081
+ *
37082
+ * @example
37083
+ * ```tsx
37084
+ * function App() {
37085
+ * const { register, handleSubmit, watch, formState: { errors } } = useForm();
37086
+ * const onSubmit = data => console.log(data);
37087
+ *
37088
+ * console.log(watch("example"));
37089
+ *
37090
+ * return (
37091
+ * <form onSubmit={handleSubmit(onSubmit)}>
37092
+ * <input defaultValue="test" {...register("example")} />
37093
+ * <input {...register("exampleRequired", { required: true })} />
37094
+ * {errors.exampleRequired && <span>This field is required</span>}
37095
+ * <button>Submit</button>
37096
+ * </form>
37097
+ * );
37098
+ * }
37099
+ * ```
36935
37100
  */
36936
37101
  function useForm(props = {}) {
36937
37102
  const _formControl = React__default["default"].useRef();
37103
+ const _values = React__default["default"].useRef();
36938
37104
  const [formState, updateFormState] = React__default["default"].useState({
36939
37105
  isDirty: false,
36940
37106
  isValidating: false,
36941
- dirtyFields: {},
37107
+ isLoading: isFunction(props.defaultValues),
36942
37108
  isSubmitted: false,
36943
- submitCount: 0,
36944
- touchedFields: {},
36945
37109
  isSubmitting: false,
36946
37110
  isSubmitSuccessful: false,
36947
37111
  isValid: false,
36948
- errors: {} });
37112
+ submitCount: 0,
37113
+ dirtyFields: {},
37114
+ touchedFields: {},
37115
+ validatingFields: {},
37116
+ errors: props.errors || {},
37117
+ disabled: props.disabled || false,
37118
+ defaultValues: isFunction(props.defaultValues) ?
37119
+ undefined :
37120
+ props.defaultValues });
36949
37121
 
36950
- if (_formControl.current) {
36951
- _formControl.current.control._options = props;
36952
- } else
36953
- {
37122
+ if (!_formControl.current) {
36954
37123
  _formControl.current = {
36955
37124
  ...createFormControl(props),
36956
37125
  formState };
36957
37126
 
36958
37127
  }
36959
37128
  const control = _formControl.current.control;
36960
- const callback = React__default["default"].useCallback((value) => {
36961
- if (shouldRenderFormState(value, control._proxyFormState, true)) {
36962
- control._formState = {
36963
- ...control._formState,
36964
- ...value };
36965
-
36966
- updateFormState({ ...control._formState });
36967
- }
36968
- }, [control]);
37129
+ control._options = props;
36969
37130
  useSubscribe({
36970
37131
  subject: control._subjects.state,
36971
- callback });
37132
+ next: (value) => {
37133
+ if (shouldRenderFormState(value, control._proxyFormState, control._updateFormState, true)) {
37134
+ updateFormState({ ...control._formState });
37135
+ }
37136
+ } });
36972
37137
 
37138
+ React__default["default"].useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
36973
37139
  React__default["default"].useEffect(() => {
36974
- if (!control._stateFlags.mount) {
36975
- control._proxyFormState.isValid && control._updateValid();
36976
- control._stateFlags.mount = true;
37140
+ if (control._proxyFormState.isDirty) {
37141
+ const isDirty = control._getDirty();
37142
+ if (isDirty !== formState.isDirty) {
37143
+ control._subjects.state.next({
37144
+ isDirty });
37145
+
37146
+ }
37147
+ }
37148
+ }, [control, formState.isDirty]);
37149
+ React__default["default"].useEffect(() => {
37150
+ if (props.values && !deepEqual(props.values, _values.current)) {
37151
+ control._reset(props.values, control._options.resetOptions);
37152
+ _values.current = props.values;
37153
+ updateFormState((state) => ({ ...state }));
37154
+ } else
37155
+ {
37156
+ control._resetDefaultValues();
37157
+ }
37158
+ }, [props.values, control]);
37159
+ React__default["default"].useEffect(() => {
37160
+ if (props.errors) {
37161
+ control._setErrors(props.errors);
37162
+ }
37163
+ }, [props.errors, control]);
37164
+ React__default["default"].useEffect(() => {
37165
+ if (!control._state.mount) {
37166
+ control._updateValid();
37167
+ control._state.mount = true;
36977
37168
  }
36978
- if (control._stateFlags.watch) {
36979
- control._stateFlags.watch = false;
36980
- control._subjects.state.next({});
37169
+ if (control._state.watch) {
37170
+ control._state.watch = false;
37171
+ control._subjects.state.next({ ...control._formState });
36981
37172
  }
36982
37173
  control._removeUnmounted();
36983
37174
  });
36984
- _formControl.current.formState = getProxyFormState(formState, control._proxyFormState);
37175
+ React__default["default"].useEffect(() => {
37176
+ props.shouldUnregister &&
37177
+ control._subjects.values.next({
37178
+ values: control._getWatch() });
37179
+
37180
+ }, [props.shouldUnregister, control]);
37181
+ _formControl.current.formState = getProxyFormState(formState, control);
36985
37182
  return _formControl.current;
36986
37183
  }
36987
37184
 
@@ -37725,25 +37922,32 @@ Check the top-level render call using <` + t + ">.");
37725
37922
  return [];
37726
37923
  };
37727
37924
  var getDirtyFieldValues = function (formMethods) {
37728
- var dirtyFields = formMethods.formState.dirtyFields,getValues = formMethods.getValues;
37925
+ var getValues = formMethods.getValues,getFieldState = formMethods.getFieldState;
37729
37926
  var allValues = getValues();
37730
- var dirtyValues = Object.keys(dirtyFields).reduce(function (acc, key) {
37731
- if (dirtyFields[key]) {
37927
+ var dirtyValues = Object.keys(getValues()).reduce(function (acc, key) {
37928
+ if (getFieldState(key).isDirty) {
37732
37929
  acc[key] = allValues[key];
37733
37930
  }
37734
37931
  return acc;
37735
37932
  }, {});
37736
37933
  return dirtyValues;
37737
37934
  };
37935
+ var markInitialValuesAsDirty = function (_a) {
37936
+ var formMethods = _a.formMethods,defaultValues = _a.defaultValues,initialValues = _a.initialValues;
37937
+ formMethods.reset(defaultValues);
37938
+ Object.keys(initialValues).forEach(function (key) {
37939
+ formMethods.setValue(key, initialValues[key], {
37940
+ shouldDirty: true,
37941
+ shouldTouch: true });
37942
+
37943
+ });
37944
+ };
37738
37945
 
37739
37946
  var useTraditionalForm = function (_a) {
37740
37947
  var questions = _a.questions,evaluateDisplayConditions = _a.evaluateDisplayConditions,onSubmit = _a.onSubmit,errorLabels = _a.errorLabels,storedAnswers = _a.storedAnswers,_b = _a.autosaveAnswers,autosaveAnswers = _b === void 0 ? true : _b,onAnswersChange = _a.onAnswersChange;
37741
37948
  var initialValues = convertToFormFormat(storedAnswers, questions);
37742
- var defaultValues = !isEmpty(initialValues) && autosaveAnswers ?
37743
- initialValues :
37744
- getInitialValues(questions);
37745
37949
  var formMethods = useForm({
37746
- defaultValues: defaultValues,
37950
+ defaultValues: getInitialValues(questions),
37747
37951
  shouldUnregister: false,
37748
37952
  shouldFocusError: true,
37749
37953
  mode: 'all' });
@@ -37780,6 +37984,23 @@ Check the top-level render call using <` + t + ">.");
37780
37984
  React.useEffect(function () {
37781
37985
  updateQuestionVisibility();
37782
37986
  }, [updateQuestionVisibility]);
37987
+ React.useEffect(function () {
37988
+ if (autosaveAnswers && !isEmpty(initialValues)) {
37989
+ markInitialValuesAsDirty({
37990
+ formMethods: formMethods,
37991
+ initialValues: initialValues,
37992
+ defaultValues: getInitialValues(questions) });
37993
+
37994
+ formMethods.trigger().then(function () {
37995
+ var _a;
37996
+ var allValues = formMethods.getValues();
37997
+ if (onAnswersChange) {
37998
+ onAnswersChange((_a = JSON.stringify(allValues)) !== null && _a !== void 0 ? _a : '{}');
37999
+ }
38000
+ updateQuestionVisibility();
38001
+ });
38002
+ }
38003
+ }, []);
37783
38004
  var handleConvertAndSubmitForm = function (formResponse) {return __awaiter(void 0, void 0, void 0, function () {
37784
38005
  return __generator(this, function (_a) {
37785
38006
  switch (_a.label) {
@@ -37797,17 +38018,17 @@ Check the top-level render call using <` + t + ">.");
37797
38018
  });
37798
38019
  });};
37799
38020
  var submitForm = function () {return __awaiter(void 0, void 0, void 0, function () {
37800
- var errors;
38021
+ var formErrors;
37801
38022
  return __generator(this, function (_a) {
37802
38023
  switch (_a.label) {
37803
38024
  case 0:return [4, updateQuestionVisibility()];
37804
38025
  case 1:
37805
38026
  _a.sent();
37806
- errors = visibleQuestions.flatMap(function (vq) {
38027
+ formErrors = visibleQuestions.flatMap(function (vq) {
37807
38028
  return getErrorsForQuestion(vq, formMethods, errorLabels, isValidE164Number, validateDateResponse, validateNumberResponse);
37808
38029
  });
37809
- setErrors(errors);
37810
- if (errors.length == 0) {
38030
+ setErrors(formErrors);
38031
+ if (formErrors.length === 0) {
37811
38032
  setFormHasErrors(false);
37812
38033
  formMethods.handleSubmit(handleConvertAndSubmitForm)();
37813
38034
  } else
@@ -37833,11 +38054,8 @@ Check the top-level render call using <` + t + ">.");
37833
38054
  var questions = _a.questions,evaluateDisplayConditions = _a.evaluateDisplayConditions,onSubmit = _a.onSubmit,errorLabels = _a.errorLabels,storedAnswers = _a.storedAnswers,_b = _a.autosaveAnswers,autosaveAnswers = _b === void 0 ? true : _b,onAnswersChange = _a.onAnswersChange;
37834
38055
  var initialValues = convertToFormFormat(storedAnswers, questions);
37835
38056
  var _c = useValidate(),isValidE164Number = _c.isValidE164Number,validateDateResponse = _c.validateDateResponse,validateNumberResponse = _c.validateNumberResponse;
37836
- var defaultValues = !isEmpty(initialValues) && autosaveAnswers ?
37837
- initialValues :
37838
- getInitialValues(questions);
37839
38057
  var formMethods = useForm({
37840
- defaultValues: defaultValues,
38058
+ defaultValues: getInitialValues(questions),
37841
38059
  shouldUnregister: false,
37842
38060
  shouldFocusError: true,
37843
38061
  mode: 'all' });
@@ -37885,6 +38103,23 @@ Check the top-level render call using <` + t + ">.");
37885
38103
  React.useEffect(function () {
37886
38104
  updateQuestionVisibility();
37887
38105
  }, [updateQuestionVisibility]);
38106
+ React.useEffect(function () {
38107
+ if (autosaveAnswers && !isEmpty(initialValues)) {
38108
+ markInitialValuesAsDirty({
38109
+ formMethods: formMethods,
38110
+ initialValues: initialValues,
38111
+ defaultValues: getInitialValues(questions) });
38112
+
38113
+ formMethods.trigger().then(function () {
38114
+ var _a;
38115
+ var allValues = formMethods.getValues();
38116
+ if (onAnswersChange) {
38117
+ onAnswersChange((_a = JSON.stringify(allValues)) !== null && _a !== void 0 ? _a : '{}');
38118
+ }
38119
+ updateQuestionVisibility();
38120
+ });
38121
+ }
38122
+ }, []);
37888
38123
  var handleCheckForErrors = function (currentQuestion) {
37889
38124
  var errorsWithoutCurrent = errors.filter(function (err) {return err.id !== (currentQuestion === null || currentQuestion === void 0 ? void 0 : currentQuestion.id);});
37890
38125
  var existingErrors = getErrorsForQuestion(currentQuestion, formMethods, errorLabels, isValidE164Number, validateDateResponse, validateNumberResponse);