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