react-hook-form 5.1.0 → 5.1.3

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.
@@ -1,5 +1,5 @@
1
1
  import * as React from 'react';
2
- import { DeepPartial, FieldValues, FormStateProxy, FieldErrors, OnSubmit, FieldElement, ValidationOptions, FieldName, FieldValue, ManualFieldError, MultipleFieldErrors, Control } from './types';
2
+ import { DeepPartial, FieldValues, FormStateProxy, FieldErrors, OnSubmit, FieldElement, ValidationOptions, FieldName, FieldValue, ManualFieldError, MultipleFieldErrors, Control, OmitResetState } from './types';
3
3
  export declare type FormProps<FormValues extends FieldValues = FieldValues> = {
4
4
  children: React.ReactNode;
5
5
  } & FormContextValues<FormValues>;
@@ -36,7 +36,7 @@ export declare type FormContextValues<FormValues extends FieldValues = FieldValu
36
36
  triggerValidation: (payload?: FieldName<FormValues> | FieldName<FormValues>[] | string, shouldRender?: boolean) => Promise<boolean>;
37
37
  errors: FieldErrors<FormValues>;
38
38
  formState: FormStateProxy<FormValues>;
39
- reset: (values?: DeepPartial<FormValues>) => void;
39
+ reset: (values?: DeepPartial<FormValues>, omitResetState?: OmitResetState) => void;
40
40
  getValues: (payload?: {
41
41
  nest: boolean;
42
42
  }) => FormValues;
@@ -1,6 +1,6 @@
1
1
  import * as React from 'react';
2
2
  import { FieldName, FormValuesFromErrors } from './types';
3
- declare const ErrorMessage: <Errors extends import("./types").NestDataObject<any>, Name extends FieldName<FormValuesFromErrors<Errors>>, As extends "symbol" | "object" | React.ReactElement<any, string | ((props: any) => React.ReactElement<any, string | any | (new (props: any) => React.Component<any, any, any>)> | null) | (new (props: any) => React.Component<any, any, any>)> | React.ComponentClass<any, any> | React.FunctionComponent<any> | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | "b" | "base" | "bdi" | "bdo" | "big" | "blockquote" | "body" | "br" | "button" | "canvas" | "caption" | "cite" | "code" | "col" | "colgroup" | "data" | "datalist" | "dd" | "del" | "details" | "dfn" | "dialog" | "div" | "dl" | "dt" | "em" | "embed" | "fieldset" | "figcaption" | "figure" | "footer" | "form" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "head" | "header" | "hgroup" | "hr" | "html" | "i" | "iframe" | "img" | "input" | "ins" | "kbd" | "keygen" | "label" | "legend" | "li" | "link" | "main" | "map" | "mark" | "menu" | "menuitem" | "meta" | "meter" | "nav" | "noindex" | "noscript" | "ol" | "optgroup" | "option" | "output" | "p" | "param" | "picture" | "pre" | "progress" | "q" | "rp" | "rt" | "ruby" | "s" | "samp" | "script" | "section" | "select" | "small" | "source" | "span" | "strong" | "style" | "sub" | "summary" | "sup" | "table" | "template" | "tbody" | "td" | "textarea" | "tfoot" | "th" | "thead" | "time" | "title" | "tr" | "track" | "u" | "ul" | "var" | "video" | "wbr" | "webview" | "svg" | "animate" | "animateMotion" | "animateTransform" | "circle" | "clipPath" | "defs" | "desc" | "ellipse" | "feBlend" | "feColorMatrix" | "feComponentTransfer" | "feComposite" | "feConvolveMatrix" | "feDiffuseLighting" | "feDisplacementMap" | "feDistantLight" | "feDropShadow" | "feFlood" | "feFuncA" | "feFuncB" | "feFuncG" | "feFuncR" | "feGaussianBlur" | "feImage" | "feMerge" | "feMergeNode" | "feMorphology" | "feOffset" | "fePointLight" | "feSpecularLighting" | "feSpotLight" | "feTile" | "feTurbulence" | "filter" | "foreignObject" | "g" | "image" | "line" | "linearGradient" | "marker" | "mask" | "metadata" | "mpath" | "path" | "pattern" | "polygon" | "polyline" | "radialGradient" | "rect" | "stop" | "switch" | "text" | "textPath" | "tspan" | "use" | "view" | undefined = undefined>({ as: InnerComponent, errors, name, message, children, ...rest }: import("./types").Assign<{
3
+ declare const ErrorMessage: <Errors extends import("./types").NestDataObject<any, import("./types").FieldError>, Name extends FieldName<FormValuesFromErrors<Errors>>, As extends "symbol" | "object" | React.ReactElement<any, string | ((props: any) => React.ReactElement<any, string | any | (new (props: any) => React.Component<any, any, any>)> | null) | (new (props: any) => React.Component<any, any, any>)> | React.ComponentClass<any, any> | React.FunctionComponent<any> | "a" | "abbr" | "address" | "area" | "article" | "aside" | "audio" | "b" | "base" | "bdi" | "bdo" | "big" | "blockquote" | "body" | "br" | "button" | "canvas" | "caption" | "cite" | "code" | "col" | "colgroup" | "data" | "datalist" | "dd" | "del" | "details" | "dfn" | "dialog" | "div" | "dl" | "dt" | "em" | "embed" | "fieldset" | "figcaption" | "figure" | "footer" | "form" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "head" | "header" | "hgroup" | "hr" | "html" | "i" | "iframe" | "img" | "input" | "ins" | "kbd" | "keygen" | "label" | "legend" | "li" | "link" | "main" | "map" | "mark" | "menu" | "menuitem" | "meta" | "meter" | "nav" | "noindex" | "noscript" | "ol" | "optgroup" | "option" | "output" | "p" | "param" | "picture" | "pre" | "progress" | "q" | "rp" | "rt" | "ruby" | "s" | "samp" | "script" | "section" | "select" | "small" | "source" | "span" | "strong" | "style" | "sub" | "summary" | "sup" | "table" | "template" | "tbody" | "td" | "textarea" | "tfoot" | "th" | "thead" | "time" | "title" | "tr" | "track" | "u" | "ul" | "var" | "video" | "wbr" | "webview" | "svg" | "animate" | "animateMotion" | "animateTransform" | "circle" | "clipPath" | "defs" | "desc" | "ellipse" | "feBlend" | "feColorMatrix" | "feComponentTransfer" | "feComposite" | "feConvolveMatrix" | "feDiffuseLighting" | "feDisplacementMap" | "feDistantLight" | "feDropShadow" | "feFlood" | "feFuncA" | "feFuncB" | "feFuncG" | "feFuncR" | "feGaussianBlur" | "feImage" | "feMerge" | "feMergeNode" | "feMorphology" | "feOffset" | "fePointLight" | "feSpecularLighting" | "feSpotLight" | "feTile" | "feTurbulence" | "filter" | "foreignObject" | "g" | "image" | "line" | "linearGradient" | "marker" | "mask" | "metadata" | "mpath" | "path" | "pattern" | "polygon" | "polyline" | "radialGradient" | "rect" | "stop" | "switch" | "text" | "textPath" | "tspan" | "use" | "view" | undefined = undefined>({ as: InnerComponent, errors, name, message, children, ...rest }: import("./types").Assign<{
4
4
  as?: As | undefined;
5
5
  errors?: Errors | undefined;
6
6
  name: Name;
@@ -1,2 +1,2 @@
1
- declare const _default: <FormValues>(fields: Partial<Record<import("../types").FieldName<FormValues>, import("../types").Field>>, fieldErrors: import("../types").NestDataObject<FormValues>) => void;
1
+ declare const _default: <FormValues>(fields: Partial<Record<import("../types").FieldName<FormValues>, import("../types").Field>>, fieldErrors: import("../types").NestDataObject<FormValues, import("../types").FieldError>) => void;
2
2
  export default _default;
@@ -1,9 +1,10 @@
1
- declare const _default: ({ hasError, isBlurEvent, isOnSubmit, isReValidateOnSubmit, isOnBlur, isReValidateOnBlur, isSubmitted, }: {
1
+ declare const _default: ({ isOnChange, hasError, isBlurEvent, isOnSubmit, isReValidateOnSubmit, isOnBlur, isReValidateOnBlur, isSubmitted, }: {
2
2
  hasError: boolean;
3
+ isOnChange: boolean;
3
4
  isBlurEvent?: boolean | undefined;
4
5
  isOnSubmit: boolean;
5
- isReValidateOnSubmit: boolean;
6
6
  isOnBlur: boolean;
7
+ isReValidateOnSubmit: boolean;
7
8
  isReValidateOnBlur: boolean;
8
9
  isSubmitted: boolean;
9
10
  }) => boolean;
@@ -1,4 +1,4 @@
1
1
  import * as React from 'react';
2
- import { Field } from '../types';
3
- declare const _default: <FormValues extends Record<string, any>>(fieldsRef: React.MutableRefObject<Partial<Record<import("../types").FieldName<FormValues>, Field>>>, validateAllFieldCriteria: boolean, { ref, ref: { type, value, name }, options, required, maxLength, minLength, min, max, pattern, validate, }: Field) => Promise<import("../types").NestDataObject<FormValues>>;
2
+ import { Field, FieldError } from '../types';
3
+ declare const _default: <FormValues extends Record<string, any>>(fieldsRef: React.MutableRefObject<Partial<Record<import("../types").FieldName<FormValues>, Field>>>, validateAllFieldCriteria: boolean, { ref, ref: { type, value, name }, options, required, maxLength, minLength, min, max, pattern, validate, }: Field) => Promise<import("../types").NestDataObject<FormValues, FieldError>>;
4
4
  export default _default;
@@ -1,8 +1,4 @@
1
- import { FieldValues, SchemaValidateOptions, FieldErrors, ValidationResolver } from '../types';
2
- declare type SchemaValidationResult<FormValues> = {
3
- errors: FieldErrors<FormValues>;
4
- values: FieldValues;
5
- };
1
+ import { FieldValues, SchemaValidateOptions, ValidationResolver, SchemaValidationResult } from '../types';
6
2
  declare type YupValidationError = {
7
3
  inner: {
8
4
  path: string;
@@ -16,6 +12,6 @@ declare type YupValidationError = {
16
12
  declare type Schema<Data> = {
17
13
  validate(value: FieldValues, options?: SchemaValidateOptions): Promise<Data>;
18
14
  };
19
- export declare const parseErrorSchema: <FormValues>(error: YupValidationError, validateAllFieldCriteria: boolean) => import("../types").NestDataObject<FormValues>;
20
- export default function validateWithSchema<FormValues, ValidationContext>(validationSchema: Schema<FormValues>, validateAllFieldCriteria: boolean, data: FormValues, validationResolver?: ValidationResolver<FormValues, ValidationContext>, context?: ValidationContext): Promise<SchemaValidationResult<FormValues>>;
15
+ export declare const parseErrorSchema: <FormValues>(error: YupValidationError, validateAllFieldCriteria: boolean) => import("../types").NestDataObject<FormValues, import("../types").FieldError>;
16
+ export default function validateWithSchema<FormValues extends FieldValues, ValidationContext extends object>(validationSchema: Schema<FormValues>, validateAllFieldCriteria: boolean, data: FormValues, validationResolver?: ValidationResolver<FormValues, ValidationContext>, context?: ValidationContext): Promise<SchemaValidationResult<FormValues>>;
21
17
  export {};
@@ -622,7 +622,8 @@ var assignWatchFields = (fieldValues, fieldName, watchFields, combinedDefaultVal
622
622
  : value;
623
623
  };
624
624
 
625
- var skipValidation = ({ hasError, isBlurEvent, isOnSubmit, isReValidateOnSubmit, isOnBlur, isReValidateOnBlur, isSubmitted, }) => (isOnSubmit && isReValidateOnSubmit) ||
625
+ var skipValidation = ({ isOnChange, hasError, isBlurEvent, isOnSubmit, isReValidateOnSubmit, isOnBlur, isReValidateOnBlur, isSubmitted, }) => (isOnChange && isBlurEvent) ||
626
+ (isOnSubmit && isReValidateOnSubmit) ||
626
627
  (isOnSubmit && !isSubmitted) ||
627
628
  (isOnBlur && !isBlurEvent && !hasError) ||
628
629
  (isReValidateOnBlur && !isBlurEvent && hasError) ||
@@ -711,7 +712,7 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
711
712
  const validationContextRef = useRef(validationContext);
712
713
  const fieldArrayNamesRef = useRef(new Set());
713
714
  const [, render] = useState();
714
- const { isOnBlur, isOnSubmit } = useRef(modeChecker(mode)).current;
715
+ const { isOnBlur, isOnSubmit, isOnChange } = useRef(modeChecker(mode)).current;
715
716
  const isWindowUndefined = typeof window === UNDEFINED;
716
717
  const shouldValidateCallback = !!(validationSchema || validationResolver);
717
718
  const isWeb = typeof document !== UNDEFINED &&
@@ -907,14 +908,9 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
907
908
  reRender,
908
909
  shouldValidateCallback,
909
910
  ]);
910
- const isFieldWatched = (name) => {
911
- const preFixName = (name.match(/\w+/) || [])[0];
912
- return (isWatchAllRef.current ||
913
- watchFieldsRef.current.has(name) ||
914
- (watchFieldsRef.current.has(preFixName) &&
915
- !isKey(name) &&
916
- fieldArrayNamesRef.current.has(preFixName)));
917
- };
911
+ const isFieldWatched = (name) => isWatchAllRef.current ||
912
+ watchFieldsRef.current.has(name) ||
913
+ watchFieldsRef.current.has((name.match(/\w+/) || [])[0]);
918
914
  function setValue(names, valueOrShouldValidate, shouldValidate) {
919
915
  let shouldRender = false;
920
916
  const isMultiple = isArray(names);
@@ -951,6 +947,7 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
951
947
  const isBlurEvent = type === EVENTS.BLUR;
952
948
  const shouldSkipValidation = skipValidation({
953
949
  hasError: !!currentError,
950
+ isOnChange,
954
951
  isBlurEvent,
955
952
  isOnSubmit,
956
953
  isReValidateOnSubmit,
@@ -1234,19 +1231,19 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
1234
1231
  const resolvedPrevious = await previous;
1235
1232
  const { ref, ref: { name }, } = field;
1236
1233
  if (!fields[name]) {
1237
- return Promise.resolve(resolvedPrevious);
1234
+ return resolvedPrevious;
1238
1235
  }
1239
1236
  const fieldError = await validateField(fieldsRef, validateAllFieldCriteria, field);
1240
1237
  if (fieldError[name]) {
1241
1238
  set(resolvedPrevious.errors, name, fieldError[name]);
1242
1239
  validFieldsRef.current.delete(name);
1243
- return Promise.resolve(resolvedPrevious);
1240
+ return resolvedPrevious;
1244
1241
  }
1245
1242
  if (fieldsWithValidationRef.current.has(name)) {
1246
1243
  validFieldsRef.current.add(name);
1247
1244
  }
1248
1245
  resolvedPrevious.values[name] = getFieldValue(fields, ref);
1249
- return Promise.resolve(resolvedPrevious);
1246
+ return resolvedPrevious;
1250
1247
  }, Promise.resolve({
1251
1248
  errors: {},
1252
1249
  values: {},
@@ -1338,6 +1335,7 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
1338
1335
  useEffect(() => () => {
1339
1336
  isUnMount.current = true;
1340
1337
  fieldsRef.current &&
1338
+ process.env.NODE_ENV === 'production' &&
1341
1339
  Object.values(fieldsRef.current).forEach((field) => removeFieldEventListenerAndRef(field, true));
1342
1340
  }, [removeFieldEventListenerAndRef]);
1343
1341
  if (!shouldValidateCallback) {
@@ -1365,6 +1363,7 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
1365
1363
  triggerValidation }, (shouldValidateCallback ? { validateSchemaIsValid } : {})), { formState, mode: {
1366
1364
  isOnBlur,
1367
1365
  isOnSubmit,
1366
+ isOnChange,
1368
1367
  }, reValidateMode: {
1369
1368
  isReValidateOnBlur,
1370
1369
  isReValidateOnSubmit,
@@ -1444,12 +1443,7 @@ function __rest(s, e) {
1444
1443
 
1445
1444
  const FormGlobalContext = createContext(null);
1446
1445
  function useFormContext() {
1447
- const context = useContext(FormGlobalContext);
1448
- if (isNullOrUndefined(context)) {
1449
- // eslint-disable-next-line no-console
1450
- console.warn('Missing FormContext');
1451
- }
1452
- return context;
1446
+ return useContext(FormGlobalContext);
1453
1447
  }
1454
1448
  function FormContext(_a) {
1455
1449
  var { children, formState, errors } = _a, restMethods = __rest(_a, ["children", "formState", "errors"]);
@@ -1537,14 +1531,14 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1537
1531
  const currentFieldsValue = getValues({ nest: true })[name];
1538
1532
  if (isArray(currentFieldsValue)) {
1539
1533
  for (let i = 0; i < currentFieldsValue.length; i++) {
1540
- fields[i] = Object.assign(Object.assign({}, fields[i]), currentFieldsValue[i]);
1534
+ allFields.current[i] = Object.assign(Object.assign({}, allFields.current[i]), currentFieldsValue[i]);
1541
1535
  }
1542
1536
  }
1543
1537
  };
1544
1538
  const append = (value) => {
1545
- mapCurrentFieldsValueWithState();
1546
1539
  if (readFormStateRef.current.dirty) {
1547
1540
  isDirtyRef.current = true;
1541
+ reRender();
1548
1542
  }
1549
1543
  commonTasks([
1550
1544
  ...allFields.current,
@@ -1554,7 +1548,6 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1554
1548
  ]);
1555
1549
  };
1556
1550
  const prepend = (value) => {
1557
- mapCurrentFieldsValueWithState();
1558
1551
  resetFields();
1559
1552
  commonTasks(prependAt(allFields.current, isArray(value) ? appendValueWithKey(value) : [appendId(value, keyName)]));
1560
1553
  if (errorsRef.current[name]) {
@@ -1562,9 +1555,11 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1562
1555
  }
1563
1556
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1564
1557
  touchedFieldsRef.current[name] = prependAt(touchedFieldsRef.current[name], fillEmptyArray(value));
1558
+ reRender();
1565
1559
  }
1566
1560
  };
1567
1561
  const remove = (index) => {
1562
+ let shouldRender = false;
1568
1563
  if (!isUndefined(index)) {
1569
1564
  mapCurrentFieldsValueWithState();
1570
1565
  }
@@ -1578,6 +1573,7 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1578
1573
  }
1579
1574
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1580
1575
  touchedFieldsRef.current[name] = removeArrayAt(touchedFieldsRef.current[name], index);
1576
+ shouldRender = true;
1581
1577
  }
1582
1578
  if (readFormStateRef.current.dirty) {
1583
1579
  dirtyFieldsRef.current.forEach(dirtyField => {
@@ -1585,6 +1581,7 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1585
1581
  dirtyFieldsRef.current.delete(dirtyField);
1586
1582
  }
1587
1583
  });
1584
+ shouldRender = true;
1588
1585
  }
1589
1586
  if (readFormStateRef.current.isValid && !validateSchemaIsValid) {
1590
1587
  let fieldIndex = -1;
@@ -1616,6 +1613,9 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1616
1613
  }
1617
1614
  }
1618
1615
  }
1616
+ shouldRender = true;
1617
+ }
1618
+ if (shouldRender) {
1619
1619
  reRender();
1620
1620
  }
1621
1621
  };
@@ -1628,6 +1628,7 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1628
1628
  }
1629
1629
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1630
1630
  touchedFieldsRef.current[name] = insertAt(touchedFieldsRef.current[name], index, fillEmptyArray(value));
1631
+ reRender();
1631
1632
  }
1632
1633
  };
1633
1634
  const swap = (indexA, indexB) => {
@@ -1642,6 +1643,7 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1642
1643
  }
1643
1644
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1644
1645
  swapArrayAt(touchedFieldsRef.current[name], indexA, indexB);
1646
+ reRender();
1645
1647
  }
1646
1648
  };
1647
1649
  const move = (from, to) => {
@@ -1656,6 +1658,7 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1656
1658
  }
1657
1659
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1658
1660
  moveArrayAt(touchedFieldsRef.current[name], from, to);
1661
+ reRender();
1659
1662
  }
1660
1663
  };
1661
1664
  const reset = () => {
@@ -1698,7 +1701,7 @@ var getInputValue = (event, isCheckboxInput) => isPrimitive(event) ||
1698
1701
  const Controller = (_a) => {
1699
1702
  var { name, rules, as: InnerComponent, onBlur, onChange, onChangeName = VALIDATION_MODE.onChange, onBlurName = VALIDATION_MODE.onBlur, valueName, defaultValue, control } = _a, rest = __rest(_a, ["name", "rules", "as", "onBlur", "onChange", "onChangeName", "onBlurName", "valueName", "defaultValue", "control"]);
1700
1703
  const methods = useFormContext();
1701
- const { defaultValuesRef, setValue, register, unregister, errorsRef, removeFieldEventListener, triggerValidation, mode: { isOnSubmit, isOnBlur }, reValidateMode: { isReValidateOnBlur, isReValidateOnSubmit }, formState: { isSubmitted }, fieldsRef, fieldArrayNamesRef, } = control || methods.control;
1704
+ const { defaultValuesRef, setValue, register, unregister, errorsRef, removeFieldEventListener, triggerValidation, mode: { isOnSubmit, isOnBlur, isOnChange }, reValidateMode: { isReValidateOnBlur, isReValidateOnSubmit }, formState: { isSubmitted }, fieldsRef, fieldArrayNamesRef, } = control || methods.control;
1702
1705
  const [value, setInputStateValue] = useState$2(isUndefined(defaultValue)
1703
1706
  ? get(defaultValuesRef.current, name)
1704
1707
  : defaultValue);
@@ -1708,6 +1711,7 @@ const Controller = (_a) => {
1708
1711
  hasError: !!get(errorsRef.current, name),
1709
1712
  isOnBlur,
1710
1713
  isOnSubmit,
1714
+ isOnChange,
1711
1715
  isReValidateOnBlur,
1712
1716
  isReValidateOnSubmit,
1713
1717
  isSubmitted,
@@ -1275,8 +1275,8 @@ var every$2 = every$1;
1275
1275
 
1276
1276
  var engineUserAgent = getBuiltIn('navigator', 'userAgent') || '';
1277
1277
 
1278
- var process = global_1.process;
1279
- var versions = process && process.versions;
1278
+ var process$1 = global_1.process;
1279
+ var versions = process$1 && process$1.versions;
1280
1280
  var v8 = versions && versions.v8;
1281
1281
  var match, version;
1282
1282
 
@@ -1541,7 +1541,7 @@ var engineIsIos = /(iphone|ipod|ipad).*applewebkit/i.test(engineUserAgent);
1541
1541
  var location = global_1.location;
1542
1542
  var set$1 = global_1.setImmediate;
1543
1543
  var clear = global_1.clearImmediate;
1544
- var process$1 = global_1.process;
1544
+ var process$2 = global_1.process;
1545
1545
  var MessageChannel = global_1.MessageChannel;
1546
1546
  var Dispatch = global_1.Dispatch;
1547
1547
  var counter = 0;
@@ -1590,9 +1590,9 @@ if (!set$1 || !clear) {
1590
1590
  delete queue[id];
1591
1591
  };
1592
1592
  // Node.js 0.8-
1593
- if (classofRaw(process$1) == 'process') {
1593
+ if (classofRaw(process$2) == 'process') {
1594
1594
  defer = function (id) {
1595
- process$1.nextTick(runner(id));
1595
+ process$2.nextTick(runner(id));
1596
1596
  };
1597
1597
  // Sphere (JS game engine) Dispatch API
1598
1598
  } else if (Dispatch && Dispatch.now) {
@@ -1638,9 +1638,9 @@ var macrotask = task.set;
1638
1638
 
1639
1639
 
1640
1640
  var MutationObserver$1 = global_1.MutationObserver || global_1.WebKitMutationObserver;
1641
- var process$2 = global_1.process;
1641
+ var process$3 = global_1.process;
1642
1642
  var Promise$1 = global_1.Promise;
1643
- var IS_NODE = classofRaw(process$2) == 'process';
1643
+ var IS_NODE = classofRaw(process$3) == 'process';
1644
1644
  // Node.js 11 shows ExperimentalWarning on getting `queueMicrotask`
1645
1645
  var queueMicrotaskDescriptor = getOwnPropertyDescriptor$2(global_1, 'queueMicrotask');
1646
1646
  var queueMicrotask = queueMicrotaskDescriptor && queueMicrotaskDescriptor.value;
@@ -1651,7 +1651,7 @@ var flush, head, last, notify, toggle, node, promise, then;
1651
1651
  if (!queueMicrotask) {
1652
1652
  flush = function () {
1653
1653
  var parent, fn;
1654
- if (IS_NODE && (parent = process$2.domain)) parent.exit();
1654
+ if (IS_NODE && (parent = process$3.domain)) parent.exit();
1655
1655
  while (head) {
1656
1656
  fn = head.fn;
1657
1657
  head = head.next;
@@ -1669,7 +1669,7 @@ if (!queueMicrotask) {
1669
1669
  // Node.js
1670
1670
  if (IS_NODE) {
1671
1671
  notify = function () {
1672
- process$2.nextTick(flush);
1672
+ process$3.nextTick(flush);
1673
1673
  };
1674
1674
  // browsers with MutationObserver, except iOS - https://github.com/zloirock/core-js/issues/339
1675
1675
  } else if (MutationObserver$1 && !engineIsIos) {
@@ -1773,11 +1773,11 @@ var getInternalPromiseState = internalState.getterFor(PROMISE);
1773
1773
  var PromiseConstructor = nativePromiseConstructor;
1774
1774
  var TypeError$1 = global_1.TypeError;
1775
1775
  var document$2 = global_1.document;
1776
- var process$3 = global_1.process;
1776
+ var process$4 = global_1.process;
1777
1777
  var $fetch = getBuiltIn('fetch');
1778
1778
  var newPromiseCapability$1 = newPromiseCapability.f;
1779
1779
  var newGenericPromiseCapability = newPromiseCapability$1;
1780
- var IS_NODE$1 = classofRaw(process$3) == 'process';
1780
+ var IS_NODE$1 = classofRaw(process$4) == 'process';
1781
1781
  var DISPATCH_EVENT = !!(document$2 && document$2.createEvent && global_1.dispatchEvent);
1782
1782
  var UNHANDLED_REJECTION = 'unhandledrejection';
1783
1783
  var REJECTION_HANDLED = 'rejectionhandled';
@@ -1893,7 +1893,7 @@ var onUnhandled = function (promise, state) {
1893
1893
  if (IS_UNHANDLED) {
1894
1894
  result = perform(function () {
1895
1895
  if (IS_NODE$1) {
1896
- process$3.emit('unhandledRejection', value, promise);
1896
+ process$4.emit('unhandledRejection', value, promise);
1897
1897
  } else dispatchEvent(UNHANDLED_REJECTION, promise, value);
1898
1898
  });
1899
1899
  // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
@@ -1910,7 +1910,7 @@ var isUnhandled = function (state) {
1910
1910
  var onHandleUnhandled = function (promise, state) {
1911
1911
  task$1.call(global_1, function () {
1912
1912
  if (IS_NODE$1) {
1913
- process$3.emit('rejectionHandled', promise);
1913
+ process$4.emit('rejectionHandled', promise);
1914
1914
  } else dispatchEvent(REJECTION_HANDLED, promise, state.value);
1915
1915
  });
1916
1916
  };
@@ -1994,7 +1994,7 @@ if (FORCED) {
1994
1994
  var reaction = newPromiseCapability$1(speciesConstructor(this, PromiseConstructor));
1995
1995
  reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
1996
1996
  reaction.fail = typeof onRejected == 'function' && onRejected;
1997
- reaction.domain = IS_NODE$1 ? process$3.domain : undefined;
1997
+ reaction.domain = IS_NODE$1 ? process$4.domain : undefined;
1998
1998
  state.parent = true;
1999
1999
  state.reactions.push(reaction);
2000
2000
  if (state.state != PENDING) notify$1(this, state, false);
@@ -4014,14 +4014,15 @@ var assignWatchFields = (function (fieldValues, fieldName, watchFields, combined
4014
4014
  });
4015
4015
 
4016
4016
  var skipValidation = (function (_a) {
4017
- var hasError = _a.hasError,
4017
+ var isOnChange = _a.isOnChange,
4018
+ hasError = _a.hasError,
4018
4019
  isBlurEvent = _a.isBlurEvent,
4019
4020
  isOnSubmit = _a.isOnSubmit,
4020
4021
  isReValidateOnSubmit = _a.isReValidateOnSubmit,
4021
4022
  isOnBlur = _a.isOnBlur,
4022
4023
  isReValidateOnBlur = _a.isReValidateOnBlur,
4023
4024
  isSubmitted = _a.isSubmitted;
4024
- return isOnSubmit && isReValidateOnSubmit || isOnSubmit && !isSubmitted || isOnBlur && !isBlurEvent && !hasError || isReValidateOnBlur && !isBlurEvent && hasError || isReValidateOnSubmit && isSubmitted;
4025
+ return isOnChange && isBlurEvent || isOnSubmit && isReValidateOnSubmit || isOnSubmit && !isSubmitted || isOnBlur && !isBlurEvent && !hasError || isReValidateOnBlur && !isBlurEvent && hasError || isReValidateOnSubmit && isSubmitted;
4025
4026
  });
4026
4027
 
4027
4028
  var getFieldValueByName = (function (fields, name) {
@@ -4146,7 +4147,8 @@ function useForm(_a) {
4146
4147
 
4147
4148
  var _h = useRef(modeChecker(mode)).current,
4148
4149
  isOnBlur = _h.isOnBlur,
4149
- isOnSubmit = _h.isOnSubmit;
4150
+ isOnSubmit = _h.isOnSubmit,
4151
+ isOnChange = _h.isOnChange;
4150
4152
  var isWindowUndefined = typeof window === UNDEFINED;
4151
4153
  var shouldValidateCallback = !!(validationSchema || validationResolver);
4152
4154
  var isWeb = typeof document !== UNDEFINED && !isWindowUndefined && !isUndefined(window.HTMLElement);
@@ -4424,8 +4426,7 @@ function useForm(_a) {
4424
4426
  }, [executeSchemaValidation, executeValidation, reRender, shouldValidateCallback]);
4425
4427
 
4426
4428
  var isFieldWatched = function (name) {
4427
- var preFixName = (name.match(/\w+/) || [])[0];
4428
- return isWatchAllRef.current || watchFieldsRef.current.has(name) || watchFieldsRef.current.has(preFixName) && !isKey(name) && fieldArrayNamesRef.current.has(preFixName);
4429
+ return isWatchAllRef.current || watchFieldsRef.current.has(name) || watchFieldsRef.current.has((name.match(/\w+/) || [])[0]);
4429
4430
  };
4430
4431
 
4431
4432
  function setValue(names, valueOrShouldValidate, shouldValidate) {
@@ -4474,6 +4475,7 @@ function useForm(_a) {
4474
4475
  isBlurEvent = type === EVENTS.BLUR;
4475
4476
  shouldSkipValidation = skipValidation({
4476
4477
  hasError: !!currentError,
4478
+ isOnChange: isOnChange,
4477
4479
  isBlurEvent: isBlurEvent,
4478
4480
  isOnSubmit: isOnSubmit,
4479
4481
  isReValidateOnSubmit: isReValidateOnSubmit,
@@ -4881,7 +4883,7 @@ function useForm(_a) {
4881
4883
  if (!fields[name]) {
4882
4884
  return [2
4883
4885
  /*return*/
4884
- , promise$3.resolve(resolvedPrevious)];
4886
+ , resolvedPrevious];
4885
4887
  }
4886
4888
 
4887
4889
  return [4
@@ -4896,7 +4898,7 @@ function useForm(_a) {
4896
4898
  validFieldsRef.current.delete(name);
4897
4899
  return [2
4898
4900
  /*return*/
4899
- , promise$3.resolve(resolvedPrevious)];
4901
+ , resolvedPrevious];
4900
4902
  }
4901
4903
 
4902
4904
  if (fieldsWithValidationRef.current.has(name)) {
@@ -4906,7 +4908,7 @@ function useForm(_a) {
4906
4908
  values$2(resolvedPrevious)[name] = getFieldValue(fields, ref);
4907
4909
  return [2
4908
4910
  /*return*/
4909
- , promise$3.resolve(resolvedPrevious)];
4911
+ , resolvedPrevious];
4910
4912
  }
4911
4913
  });
4912
4914
  });
@@ -5067,7 +5069,7 @@ function useForm(_a) {
5067
5069
  var _context8;
5068
5070
 
5069
5071
  isUnMount.current = true;
5070
- fieldsRef.current && forEach$2(_context8 = values$5(fieldsRef.current)).call(_context8, function (field) {
5072
+ fieldsRef.current && process.env.NODE_ENV === 'production' && forEach$2(_context8 = values$5(fieldsRef.current)).call(_context8, function (field) {
5071
5073
  return removeFieldEventListenerAndRef(field, true);
5072
5074
  });
5073
5075
  };
@@ -5101,7 +5103,8 @@ function useForm(_a) {
5101
5103
  formState: formState,
5102
5104
  mode: {
5103
5105
  isOnBlur: isOnBlur,
5104
- isOnSubmit: isOnSubmit
5106
+ isOnSubmit: isOnSubmit,
5107
+ isOnChange: isOnChange
5105
5108
  },
5106
5109
  reValidateMode: {
5107
5110
  isReValidateOnBlur: isReValidateOnBlur,
@@ -5149,14 +5152,7 @@ function useForm(_a) {
5149
5152
 
5150
5153
  var FormGlobalContext = React.createContext(null);
5151
5154
  function useFormContext() {
5152
- var context = React.useContext(FormGlobalContext);
5153
-
5154
- if (isNullOrUndefined(context)) {
5155
- // eslint-disable-next-line no-console
5156
- console.warn('Missing FormContext');
5157
- }
5158
-
5159
- return context;
5155
+ return React.useContext(FormGlobalContext);
5160
5156
  }
5161
5157
  function FormContext(_a) {
5162
5158
  var children = _a.children,
@@ -5431,23 +5427,21 @@ var useFieldArray = function (_a) {
5431
5427
 
5432
5428
  if (isArray$4(currentFieldsValue)) {
5433
5429
  for (var i = 0; i < currentFieldsValue.length; i++) {
5434
- fields[i] = __assign(__assign({}, fields[i]), currentFieldsValue[i]);
5430
+ allFields.current[i] = __assign(__assign({}, allFields.current[i]), currentFieldsValue[i]);
5435
5431
  }
5436
5432
  }
5437
5433
  };
5438
5434
 
5439
5435
  var append = function (value) {
5440
- mapCurrentFieldsValueWithState();
5441
-
5442
5436
  if (readFormStateRef.current.dirty) {
5443
5437
  isDirtyRef.current = true;
5438
+ reRender();
5444
5439
  }
5445
5440
 
5446
5441
  commonTasks(__spread(allFields.current, isArray$4(value) ? appendValueWithKey(value) : [appendId(value, keyName)]));
5447
5442
  };
5448
5443
 
5449
5444
  var prepend = function (value) {
5450
- mapCurrentFieldsValueWithState();
5451
5445
  resetFields();
5452
5446
  commonTasks(prependAt(allFields.current, isArray$4(value) ? appendValueWithKey(value) : [appendId(value, keyName)]));
5453
5447
 
@@ -5457,10 +5451,13 @@ var useFieldArray = function (_a) {
5457
5451
 
5458
5452
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
5459
5453
  touchedFieldsRef.current[name] = prependAt(touchedFieldsRef.current[name], fillEmptyArray(value));
5454
+ reRender();
5460
5455
  }
5461
5456
  };
5462
5457
 
5463
5458
  var remove = function (index) {
5459
+ var shouldRender = false;
5460
+
5464
5461
  if (!isUndefined(index)) {
5465
5462
  mapCurrentFieldsValueWithState();
5466
5463
  }
@@ -5480,6 +5477,7 @@ var useFieldArray = function (_a) {
5480
5477
 
5481
5478
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
5482
5479
  touchedFieldsRef.current[name] = removeArrayAt(touchedFieldsRef.current[name], index);
5480
+ shouldRender = true;
5483
5481
  }
5484
5482
 
5485
5483
  if (readFormStateRef.current.dirty) {
@@ -5490,6 +5488,8 @@ var useFieldArray = function (_a) {
5490
5488
  dirtyFieldsRef.current.delete(dirtyField);
5491
5489
  }
5492
5490
  });
5491
+
5492
+ shouldRender = true;
5493
5493
  }
5494
5494
 
5495
5495
  if (readFormStateRef.current.isValid && !validateSchemaIsValid) {
@@ -5531,6 +5531,10 @@ var useFieldArray = function (_a) {
5531
5531
  }
5532
5532
  }
5533
5533
 
5534
+ shouldRender = true;
5535
+ }
5536
+
5537
+ if (shouldRender) {
5534
5538
  reRender();
5535
5539
  }
5536
5540
  };
@@ -5546,6 +5550,7 @@ var useFieldArray = function (_a) {
5546
5550
 
5547
5551
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
5548
5552
  touchedFieldsRef.current[name] = insertAt(touchedFieldsRef.current[name], index, fillEmptyArray(value));
5553
+ reRender();
5549
5554
  }
5550
5555
  };
5551
5556
 
@@ -5563,6 +5568,7 @@ var useFieldArray = function (_a) {
5563
5568
 
5564
5569
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
5565
5570
  swapArrayAt(touchedFieldsRef.current[name], indexA, indexB);
5571
+ reRender();
5566
5572
  }
5567
5573
  };
5568
5574
 
@@ -5580,6 +5586,7 @@ var useFieldArray = function (_a) {
5580
5586
 
5581
5587
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
5582
5588
  moveArrayAt(touchedFieldsRef.current[name], from, to);
5589
+ reRender();
5583
5590
  }
5584
5591
  };
5585
5592
 
@@ -5668,6 +5675,7 @@ var Controller = function (_a) {
5668
5675
  _j = _h.mode,
5669
5676
  isOnSubmit = _j.isOnSubmit,
5670
5677
  isOnBlur = _j.isOnBlur,
5678
+ isOnChange = _j.isOnChange,
5671
5679
  _k = _h.reValidateMode,
5672
5680
  isReValidateOnBlur = _k.isReValidateOnBlur,
5673
5681
  isReValidateOnSubmit = _k.isReValidateOnSubmit,
@@ -5687,6 +5695,7 @@ var Controller = function (_a) {
5687
5695
  hasError: !!get$1(errorsRef.current, name),
5688
5696
  isOnBlur: isOnBlur,
5689
5697
  isOnSubmit: isOnSubmit,
5698
+ isOnChange: isOnChange,
5690
5699
  isReValidateOnBlur: isReValidateOnBlur,
5691
5700
  isReValidateOnSubmit: isReValidateOnSubmit,
5692
5701
  isSubmitted: isSubmitted
@@ -625,7 +625,8 @@ var assignWatchFields = (fieldValues, fieldName, watchFields, combinedDefaultVal
625
625
  : value;
626
626
  };
627
627
 
628
- var skipValidation = ({ hasError, isBlurEvent, isOnSubmit, isReValidateOnSubmit, isOnBlur, isReValidateOnBlur, isSubmitted, }) => (isOnSubmit && isReValidateOnSubmit) ||
628
+ var skipValidation = ({ isOnChange, hasError, isBlurEvent, isOnSubmit, isReValidateOnSubmit, isOnBlur, isReValidateOnBlur, isSubmitted, }) => (isOnChange && isBlurEvent) ||
629
+ (isOnSubmit && isReValidateOnSubmit) ||
629
630
  (isOnSubmit && !isSubmitted) ||
630
631
  (isOnBlur && !isBlurEvent && !hasError) ||
631
632
  (isReValidateOnBlur && !isBlurEvent && hasError) ||
@@ -714,7 +715,7 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
714
715
  const validationContextRef = useRef(validationContext);
715
716
  const fieldArrayNamesRef = useRef(new Set());
716
717
  const [, render] = useState();
717
- const { isOnBlur, isOnSubmit } = useRef(modeChecker(mode)).current;
718
+ const { isOnBlur, isOnSubmit, isOnChange } = useRef(modeChecker(mode)).current;
718
719
  const isWindowUndefined = typeof window === UNDEFINED;
719
720
  const shouldValidateCallback = !!(validationSchema || validationResolver);
720
721
  const isWeb = typeof document !== UNDEFINED &&
@@ -910,14 +911,9 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
910
911
  reRender,
911
912
  shouldValidateCallback,
912
913
  ]);
913
- const isFieldWatched = (name) => {
914
- const preFixName = (name.match(/\w+/) || [])[0];
915
- return (isWatchAllRef.current ||
916
- watchFieldsRef.current.has(name) ||
917
- (watchFieldsRef.current.has(preFixName) &&
918
- !isKey(name) &&
919
- fieldArrayNamesRef.current.has(preFixName)));
920
- };
914
+ const isFieldWatched = (name) => isWatchAllRef.current ||
915
+ watchFieldsRef.current.has(name) ||
916
+ watchFieldsRef.current.has((name.match(/\w+/) || [])[0]);
921
917
  function setValue(names, valueOrShouldValidate, shouldValidate) {
922
918
  let shouldRender = false;
923
919
  const isMultiple = isArray(names);
@@ -954,6 +950,7 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
954
950
  const isBlurEvent = type === EVENTS.BLUR;
955
951
  const shouldSkipValidation = skipValidation({
956
952
  hasError: !!currentError,
953
+ isOnChange,
957
954
  isBlurEvent,
958
955
  isOnSubmit,
959
956
  isReValidateOnSubmit,
@@ -1237,19 +1234,19 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
1237
1234
  const resolvedPrevious = await previous;
1238
1235
  const { ref, ref: { name }, } = field;
1239
1236
  if (!fields[name]) {
1240
- return Promise.resolve(resolvedPrevious);
1237
+ return resolvedPrevious;
1241
1238
  }
1242
1239
  const fieldError = await validateField(fieldsRef, validateAllFieldCriteria, field);
1243
1240
  if (fieldError[name]) {
1244
1241
  set(resolvedPrevious.errors, name, fieldError[name]);
1245
1242
  validFieldsRef.current.delete(name);
1246
- return Promise.resolve(resolvedPrevious);
1243
+ return resolvedPrevious;
1247
1244
  }
1248
1245
  if (fieldsWithValidationRef.current.has(name)) {
1249
1246
  validFieldsRef.current.add(name);
1250
1247
  }
1251
1248
  resolvedPrevious.values[name] = getFieldValue(fields, ref);
1252
- return Promise.resolve(resolvedPrevious);
1249
+ return resolvedPrevious;
1253
1250
  }, Promise.resolve({
1254
1251
  errors: {},
1255
1252
  values: {},
@@ -1341,6 +1338,7 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
1341
1338
  useEffect(() => () => {
1342
1339
  isUnMount.current = true;
1343
1340
  fieldsRef.current &&
1341
+ process.env.NODE_ENV === 'production' &&
1344
1342
  Object.values(fieldsRef.current).forEach((field) => removeFieldEventListenerAndRef(field, true));
1345
1343
  }, [removeFieldEventListenerAndRef]);
1346
1344
  if (!shouldValidateCallback) {
@@ -1368,6 +1366,7 @@ function useForm({ mode = VALIDATION_MODE.onSubmit, reValidateMode = VALIDATION_
1368
1366
  triggerValidation }, (shouldValidateCallback ? { validateSchemaIsValid } : {})), { formState, mode: {
1369
1367
  isOnBlur,
1370
1368
  isOnSubmit,
1369
+ isOnChange,
1371
1370
  }, reValidateMode: {
1372
1371
  isReValidateOnBlur,
1373
1372
  isReValidateOnSubmit,
@@ -1447,12 +1446,7 @@ function __rest(s, e) {
1447
1446
 
1448
1447
  const FormGlobalContext = React.createContext(null);
1449
1448
  function useFormContext() {
1450
- const context = React.useContext(FormGlobalContext);
1451
- if (isNullOrUndefined(context)) {
1452
- // eslint-disable-next-line no-console
1453
- console.warn('Missing FormContext');
1454
- }
1455
- return context;
1449
+ return React.useContext(FormGlobalContext);
1456
1450
  }
1457
1451
  function FormContext(_a) {
1458
1452
  var { children, formState, errors } = _a, restMethods = __rest(_a, ["children", "formState", "errors"]);
@@ -1540,14 +1534,14 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1540
1534
  const currentFieldsValue = getValues({ nest: true })[name];
1541
1535
  if (isArray(currentFieldsValue)) {
1542
1536
  for (let i = 0; i < currentFieldsValue.length; i++) {
1543
- fields[i] = Object.assign(Object.assign({}, fields[i]), currentFieldsValue[i]);
1537
+ allFields.current[i] = Object.assign(Object.assign({}, allFields.current[i]), currentFieldsValue[i]);
1544
1538
  }
1545
1539
  }
1546
1540
  };
1547
1541
  const append = (value) => {
1548
- mapCurrentFieldsValueWithState();
1549
1542
  if (readFormStateRef.current.dirty) {
1550
1543
  isDirtyRef.current = true;
1544
+ reRender();
1551
1545
  }
1552
1546
  commonTasks([
1553
1547
  ...allFields.current,
@@ -1557,7 +1551,6 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1557
1551
  ]);
1558
1552
  };
1559
1553
  const prepend = (value) => {
1560
- mapCurrentFieldsValueWithState();
1561
1554
  resetFields();
1562
1555
  commonTasks(prependAt(allFields.current, isArray(value) ? appendValueWithKey(value) : [appendId(value, keyName)]));
1563
1556
  if (errorsRef.current[name]) {
@@ -1565,9 +1558,11 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1565
1558
  }
1566
1559
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1567
1560
  touchedFieldsRef.current[name] = prependAt(touchedFieldsRef.current[name], fillEmptyArray(value));
1561
+ reRender();
1568
1562
  }
1569
1563
  };
1570
1564
  const remove = (index) => {
1565
+ let shouldRender = false;
1571
1566
  if (!isUndefined(index)) {
1572
1567
  mapCurrentFieldsValueWithState();
1573
1568
  }
@@ -1581,6 +1576,7 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1581
1576
  }
1582
1577
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1583
1578
  touchedFieldsRef.current[name] = removeArrayAt(touchedFieldsRef.current[name], index);
1579
+ shouldRender = true;
1584
1580
  }
1585
1581
  if (readFormStateRef.current.dirty) {
1586
1582
  dirtyFieldsRef.current.forEach(dirtyField => {
@@ -1588,6 +1584,7 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1588
1584
  dirtyFieldsRef.current.delete(dirtyField);
1589
1585
  }
1590
1586
  });
1587
+ shouldRender = true;
1591
1588
  }
1592
1589
  if (readFormStateRef.current.isValid && !validateSchemaIsValid) {
1593
1590
  let fieldIndex = -1;
@@ -1619,6 +1616,9 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1619
1616
  }
1620
1617
  }
1621
1618
  }
1619
+ shouldRender = true;
1620
+ }
1621
+ if (shouldRender) {
1622
1622
  reRender();
1623
1623
  }
1624
1624
  };
@@ -1631,6 +1631,7 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1631
1631
  }
1632
1632
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1633
1633
  touchedFieldsRef.current[name] = insertAt(touchedFieldsRef.current[name], index, fillEmptyArray(value));
1634
+ reRender();
1634
1635
  }
1635
1636
  };
1636
1637
  const swap = (indexA, indexB) => {
@@ -1645,6 +1646,7 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1645
1646
  }
1646
1647
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1647
1648
  swapArrayAt(touchedFieldsRef.current[name], indexA, indexB);
1649
+ reRender();
1648
1650
  }
1649
1651
  };
1650
1652
  const move = (from, to) => {
@@ -1659,6 +1661,7 @@ const useFieldArray = ({ control, name, keyName = 'id', }) => {
1659
1661
  }
1660
1662
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1661
1663
  moveArrayAt(touchedFieldsRef.current[name], from, to);
1664
+ reRender();
1662
1665
  }
1663
1666
  };
1664
1667
  const reset = () => {
@@ -1701,7 +1704,7 @@ var getInputValue = (event, isCheckboxInput) => isPrimitive(event) ||
1701
1704
  const Controller = (_a) => {
1702
1705
  var { name, rules, as: InnerComponent, onBlur, onChange, onChangeName = VALIDATION_MODE.onChange, onBlurName = VALIDATION_MODE.onBlur, valueName, defaultValue, control } = _a, rest = __rest(_a, ["name", "rules", "as", "onBlur", "onChange", "onChangeName", "onBlurName", "valueName", "defaultValue", "control"]);
1703
1706
  const methods = useFormContext();
1704
- const { defaultValuesRef, setValue, register, unregister, errorsRef, removeFieldEventListener, triggerValidation, mode: { isOnSubmit, isOnBlur }, reValidateMode: { isReValidateOnBlur, isReValidateOnSubmit }, formState: { isSubmitted }, fieldsRef, fieldArrayNamesRef, } = control || methods.control;
1707
+ const { defaultValuesRef, setValue, register, unregister, errorsRef, removeFieldEventListener, triggerValidation, mode: { isOnSubmit, isOnBlur, isOnChange }, reValidateMode: { isReValidateOnBlur, isReValidateOnSubmit }, formState: { isSubmitted }, fieldsRef, fieldArrayNamesRef, } = control || methods.control;
1705
1708
  const [value, setInputStateValue] = React.useState(isUndefined(defaultValue)
1706
1709
  ? get(defaultValuesRef.current, name)
1707
1710
  : defaultValue);
@@ -1711,6 +1714,7 @@ const Controller = (_a) => {
1711
1714
  hasError: !!get(errorsRef.current, name),
1712
1715
  isOnBlur,
1713
1716
  isOnSubmit,
1717
+ isOnChange,
1714
1718
  isReValidateOnBlur,
1715
1719
  isReValidateOnSubmit,
1716
1720
  isSubmitted,
@@ -1 +1 @@
1
- import*as e from"react";import{createContext as r,useContext as t,createElement as n,useState as s,useRef as c,useEffect as u,isValidElement as i,cloneElement as a,Fragment as o}from"react";var l=e=>void 0===e,f=e=>null===e||l(e),d=e=>Array.isArray(e);const g=e=>"object"==typeof e;var m=e=>!f(e)&&!d(e)&&g(e),h=e=>m(e)&&e.nodeType===Node.ELEMENT_NODE;const v={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit"},b="undefined",p={BLUR:"blur",CHANGE:"change",INPUT:"input"},y="max",O="min",j="maxLength",S="minLength",w="pattern",x="required",R="validate",V=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,E=/^\w*$/,B=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,N=/\\(\\)?/g;var F=e=>!d(e)&&(E.test(e)||!V.test(e)),C=e=>{const r=[];return e.replace(B,(e,t,n,s)=>{r.push(n?s.replace(N,"$1"):t||e)}),r};function k(e,r,t){let n=-1;const s=F(r)?[r]:C(r),c=s.length,u=c-1;for(;++n<c;){const r=s[n];let c=t;if(n!==u){const t=e[r];c=m(t)||d(t)?t:isNaN(s[n+1])?{}:[]}e[r]=c,e=e[r]}return e}var L=e=>Object.entries(e).reduce((e,[r,t])=>F(r)?Object.assign(Object.assign({},e),{[r]:t}):(k(e,r,t),e),{}),$=(e,r,t)=>{const n=r.split(/[,[\].]+?/).filter(Boolean).reduce((e,r)=>f(e)?e:e[r],e);return l(n)||n===e?e[r]||t:n},A=(e,r)=>{for(const t in e)if($(r,t)){const r=e[t];if(r){if(h(r.ref)&&r.ref.focus){r.ref.focus();break}if(r.options){r.options[0].ref.focus();break}}}},P=(e,r)=>{h(e)&&e.removeEventListener&&(e.removeEventListener(p.INPUT,r),e.removeEventListener(p.CHANGE,r),e.removeEventListener(p.BLUR,r))},M=e=>!!e&&"radio"===e.type,W=e=>!!e&&"checkbox"===e.type;function D(e){return!e||e instanceof HTMLElement&&e.nodeType!==Node.DOCUMENT_NODE&&D(e.parentNode)}var I=e=>m(e)&&!Object.keys(e).length;function T(e){return d(e)?e:C(e)}function U(e,r){return 1==r.length?e:function(e,r){const t=F(r)?[r]:T(r),n=r.length;let s=0;for(;s<n;)e=l(e)?s++:e[t[s++]];return s==n?e:void 0}(e,function(e,r,t){let n=-1,s=e.length;r<0&&(r=-r>s?0:s+r),(t=t>s?s:t)<0&&(t+=s),s=r>t?0:t-r;const c=Array(s);for(;++n<s;)c[n]=e[n+r];return c}(r,0,-1))}function z(e,r){return r.forEach(r=>{!function(e,r){const t=F(r)?[r]:T(r),n=U(e,t),s=t[t.length-1],c=!(null!=n)||delete n[s];let u=void 0;for(let r=0;r<t.slice(0,-1).length;r++){let n=-1,s=void 0;const c=t.slice(0,-(r+1)),i=c.length-1;for(r>0&&(u=e);++n<c.length;){const r=c[n];s=s?s[r]:e[r],i===n&&(m(s)&&I(s)?u?delete u[r]:delete e[r]:d(s)&&!s.filter(e=>m(e)&&!I(e)).length&&u&&delete u[r]),u=s}}}(e,r)}),e}const H={isValid:!1,value:""};var G=e=>d(e)?e.reduce((e,{ref:{checked:r,value:t}})=>r?{isValid:!0,value:t}:e,H):H,q=e=>[...e].filter(({selected:e})=>e).map(({value:e})=>e),_=e=>!!e&&"file"===e.type,J=e=>!!e&&"select-multiple"===e.type,K=e=>""===e;const Q={value:!1,isValid:!1},X={value:!0,isValid:!0};var Y=e=>{if(d(e)){if(e.length>1){const r=e.filter(({ref:{checked:e}})=>e).map(({ref:{value:e}})=>e);return{value:r,isValid:!!r.length}}const{checked:r,value:t,attributes:n}=e[0].ref;return r?n&&!l(n.value)?l(t)||K(t)?X:{value:t,isValid:!0}:X:Q}return Q};function Z(e,r){const{name:t,value:n}=r,s=e[t];return _(r)?r.files:M(r)?s?G(s.options).value:"":J(r)?q(r.options):W(r)?!!s&&Y(s.options).value:n}var ee=e=>"string"==typeof e,re=(e,r)=>{const t={},n=ee(r),s=d(r),c=r&&r.nest;for(const u in e)(l(r)||c||n&&u.startsWith(r)||s&&r.find(e=>u.startsWith(e)))&&(t[u]=Z(e,e[u].ref));return t},te=(e,{type:r,types:t,message:n})=>m(e)&&e.type===r&&e.message===n&&((e={},r={})=>Object.entries(e).reduce((e,[t,n])=>!!e&&r[t]&&r[t]===n,!0))(e.types,t);var ne=e=>e instanceof RegExp,se=e=>{const r=m(e)&&!ne(e);return{value:r?e.value:e,message:r?e.message:""}},ce=e=>"function"==typeof e,ue=e=>"boolean"==typeof e;function ie(e,r,t="validate"){const n=ee(e);if(n||ue(e)&&!e){return{type:t,message:n?e:"",ref:r}}}var ae=(e,r,t,n,s)=>{if(!r)return{};const c=t[e];return Object.assign(Object.assign({},c),{types:Object.assign(Object.assign({},c&&c.types?c.types:{}),{[n]:s||!0})})},oe=async(e,r,{ref:t,ref:{type:n,value:s,name:c},options:u,required:i,maxLength:a,minLength:o,min:l,max:d,pattern:g,validate:h})=>{const v=e.current,b={},p=M(t),V=W(t),E=p||V,B=K(s),N=ae.bind(null,c,r,b),F=(e,n,s,u=j,i=S)=>{const a=e?n:s;if(b[c]=Object.assign({type:e?u:i,message:a,ref:t},N(e?u:i,a)),!r)return b};if(i&&(!p&&!V&&(B||f(s))||ue(s)&&!s||V&&!Y(u).isValid||p&&!G(u).isValid)){const{value:e,message:n}=ee(i)?{value:!!i,message:i}:se(i);if(e&&(b[c]=Object.assign({type:x,message:n,ref:E?v[c].options[0].ref:t},N(x,n)),!r))return b}if(!f(l)||!f(d)){let e,c;const{value:u,message:i}=se(d),{value:a,message:o}=se(l);if("number"===n||!n&&!isNaN(s)){const r=t.valueAsNumber||parseFloat(s);f(u)||(e=r>u),f(a)||(c=r<a)}else{const r=t.valueAsDate||new Date(s);ee(u)&&(e=r>new Date(u)),ee(a)&&(c=r<new Date(a))}if((e||c)&&(F(!!e,i,o,y,O),!r))return b}if(ee(s)&&!B&&(a||o)){const{value:e,message:t}=se(a),{value:n,message:c}=se(o),u=s.toString().length,i=a&&u>e,l=o&&u<n;if((i||l)&&(F(!!i,t,c),!r))return b}if(g&&!B){const{value:e,message:n}=se(g);if(ne(e)&&!e.test(s)&&(b[c]=Object.assign({type:w,message:n,ref:t},N(w,n)),!r))return b}if(h){const e=Z(v,t),n=E&&u?u[0].ref:t;if(ce(h)){const t=ie(await h(e),n);if(t&&(b[c]=Object.assign(Object.assign({},t),N(R,t.message)),!r))return b}else if(m(h)){const t=Object.entries(h),s=await new Promise(s=>{t.reduce(async(u,[i,a],o)=>{if(!I(await u)&&!r||!ce(a))return s(u);let l;const f=ie(await a(e),n,i);return f?(l=Object.assign(Object.assign({},f),N(i,f.message)),r&&(b[c]=l)):l=u,t.length-1===o?s(l):l},{})});if(!I(s)&&(b[c]=Object.assign({ref:n},s),!r))return b}}return b};const le=(e,r)=>d(e.inner)?e.inner.reduce((e,{path:t,message:n,type:s})=>Object.assign(Object.assign({},e),e[t]&&r?{[t]:ae(t,r,e,s,n)}:{[t]:e[t]||Object.assign({message:n,type:s},r?{types:{[s]:n||!0}}:{})}),{}):{[e.path]:{message:e.message,type:e.type}};async function fe(e,r,t,n,s){if(n)return n(t,s);try{return{values:await e.validate(t,{abortEarly:!1,context:s}),errors:{}}}catch(e){return{values:{},errors:L(le(e,r))}}}var de=(e,r,t)=>l(e[r])?$(e,r,t):e[r];var ge=e=>f(e)||!g(e);const me=(e,r)=>{const t=(r,t,n)=>{const s=n?`${e}.${t}`:`${e}[${t}]`;return ge(r)?s:me(s,r)};return d(r)?r.map((e,r)=>t(e,r)):Object.entries(r).map(([e,r])=>t(r,e,!0))};var he=(e,r)=>(function e(r){return r.reduce((r,t)=>r.concat(d(t)?e(t):t),[])})(me(e,r)),ve=(e,r,t,n,s)=>{let c;return t.add(r),I(e)?c=s||void 0:l(e[r])?(c=$(L(e),r),d(s)&&d(c)&&c.length!==s.length&&(c=s),l(c)||he(r,c).forEach(e=>t.add(e))):(c=e[r],t.add(r)),l(c)?m(n)?de(n,r):n:c},be=({hasError:e,isBlurEvent:r,isOnSubmit:t,isReValidateOnSubmit:n,isOnBlur:s,isReValidateOnBlur:c,isSubmitted:u})=>t&&n||t&&!u||s&&!r&&!e||c&&!r&&e||n&&u,pe=(e,r)=>{const t=L(re(e));return r?$(t,r,t):t};function ye(e,r){let t=!1;if(!d(e)||!d(r)||e.length!==r.length)return!0;for(let n=0;n<e.length&&!t;n++){const s=e[n],c=r[n];if(l(c)||Object.keys(s).length!==Object.keys(c).length){t=!0;break}for(const e in s)if(s[e]!==c[e]){t=!0;break}}return t}const Oe=(e,r)=>e.startsWith(`${r}[`);var je=(e,r)=>[...e].reduce((e,t)=>!!Oe(r,t)||e,!1),Se=e=>typeof FileList!==b&&e instanceof FileList;var we=e=>({isOnSubmit:!e||e===v.onSubmit,isOnBlur:e===v.onBlur,isOnChange:e===v.onChange});const{useRef:xe,useState:Re,useCallback:Ve,useEffect:Ee}=e;function Be({mode:e=v.onSubmit,reValidateMode:r=v.onChange,validationSchema:t,validationResolver:n,validationContext:s,defaultValues:c={},submitFocusError:u=!0,validateCriteriaMode:i}={}){const a=xe({}),o="all"===i,g=xe({}),y=xe({}),O=xe({}),j=xe(new Set),S=xe(new Set),w=xe(new Set),x=xe(new Set),R=xe(!0),V=xe({}),E=xe(c),B=xe(!1),N=xe(!1),C=xe(!1),T=xe(!1),U=xe(0),H=xe(!1),G=xe(),q=xe({}),Q=xe(s),X=xe(new Set),[,Y]=Re(),{isOnBlur:ne,isOnSubmit:se}=xe(we(e)).current,ie=typeof window===b,ae=!(!t&&!n),le=typeof document!==b&&!ie&&!l(window.HTMLElement),me=le&&"Proxy"in window,he=xe({dirty:!me,dirtyFields:!me,isSubmitted:se,submitCount:!me,touched:!me,isSubmitting:!me,isValid:!me}),{isOnBlur:Oe,isOnSubmit:Be}=xe(we(r)).current,Ne=Ve(()=>{B.current||Y({})},[]),Fe=Ve((e,r,t,n)=>{let s=t||function({errors:e,name:r,error:t,validFields:n,fieldsWithValidation:s}){const c=I(t),u=I(e),i=$(t,r),a=$(e,r);return!(c&&n.has(r)||a&&a.isManual)&&(!!(u!==c||!u&&!a||c&&s.has(r)&&!n.has(r))||i&&!te(a,i))}({errors:g.current,error:r,name:e,validFields:x.current,fieldsWithValidation:w.current});if(I(r)?((w.current.has(e)||ae)&&(x.current.add(e),s=s||$(g.current,e)),g.current=z(g.current,[e])):(x.current.delete(e),s=s||!$(g.current,e),k(g.current,e,r[e])),s&&!n)return Ne(),!0},[Ne,ae]),Ce=Ve((e,r)=>{const t=e.ref,n=e.options,{type:s}=t,c=le&&h(t)&&f(r)?"":r;return M(t)&&n?n.forEach(({ref:e})=>e.checked=e.value===c):_(t)?K(c)||Se(c)?t.files=c:t.value=c:J(t)?[...t.options].forEach(e=>e.selected=c.includes(e.value)):W(t)&&n?n.length>1?n.forEach(({ref:e})=>e.checked=c.includes(e.value)):n[0].ref.checked=!!c:t.value=c,!!s},[le]),ke=e=>{if(!a.current[e]||!he.current.dirty&&!he.current.dirtyFields)return!1;const r=je(X.current,e),t=S.current.size;let n=V.current[e]!==Z(a.current,a.current[e].ref);if(r){const r=e.substring(0,e.indexOf("["));n=ye(pe(a.current,r),$(E.current,r))}const s=(r?T.current:S.current.has(e))!==n;return n?S.current.add(e):S.current.delete(e),T.current=r?n:!!S.current.size,he.current.dirty?s:t!==S.current.size},Le=Ve(e=>{if(ke(e)||!$(y.current,e)&&he.current.touched)return!!k(y.current,e,!0)},[]),$e=Ve((e,r,t)=>{const n=d(r);for(const s in r){const c=`${t||e}${n?`[${s}]`:`.${s}`}`;m(r[s])&&$e(e,r[s],c);const u=a.current[c];u&&(Ce(u,r[s]),Le(c))}},[Ce,Le]),Ae=Ve((e,r)=>{const t=a.current[e];if(t){Ce(t,r);const n=Le(e);if(ue(n))return n}else ge(r)||$e(e,r)},[Le,Ce,$e]),Pe=Ve(async(e,r)=>{const t=a.current[e];if(!t)return!1;const n=await oe(a,o,t);return Fe(e,n,!1,r),I(n)},[Fe,o]),Me=Ve(async e=>{const{errors:r}=await fe(t,o,pe(a.current),n,Q.current),s=R.current;return R.current=I(r),d(e)?(e.forEach(e=>{const t=$(r,e);t?k(g.current,e,t):z(g.current,[e])}),Ne()):Fe(e,$(r,e)?{[e]:$(r,e)}:{},s!==R.current),I(g.current)},[Ne,Fe,o,n,t]),We=Ve(async e=>{const r=e||Object.keys(a.current);if(ae)return Me(r);if(d(r)){const e=await Promise.all(r.map(async e=>await Pe(e,!0)));return Ne(),e.every(Boolean)}return await Pe(r)},[Me,Pe,Ne,ae]),De=e=>{const r=(e.match(/\w+/)||[])[0];return N.current||j.current.has(e)||j.current.has(r)&&!F(e)&&X.current.has(r)};function Ie(e,r,t){let n=!1;const s=d(e);(s?e:[e]).forEach(e=>{const t=ee(e);n=!(!Ae(t?e:Object.keys(e)[0],t?r:Object.values(e)[0])&&!s)||De(e)}),(n||s)&&Ne(),(t||s&&r)&&We(s?void 0:e)}G.current=G.current?G.current:async({type:e,target:r})=>{const s=r?r.name:"",c=a.current,u=g.current,i=c[s],l=$(u,s);let f;if(!i)return;const d=e===p.BLUR,m=be({hasError:!!l,isBlurEvent:d,isOnSubmit:se,isReValidateOnSubmit:Be,isOnBlur:ne,isReValidateOnBlur:Oe,isSubmitted:C.current}),h=ke(s);let v=De(s)||h;if(d&&!$(y.current,s)&&he.current.touched&&(k(y.current,s,!0),v=!0),m)return v&&Ne();if(ae){const{errors:e}=await fe(t,o,pe(c),n,Q.current),r=R.current;R.current=I(e),f=$(e,s)?{[s]:$(e,s)}:{},r!==R.current&&(v=!0)}else f=await oe(a,o,i);!Fe(s,f)&&v&&Ne()};const Te=Ve((e={})=>{const r=I(E.current)?re(a.current):E.current;fe(t,o,L(Object.assign(Object.assign({},r),e)),n,Q.current).then(({errors:e})=>{const r=R.current;R.current=I(e),r!==R.current&&Ne()})},[Ne,o,n]),Ue=(e,r)=>{!l(G.current)&&e&&function(e,r,t,n){if(!t)return;const{ref:s,ref:{name:c,type:u},mutationWatcher:i}=t;if(!u)return void delete e[c];const a=e[c];if((M(s)||W(s))&&a){const{options:t}=a;d(t)&&t.length?(t.forEach(({ref:e,mutationWatcher:s},c)=>{(e&&D(e)||n)&&(P(e,r),s&&s.disconnect(),z(t,[`[${c}]`]))}),t&&!t.filter(Boolean).length&&delete e[c]):delete e[c]}else(D(s)||n)&&(P(s,r),i&&i.disconnect(),delete e[c])}(a.current,G.current,e,r)},ze=Ve((e,r)=>{if(!e||e&&je(X.current,e.ref.name)&&!r)return;Ue(e,r);const{name:t}=e.ref;g.current=z(g.current,[t]),y.current=z(y.current,[t]),V.current=z(V.current,[t]),[S,w,x,j].forEach(e=>e.current.delete(t)),(he.current.isValid||he.current.touched)&&(Ne(),ae&&Te())},[Ne,ae,Te]);const He=({name:e,type:r,types:t,message:n,preventRender:s})=>{const c=a.current[e];te(g.current[e],{type:r,message:n,types:t})||(k(g.current,e,{type:r,types:t,message:n,ref:c?c.ref:{},isManual:!0}),s||Ne())};function Ge(e){I(a.current)||(d(e)?e:[e]).forEach(e=>ze(a.current[e],!0))}function qe(e,r={}){if(!e.name)return console.warn("Missing name @",e);const{name:t,type:n,value:s}=e,c=Object.assign({ref:e},r),u=a.current,i=M(e)||W(e);let f,g=u[t],m=!0,v=!1;if(i?g&&d(g.options)&&g.options.find(({ref:e})=>s===e.value):g)return void(u[t]=Object.assign(Object.assign({},g),r));if(n){const s=function(e,r){const t=new MutationObserver(()=>{D(e)&&(t.disconnect(),r())});return t.observe(window.document,{childList:!0,subtree:!0}),t}(e,()=>ze(c));g=i?Object.assign({options:[...g&&g.options||[],{ref:e,mutationWatcher:s}],ref:{type:n,name:t}},r):Object.assign(Object.assign({},c),{mutationWatcher:s})}else g=c;if(u[t]=g,I(E.current)||(f=de(E.current,t),m=l(f),v=je(X.current,t),m||v||Ce(g,f)),ae&&!v&&he.current.isValid?Te():I(r)||(w.current.add(t),!se&&he.current.isValid&&oe(a,o,g).then(e=>{const r=R.current;I(e)?x.current.add(t):R.current=!1,r!==R.current&&Ne()})),V.current[t]||v&&m||(V.current[t]=m?Z(u,g.ref):f),!n)return;!function({field:e,handleChange:r,isRadioOrCheckbox:t}){const{ref:n}=e;h(n)&&n.addEventListener&&r&&(n.addEventListener(t?p.CHANGE:p.INPUT,r),n.addEventListener(p.BLUR,r))}({field:i&&g.options?g.options[g.options.length-1]:g,isRadioOrCheckbox:i,handleChange:G.current})}function _e(e,r){if(!ie)if(ee(e))qe({name:e},r);else{if(!(m(e)&&"name"in e))return r=>r&&qe(r,e);qe(e,r)}}const Je=Ve(e=>async r=>{let s,c;r&&(r.preventDefault(),r.persist());const i=a.current;he.current.isSubmitting&&(H.current=!0,Ne());try{if(ae){c=re(i);const{errors:e,values:r}=await fe(t,o,L(c),n,Q.current);g.current=e,s=e,c=r}else{const{errors:e,values:r}=await Object.values(i).reduce(async(e,r)=>{if(!r)return e;const t=await e,{ref:n,ref:{name:s}}=r;if(!i[s])return Promise.resolve(t);const c=await oe(a,o,r);return c[s]?(k(t.errors,s,c[s]),x.current.delete(s),Promise.resolve(t)):(w.current.has(s)&&x.current.add(s),t.values[s]=Z(i,n),Promise.resolve(t))},Promise.resolve({errors:{},values:{}}));s=e,c=r}I(s)?(g.current={},await e(L(c),r)):(u&&le&&A(i,s),g.current=s)}finally{C.current=!0,H.current=!1,U.current=U.current+1,Ne()}},[le,Ne,ae,u,o,n,t]),Ke=e=>{const r=re(a.current),t=I(r)?E.current:r;return e&&e.nest?L(t):t};Ee(()=>()=>{B.current=!0,a.current&&Object.values(a.current).forEach(e=>ze(e,!0))},[ze]),ae||(R.current=x.current.size>=w.current.size&&I(g.current));const Qe={dirty:T.current,dirtyFields:S.current,isSubmitted:C.current,submitCount:U.current,touched:y.current,isSubmitting:H.current,isValid:se?C.current&&I(g.current):R.current};return{watch:function(e,r){const t=l(r)?l(E.current)?{}:E.current:r,n=re(a.current,e),s=j.current;if(ee(e))return ve(n,e,s,t,X.current.has(e)?O.current[e]:void 0);if(d(e))return e.reduce((e,r)=>Object.assign(Object.assign({},e),{[r]:ve(n,r,s,t)}),{});N.current=!0;const c=!I(n)&&n||r||E.current;return e&&e.nest?L(c):c},control:Object.assign(Object.assign({register:_e,unregister:Ge,removeFieldEventListener:Ue,getValues:Ke,setValue:Ie,reRender:Ne,triggerValidation:We},ae?{validateSchemaIsValid:Te}:{}),{formState:Qe,mode:{isOnBlur:ne,isOnSubmit:se},reValidateMode:{isReValidateOnBlur:Oe,isReValidateOnSubmit:Be},errorsRef:g,touchedFieldsRef:y,fieldsRef:a,resetFieldArrayFunctionRef:q,validFieldsRef:x,dirtyFieldsRef:S,fieldsWithValidationRef:w,watchFieldArrayRef:O,fieldArrayNamesRef:X,isDirtyRef:T,readFormStateRef:he,defaultValuesRef:E}),handleSubmit:Je,setValue:Ve(Ie,[Ne,Ae,We]),triggerValidation:We,getValues:Ve(Ke,[]),reset:Ve((e,r={})=>{if(le)for(const e of Object.values(a.current))if(e&&h(e.ref)&&e.ref.closest)try{e.ref.closest("form").reset();break}catch(e){}e&&(E.current=e),Object.values(q.current).forEach(e=>ce(e)&&e()),(({errors:e,dirty:r,isSubmitted:t,touched:n,isValid:s,submitCount:c})=>{a.current={},e||(g.current={}),n||(y.current={}),s||(x.current=new Set,w.current=new Set,R.current=!0),r||(S.current=new Set,T.current=!1),t||(C.current=!1),c||(U.current=0),V.current={},j.current=new Set,N.current=!1})(r),Ne()},[]),register:Ve(_e,[E.current,V.current,O.current]),unregister:Ve(Ge,[]),clearError:Ve(function(e){l(e)?g.current={}:z(g.current,d(e)?e:[e]),Ne()},[]),setError:Ve(function(e,r="",t){ee(e)?He(Object.assign({name:e},m(r)?{types:r,type:""}:{type:r,message:t})):d(e)&&(e.forEach(e=>He(Object.assign(Object.assign({},e),{preventRender:!0}))),Ne())},[]),errors:g.current,formState:me?new Proxy(Qe,{get:(e,r)=>r in e?(he.current[r]=!0,e[r]):{}}):Qe}}function Ne(e,r){var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&r.indexOf(n)<0&&(t[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(n=Object.getOwnPropertySymbols(e);s<n.length;s++)r.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(t[n[s]]=e[n[s]])}return t}const Fe=r(null);function Ce(){const e=t(Fe);return f(e)&&console.warn("Missing FormContext"),e}function ke(e){var{children:r,formState:t,errors:s}=e,c=Ne(e,["children","formState","errors"]);return n(Fe.Provider,{value:Object.assign(Object.assign({},c),{formState:t,errors:s})},r)}var Le=()=>{const e=typeof performance===b?Date.now():1e3*performance.now();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){const t=(16*Math.random()+e)%16|0;return("x"==r?t:3&t|8).toString(16)})};const $e=(e,r)=>Object.assign(Object.assign({},m(e)?e:{value:e}),{[r]:Le()}),Ae=(e,r)=>(d(e)?e:[]).map(e=>$e(e,r)),Pe=(e,r)=>[...e.slice(0,r),...e.slice(r+1)];var Me=(e,r)=>l(r)?[]:d(r)?r.reduce(({result:e,previousIndex:r},t)=>({result:Pe(e,r>-1&&r<t?t-1:t),previousIndex:t}),{result:e,previousIndex:-1}).result:Pe(e,r),We=(e,r,t)=>d(e)?e.splice(t,0,e.splice(r,1)[0]):[],De=(e,r,t)=>d(e)&&([e[r],e[t]]=[e[t],e[r]]),Ie=(e,r)=>[...d(r)?r:[r||null],...e],Te=(e,r,t)=>[...e.slice(0,r),...d(t)?t:[t||null],...e.slice(r)],Ue=e=>d(e)?Array(e.length).fill(null):void 0;const{useEffect:ze,useCallback:He,useRef:Ge,useState:qe}=e,_e=({control:e,name:r,keyName:t="id"})=>{const n=Ce(),{resetFieldArrayFunctionRef:s,fieldArrayNamesRef:c,reRender:u,fieldsRef:i,getValues:a,defaultValuesRef:o,removeFieldEventListener:f,errorsRef:g,dirtyFieldsRef:m,isDirtyRef:h,touchedFieldsRef:v,readFormStateRef:b,watchFieldArrayRef:p,validFieldsRef:y,fieldsWithValidationRef:O,validateSchemaIsValid:j}=e||n.control,S=Ge($(o.current,r,[])),[w,x]=qe(Ae(S.current,t)),R=Ge(w),V=e=>e.map(e=>$e(e,t));R.current=w;const E=e=>{p.current=Object.assign(Object.assign({},p.current),{[r]:e}),x(e),b.current.isValid&&j&&j({[r]:e})},B=e=>{b.current.dirty&&(h.current=!!l(e)||ye(e,S.current));for(const e in i.current)Oe(e,r)&&i.current[e]&&f(i.current[e],!0)},N=()=>{const e=a({nest:!0})[r];if(d(e))for(let r=0;r<e.length;r++)w[r]=Object.assign(Object.assign({},w[r]),e[r])},F=()=>{B(),S.current=$(o.current,r,[]),x(Ae(S.current,t))};return ze(()=>{const e=s.current,t=c.current;return t.add(r),e[r]=F,p.current=Object.assign(Object.assign({},p.current),{[r]:w}),()=>{B(),delete e[r],t.delete(r)}},[]),{swap:He((e,t)=>{N();const n=pe(i.current,r);De(n,e,t),B(n),De(R.current,e,t),E([...R.current]),g.current[r]&&De(g.current[r],e,t),b.current.touched&&v.current[r]&&De(v.current[r],e,t)},[]),move:He((e,t)=>{N();const n=pe(i.current,r);We(n,e,t),B(n),We(R.current,e,t),E([...R.current]),g.current[r]&&We(g.current[r],e,t),b.current.touched&&v.current[r]&&We(v.current[r],e,t)},[]),prepend:He(e=>{N(),B(),E(Ie(R.current,d(e)?V(e):[$e(e,t)])),g.current[r]&&(g.current[r]=Ie(g.current[r],Ue(e))),b.current.touched&&v.current[r]&&(v.current[r]=Ie(v.current[r],Ue(e)))},[]),append:He(e=>{N(),b.current.dirty&&(h.current=!0),E([...R.current,...d(e)?V(e):[$e(e,t)]])},[]),remove:He(e=>{if(l(e)||N(),B(Me(pe(i.current,r),e)),E(Me(R.current,e)),g.current[r]&&(g.current[r]=Me(g.current[r],e),g.current[r].filter(Boolean).length||delete g.current[r]),b.current.touched&&v.current[r]&&(v.current[r]=Me(v.current[r],e)),b.current.dirty&&m.current.forEach(t=>{(l(r)||t.startsWith(`${r}[${e}]`))&&m.current.delete(t)}),b.current.isValid&&!j){let t=-1,n=!1;const s=l(e);for(;t++<w.length;){const c=t===w.length-1,u=(d(e)?e:[e]).indexOf(t)>=0;if((u||s)&&(n=!0),n)for(const e in w[t]){const n=`${r}[${t}].${e}`;if(u||c||s)y.current.delete(n),O.current.delete(n);else{const s=`${r}[${t-1}].${e}`;y.current.has(n)&&y.current.add(s),O.current.has(n)&&O.current.add(s)}}}u()}},[w]),insert:He((e,n)=>{N(),B(Te(pe(i.current,r),e)),E(Te(R.current,e,d(n)?V(n):[$e(n,t)])),g.current[r]&&(g.current[r]=Te(g.current[r],e,Ue(n))),b.current.touched&&v.current[r]&&(v.current[r]=Te(v.current[r],e,Ue(n)))},[]),fields:w}};const Je=e=>{var{name:r,rules:t,as:o,onBlur:f,onChange:d,onChangeName:g=v.onChange,onBlurName:h=v.onBlur,valueName:b,defaultValue:p,control:y}=e,O=Ne(e,["name","rules","as","onBlur","onChange","onChangeName","onBlurName","valueName","defaultValue","control"]);const j=Ce(),{defaultValuesRef:S,setValue:w,register:x,unregister:R,errorsRef:V,removeFieldEventListener:E,triggerValidation:B,mode:{isOnSubmit:N,isOnBlur:F},reValidateMode:{isReValidateOnBlur:C,isReValidateOnSubmit:k},formState:{isSubmitted:L},fieldsRef:A,fieldArrayNamesRef:P}=y||j.control,[M,W]=s(l(p)?$(S.current,r):p),D=c(M),I=ue(M),T=()=>!be({hasError:!!$(V.current,r),isOnBlur:F,isOnSubmit:N,isReValidateOnBlur:C,isReValidateOnSubmit:k,isSubmitted:L}),U=e=>{const r=((e,r)=>ge(e)||!m(e.target)||m(e.target)&&!e.type?e:r||l(e.target.value)?e.target.checked:e.target.value)(e,I);return W(r),D.current=r,r},z=()=>{je(P.current,r)&&A.current[r]&&E(A.current[r],!0),x(Object.defineProperty({name:r},"value",{set(e){W(e),D.current=e},get:()=>D.current}),Object.assign({},t))};u(()=>{A.current[r]||(z(),W(l(p)?$(S.current,r):p))}),u(()=>(z(),()=>{je(P.current,r)||R(r)}),[r]),u(()=>{z()},[t]);const H=F||C,G=Object.assign(Object.assign(Object.assign(Object.assign({name:r},O),d?{[g]:(e=>(...t)=>w(r,U(e(t)),T()))(d)}:{[g]:e=>{const t=U(e);w(r,t,T())}}),f||H?{[h]:(...e)=>{f&&f(e),H&&B(r)}}:{}),{[b||(I?"checked":"value")]:M});return i(o)?a(o,G):n(o,G)},Ke=e=>{var{as:r,errors:t,name:s,message:c,children:u}=e,l=Ne(e,["as","errors","name","message","children"]);const f=Ce(),d=$(t||f.errors,s);if(!d)return null;const{message:g,types:m}=d,h=Object.assign(Object.assign({},r?l:{}),{children:u?u({message:g||c,messages:m}):g||c});return r?i(r)?a(r,h):n(r,h):n(o,Object.assign({},h))};export{Je as Controller,Ke as ErrorMessage,ke as FormContext,_e as useFieldArray,Be as useForm,Ce as useFormContext};
1
+ import*as e from"react";import{createContext as r,useContext as t,createElement as n,useState as c,useRef as s,useEffect as u,isValidElement as i,cloneElement as a,Fragment as o}from"react";var l=e=>void 0===e,f=e=>null===e||l(e),d=e=>Array.isArray(e);const g=e=>"object"==typeof e;var m=e=>!f(e)&&!d(e)&&g(e),h=e=>m(e)&&e.nodeType===Node.ELEMENT_NODE;const v={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit"},b="undefined",p={BLUR:"blur",CHANGE:"change",INPUT:"input"},O="max",y="min",j="maxLength",S="minLength",R="pattern",w="required",x="validate",E=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,V=/^\w*$/,B=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,C=/\\(\\)?/g;var N=e=>!d(e)&&(V.test(e)||!E.test(e)),F=e=>{const r=[];return e.replace(B,(e,t,n,c)=>{r.push(n?c.replace(C,"$1"):t||e)}),r};function k(e,r,t){let n=-1;const c=N(r)?[r]:F(r),s=c.length,u=s-1;for(;++n<s;){const r=c[n];let s=t;if(n!==u){const t=e[r];s=m(t)||d(t)?t:isNaN(c[n+1])?{}:[]}e[r]=s,e=e[r]}return e}var L=e=>Object.entries(e).reduce((e,[r,t])=>N(r)?Object.assign(Object.assign({},e),{[r]:t}):(k(e,r,t),e),{}),$=(e,r,t)=>{const n=r.split(/[,[\].]+?/).filter(Boolean).reduce((e,r)=>f(e)?e:e[r],e);return l(n)||n===e?e[r]||t:n},A=(e,r)=>{for(const t in e)if($(r,t)){const r=e[t];if(r){if(h(r.ref)&&r.ref.focus){r.ref.focus();break}if(r.options){r.options[0].ref.focus();break}}}},M=(e,r)=>{h(e)&&e.removeEventListener&&(e.removeEventListener(p.INPUT,r),e.removeEventListener(p.CHANGE,r),e.removeEventListener(p.BLUR,r))},P=e=>!!e&&"radio"===e.type,D=e=>!!e&&"checkbox"===e.type;function W(e){return!e||e instanceof HTMLElement&&e.nodeType!==Node.DOCUMENT_NODE&&W(e.parentNode)}var I=e=>m(e)&&!Object.keys(e).length;function T(e){return d(e)?e:F(e)}function U(e,r){return 1==r.length?e:function(e,r){const t=N(r)?[r]:T(r),n=r.length;let c=0;for(;c<n;)e=l(e)?c++:e[t[c++]];return c==n?e:void 0}(e,function(e,r,t){let n=-1,c=e.length;r<0&&(r=-r>c?0:c+r),(t=t>c?c:t)<0&&(t+=c),c=r>t?0:t-r;const s=Array(c);for(;++n<c;)s[n]=e[n+r];return s}(r,0,-1))}function z(e,r){return r.forEach(r=>{!function(e,r){const t=N(r)?[r]:T(r),n=U(e,t),c=t[t.length-1],s=!(null!=n)||delete n[c];let u=void 0;for(let r=0;r<t.slice(0,-1).length;r++){let n=-1,c=void 0;const s=t.slice(0,-(r+1)),i=s.length-1;for(r>0&&(u=e);++n<s.length;){const r=s[n];c=c?c[r]:e[r],i===n&&(m(c)&&I(c)?u?delete u[r]:delete e[r]:d(c)&&!c.filter(e=>m(e)&&!I(e)).length&&u&&delete u[r]),u=c}}}(e,r)}),e}const H={isValid:!1,value:""};var G=e=>d(e)?e.reduce((e,{ref:{checked:r,value:t}})=>r?{isValid:!0,value:t}:e,H):H,_=e=>[...e].filter(({selected:e})=>e).map(({value:e})=>e),q=e=>!!e&&"file"===e.type,J=e=>!!e&&"select-multiple"===e.type,K=e=>""===e;const Q={value:!1,isValid:!1},X={value:!0,isValid:!0};var Y=e=>{if(d(e)){if(e.length>1){const r=e.filter(({ref:{checked:e}})=>e).map(({ref:{value:e}})=>e);return{value:r,isValid:!!r.length}}const{checked:r,value:t,attributes:n}=e[0].ref;return r?n&&!l(n.value)?l(t)||K(t)?X:{value:t,isValid:!0}:X:Q}return Q};function Z(e,r){const{name:t,value:n}=r,c=e[t];return q(r)?r.files:P(r)?c?G(c.options).value:"":J(r)?_(r.options):D(r)?!!c&&Y(c.options).value:n}var ee=e=>"string"==typeof e,re=(e,r)=>{const t={},n=ee(r),c=d(r),s=r&&r.nest;for(const u in e)(l(r)||s||n&&u.startsWith(r)||c&&r.find(e=>u.startsWith(e)))&&(t[u]=Z(e,e[u].ref));return t},te=(e,{type:r,types:t,message:n})=>m(e)&&e.type===r&&e.message===n&&((e={},r={})=>Object.entries(e).reduce((e,[t,n])=>!!e&&r[t]&&r[t]===n,!0))(e.types,t);var ne=e=>e instanceof RegExp,ce=e=>{const r=m(e)&&!ne(e);return{value:r?e.value:e,message:r?e.message:""}},se=e=>"function"==typeof e,ue=e=>"boolean"==typeof e;function ie(e,r,t="validate"){const n=ee(e);if(n||ue(e)&&!e){return{type:t,message:n?e:"",ref:r}}}var ae=(e,r,t,n,c)=>{if(!r)return{};const s=t[e];return Object.assign(Object.assign({},s),{types:Object.assign(Object.assign({},s&&s.types?s.types:{}),{[n]:c||!0})})},oe=async(e,r,{ref:t,ref:{type:n,value:c,name:s},options:u,required:i,maxLength:a,minLength:o,min:l,max:d,pattern:g,validate:h})=>{const v=e.current,b={},p=P(t),E=D(t),V=p||E,B=K(c),C=ae.bind(null,s,r,b),N=(e,n,c,u=j,i=S)=>{const a=e?n:c;if(b[s]=Object.assign({type:e?u:i,message:a,ref:t},C(e?u:i,a)),!r)return b};if(i&&(!p&&!E&&(B||f(c))||ue(c)&&!c||E&&!Y(u).isValid||p&&!G(u).isValid)){const{value:e,message:n}=ee(i)?{value:!!i,message:i}:ce(i);if(e&&(b[s]=Object.assign({type:w,message:n,ref:V?v[s].options[0].ref:t},C(w,n)),!r))return b}if(!f(l)||!f(d)){let e,s;const{value:u,message:i}=ce(d),{value:a,message:o}=ce(l);if("number"===n||!n&&!isNaN(c)){const r=t.valueAsNumber||parseFloat(c);f(u)||(e=r>u),f(a)||(s=r<a)}else{const r=t.valueAsDate||new Date(c);ee(u)&&(e=r>new Date(u)),ee(a)&&(s=r<new Date(a))}if((e||s)&&(N(!!e,i,o,O,y),!r))return b}if(ee(c)&&!B&&(a||o)){const{value:e,message:t}=ce(a),{value:n,message:s}=ce(o),u=c.toString().length,i=a&&u>e,l=o&&u<n;if((i||l)&&(N(!!i,t,s),!r))return b}if(g&&!B){const{value:e,message:n}=ce(g);if(ne(e)&&!e.test(c)&&(b[s]=Object.assign({type:R,message:n,ref:t},C(R,n)),!r))return b}if(h){const e=Z(v,t),n=V&&u?u[0].ref:t;if(se(h)){const t=ie(await h(e),n);if(t&&(b[s]=Object.assign(Object.assign({},t),C(x,t.message)),!r))return b}else if(m(h)){const t=Object.entries(h),c=await new Promise(c=>{t.reduce(async(u,[i,a],o)=>{if(!I(await u)&&!r||!se(a))return c(u);let l;const f=ie(await a(e),n,i);return f?(l=Object.assign(Object.assign({},f),C(i,f.message)),r&&(b[s]=l)):l=u,t.length-1===o?c(l):l},{})});if(!I(c)&&(b[s]=Object.assign({ref:n},c),!r))return b}}return b};const le=(e,r)=>d(e.inner)?e.inner.reduce((e,{path:t,message:n,type:c})=>Object.assign(Object.assign({},e),e[t]&&r?{[t]:ae(t,r,e,c,n)}:{[t]:e[t]||Object.assign({message:n,type:c},r?{types:{[c]:n||!0}}:{})}),{}):{[e.path]:{message:e.message,type:e.type}};async function fe(e,r,t,n,c){if(n)return n(t,c);try{return{values:await e.validate(t,{abortEarly:!1,context:c}),errors:{}}}catch(e){return{values:{},errors:L(le(e,r))}}}var de=(e,r,t)=>l(e[r])?$(e,r,t):e[r];var ge=e=>f(e)||!g(e);const me=(e,r)=>{const t=(r,t,n)=>{const c=n?`${e}.${t}`:`${e}[${t}]`;return ge(r)?c:me(c,r)};return d(r)?r.map((e,r)=>t(e,r)):Object.entries(r).map(([e,r])=>t(r,e,!0))};var he=(e,r)=>(function e(r){return r.reduce((r,t)=>r.concat(d(t)?e(t):t),[])})(me(e,r)),ve=(e,r,t,n,c)=>{let s;return t.add(r),I(e)?s=c||void 0:l(e[r])?(s=$(L(e),r),d(c)&&d(s)&&s.length!==c.length&&(s=c),l(s)||he(r,s).forEach(e=>t.add(e))):(s=e[r],t.add(r)),l(s)?m(n)?de(n,r):n:s},be=({isOnChange:e,hasError:r,isBlurEvent:t,isOnSubmit:n,isReValidateOnSubmit:c,isOnBlur:s,isReValidateOnBlur:u,isSubmitted:i})=>e&&t||n&&c||n&&!i||s&&!t&&!r||u&&!t&&r||c&&i,pe=(e,r)=>{const t=L(re(e));return r?$(t,r,t):t};function Oe(e,r){let t=!1;if(!d(e)||!d(r)||e.length!==r.length)return!0;for(let n=0;n<e.length&&!t;n++){const c=e[n],s=r[n];if(l(s)||Object.keys(c).length!==Object.keys(s).length){t=!0;break}for(const e in c)if(c[e]!==s[e]){t=!0;break}}return t}const ye=(e,r)=>e.startsWith(`${r}[`);var je=(e,r)=>[...e].reduce((e,t)=>!!ye(r,t)||e,!1),Se=e=>typeof FileList!==b&&e instanceof FileList;var Re=e=>({isOnSubmit:!e||e===v.onSubmit,isOnBlur:e===v.onBlur,isOnChange:e===v.onChange});const{useRef:we,useState:xe,useCallback:Ee,useEffect:Ve}=e;function Be({mode:e=v.onSubmit,reValidateMode:r=v.onChange,validationSchema:t,validationResolver:n,validationContext:c,defaultValues:s={},submitFocusError:u=!0,validateCriteriaMode:i}={}){const a=we({}),o="all"===i,g=we({}),O=we({}),y=we({}),j=we(new Set),S=we(new Set),R=we(new Set),w=we(new Set),x=we(!0),E=we({}),V=we(s),B=we(!1),C=we(!1),N=we(!1),F=we(!1),T=we(0),U=we(!1),H=we(),G=we({}),_=we(c),Q=we(new Set),[,X]=xe(),{isOnBlur:Y,isOnSubmit:ne,isOnChange:ce}=we(Re(e)).current,ie=typeof window===b,ae=!(!t&&!n),le=typeof document!==b&&!ie&&!l(window.HTMLElement),me=le&&"Proxy"in window,he=we({dirty:!me,dirtyFields:!me,isSubmitted:ne,submitCount:!me,touched:!me,isSubmitting:!me,isValid:!me}),{isOnBlur:ye,isOnSubmit:Be}=we(Re(r)).current,Ce=Ee(()=>{B.current||X({})},[]),Ne=Ee((e,r,t,n)=>{let c=t||function({errors:e,name:r,error:t,validFields:n,fieldsWithValidation:c}){const s=I(t),u=I(e),i=$(t,r),a=$(e,r);return!(s&&n.has(r)||a&&a.isManual)&&(!!(u!==s||!u&&!a||s&&c.has(r)&&!n.has(r))||i&&!te(a,i))}({errors:g.current,error:r,name:e,validFields:w.current,fieldsWithValidation:R.current});if(I(r)?((R.current.has(e)||ae)&&(w.current.add(e),c=c||$(g.current,e)),g.current=z(g.current,[e])):(w.current.delete(e),c=c||!$(g.current,e),k(g.current,e,r[e])),c&&!n)return Ce(),!0},[Ce,ae]),Fe=Ee((e,r)=>{const t=e.ref,n=e.options,{type:c}=t,s=le&&h(t)&&f(r)?"":r;return P(t)&&n?n.forEach(({ref:e})=>e.checked=e.value===s):q(t)?K(s)||Se(s)?t.files=s:t.value=s:J(t)?[...t.options].forEach(e=>e.selected=s.includes(e.value)):D(t)&&n?n.length>1?n.forEach(({ref:e})=>e.checked=s.includes(e.value)):n[0].ref.checked=!!s:t.value=s,!!c},[le]),ke=e=>{if(!a.current[e]||!he.current.dirty&&!he.current.dirtyFields)return!1;const r=je(Q.current,e),t=S.current.size;let n=E.current[e]!==Z(a.current,a.current[e].ref);if(r){const r=e.substring(0,e.indexOf("["));n=Oe(pe(a.current,r),$(V.current,r))}const c=(r?F.current:S.current.has(e))!==n;return n?S.current.add(e):S.current.delete(e),F.current=r?n:!!S.current.size,he.current.dirty?c:t!==S.current.size},Le=Ee(e=>{if(ke(e)||!$(O.current,e)&&he.current.touched)return!!k(O.current,e,!0)},[]),$e=Ee((e,r,t)=>{const n=d(r);for(const c in r){const s=`${t||e}${n?`[${c}]`:`.${c}`}`;m(r[c])&&$e(e,r[c],s);const u=a.current[s];u&&(Fe(u,r[c]),Le(s))}},[Fe,Le]),Ae=Ee((e,r)=>{const t=a.current[e];if(t){Fe(t,r);const n=Le(e);if(ue(n))return n}else ge(r)||$e(e,r)},[Le,Fe,$e]),Me=Ee(async(e,r)=>{const t=a.current[e];if(!t)return!1;const n=await oe(a,o,t);return Ne(e,n,!1,r),I(n)},[Ne,o]),Pe=Ee(async e=>{const{errors:r}=await fe(t,o,pe(a.current),n,_.current),c=x.current;return x.current=I(r),d(e)?(e.forEach(e=>{const t=$(r,e);t?k(g.current,e,t):z(g.current,[e])}),Ce()):Ne(e,$(r,e)?{[e]:$(r,e)}:{},c!==x.current),I(g.current)},[Ce,Ne,o,n,t]),De=Ee(async e=>{const r=e||Object.keys(a.current);if(ae)return Pe(r);if(d(r)){const e=await Promise.all(r.map(async e=>await Me(e,!0)));return Ce(),e.every(Boolean)}return await Me(r)},[Pe,Me,Ce,ae]),We=e=>C.current||j.current.has(e)||j.current.has((e.match(/\w+/)||[])[0]);function Ie(e,r,t){let n=!1;const c=d(e);(c?e:[e]).forEach(e=>{const t=ee(e);n=!(!Ae(t?e:Object.keys(e)[0],t?r:Object.values(e)[0])&&!c)||We(e)}),(n||c)&&Ce(),(t||c&&r)&&De(c?void 0:e)}H.current=H.current?H.current:async({type:e,target:r})=>{const c=r?r.name:"",s=a.current,u=g.current,i=s[c],l=$(u,c);let f;if(!i)return;const d=e===p.BLUR,m=be({hasError:!!l,isOnChange:ce,isBlurEvent:d,isOnSubmit:ne,isReValidateOnSubmit:Be,isOnBlur:Y,isReValidateOnBlur:ye,isSubmitted:N.current}),h=ke(c);let v=We(c)||h;if(d&&!$(O.current,c)&&he.current.touched&&(k(O.current,c,!0),v=!0),m)return v&&Ce();if(ae){const{errors:e}=await fe(t,o,pe(s),n,_.current),r=x.current;x.current=I(e),f=$(e,c)?{[c]:$(e,c)}:{},r!==x.current&&(v=!0)}else f=await oe(a,o,i);!Ne(c,f)&&v&&Ce()};const Te=Ee((e={})=>{const r=I(V.current)?re(a.current):V.current;fe(t,o,L(Object.assign(Object.assign({},r),e)),n,_.current).then(({errors:e})=>{const r=x.current;x.current=I(e),r!==x.current&&Ce()})},[Ce,o,n]),Ue=(e,r)=>{!l(H.current)&&e&&function(e,r,t,n){if(!t)return;const{ref:c,ref:{name:s,type:u},mutationWatcher:i}=t;if(!u)return void delete e[s];const a=e[s];if((P(c)||D(c))&&a){const{options:t}=a;d(t)&&t.length?(t.forEach(({ref:e,mutationWatcher:c},s)=>{(e&&W(e)||n)&&(M(e,r),c&&c.disconnect(),z(t,[`[${s}]`]))}),t&&!t.filter(Boolean).length&&delete e[s]):delete e[s]}else(W(c)||n)&&(M(c,r),i&&i.disconnect(),delete e[s])}(a.current,H.current,e,r)},ze=Ee((e,r)=>{if(!e||e&&je(Q.current,e.ref.name)&&!r)return;Ue(e,r);const{name:t}=e.ref;g.current=z(g.current,[t]),O.current=z(O.current,[t]),E.current=z(E.current,[t]),[S,R,w,j].forEach(e=>e.current.delete(t)),(he.current.isValid||he.current.touched)&&(Ce(),ae&&Te())},[Ce,ae,Te]);const He=({name:e,type:r,types:t,message:n,preventRender:c})=>{const s=a.current[e];te(g.current[e],{type:r,message:n,types:t})||(k(g.current,e,{type:r,types:t,message:n,ref:s?s.ref:{},isManual:!0}),c||Ce())};function Ge(e){I(a.current)||(d(e)?e:[e]).forEach(e=>ze(a.current[e],!0))}function _e(e,r={}){if(!e.name)return console.warn("Missing name @",e);const{name:t,type:n,value:c}=e,s=Object.assign({ref:e},r),u=a.current,i=P(e)||D(e);let f,g=u[t],m=!0,v=!1;if(i?g&&d(g.options)&&g.options.find(({ref:e})=>c===e.value):g)return void(u[t]=Object.assign(Object.assign({},g),r));if(n){const c=function(e,r){const t=new MutationObserver(()=>{W(e)&&(t.disconnect(),r())});return t.observe(window.document,{childList:!0,subtree:!0}),t}(e,()=>ze(s));g=i?Object.assign({options:[...g&&g.options||[],{ref:e,mutationWatcher:c}],ref:{type:n,name:t}},r):Object.assign(Object.assign({},s),{mutationWatcher:c})}else g=s;if(u[t]=g,I(V.current)||(f=de(V.current,t),m=l(f),v=je(Q.current,t),m||v||Fe(g,f)),ae&&!v&&he.current.isValid?Te():I(r)||(R.current.add(t),!ne&&he.current.isValid&&oe(a,o,g).then(e=>{const r=x.current;I(e)?w.current.add(t):x.current=!1,r!==x.current&&Ce()})),E.current[t]||v&&m||(E.current[t]=m?Z(u,g.ref):f),!n)return;!function({field:e,handleChange:r,isRadioOrCheckbox:t}){const{ref:n}=e;h(n)&&n.addEventListener&&r&&(n.addEventListener(t?p.CHANGE:p.INPUT,r),n.addEventListener(p.BLUR,r))}({field:i&&g.options?g.options[g.options.length-1]:g,isRadioOrCheckbox:i,handleChange:H.current})}function qe(e,r){if(!ie)if(ee(e))_e({name:e},r);else{if(!(m(e)&&"name"in e))return r=>r&&_e(r,e);_e(e,r)}}const Je=Ee(e=>async r=>{let c,s;r&&(r.preventDefault(),r.persist());const i=a.current;he.current.isSubmitting&&(U.current=!0,Ce());try{if(ae){s=re(i);const{errors:e,values:r}=await fe(t,o,L(s),n,_.current);g.current=e,c=e,s=r}else{const{errors:e,values:r}=await Object.values(i).reduce(async(e,r)=>{if(!r)return e;const t=await e,{ref:n,ref:{name:c}}=r;if(!i[c])return t;const s=await oe(a,o,r);return s[c]?(k(t.errors,c,s[c]),w.current.delete(c),t):(R.current.has(c)&&w.current.add(c),t.values[c]=Z(i,n),t)},Promise.resolve({errors:{},values:{}}));c=e,s=r}I(c)?(g.current={},await e(L(s),r)):(u&&le&&A(i,c),g.current=c)}finally{N.current=!0,U.current=!1,T.current=T.current+1,Ce()}},[le,Ce,ae,u,o,n,t]),Ke=e=>{const r=re(a.current),t=I(r)?V.current:r;return e&&e.nest?L(t):t};Ve(()=>()=>{B.current=!0,a.current&&"production"===process.env.NODE_ENV&&Object.values(a.current).forEach(e=>ze(e,!0))},[ze]),ae||(x.current=w.current.size>=R.current.size&&I(g.current));const Qe={dirty:F.current,dirtyFields:S.current,isSubmitted:N.current,submitCount:T.current,touched:O.current,isSubmitting:U.current,isValid:ne?N.current&&I(g.current):x.current};return{watch:function(e,r){const t=l(r)?l(V.current)?{}:V.current:r,n=re(a.current,e),c=j.current;if(ee(e))return ve(n,e,c,t,Q.current.has(e)?y.current[e]:void 0);if(d(e))return e.reduce((e,r)=>Object.assign(Object.assign({},e),{[r]:ve(n,r,c,t)}),{});C.current=!0;const s=!I(n)&&n||r||V.current;return e&&e.nest?L(s):s},control:Object.assign(Object.assign({register:qe,unregister:Ge,removeFieldEventListener:Ue,getValues:Ke,setValue:Ie,reRender:Ce,triggerValidation:De},ae?{validateSchemaIsValid:Te}:{}),{formState:Qe,mode:{isOnBlur:Y,isOnSubmit:ne,isOnChange:ce},reValidateMode:{isReValidateOnBlur:ye,isReValidateOnSubmit:Be},errorsRef:g,touchedFieldsRef:O,fieldsRef:a,resetFieldArrayFunctionRef:G,validFieldsRef:w,dirtyFieldsRef:S,fieldsWithValidationRef:R,watchFieldArrayRef:y,fieldArrayNamesRef:Q,isDirtyRef:F,readFormStateRef:he,defaultValuesRef:V}),handleSubmit:Je,setValue:Ee(Ie,[Ce,Ae,De]),triggerValidation:De,getValues:Ee(Ke,[]),reset:Ee((e,r={})=>{if(le)for(const e of Object.values(a.current))if(e&&h(e.ref)&&e.ref.closest)try{e.ref.closest("form").reset();break}catch(e){}e&&(V.current=e),Object.values(G.current).forEach(e=>se(e)&&e()),(({errors:e,dirty:r,isSubmitted:t,touched:n,isValid:c,submitCount:s})=>{a.current={},e||(g.current={}),n||(O.current={}),c||(w.current=new Set,R.current=new Set,x.current=!0),r||(S.current=new Set,F.current=!1),t||(N.current=!1),s||(T.current=0),E.current={},j.current=new Set,C.current=!1})(r),Ce()},[]),register:Ee(qe,[V.current,E.current,y.current]),unregister:Ee(Ge,[]),clearError:Ee(function(e){l(e)?g.current={}:z(g.current,d(e)?e:[e]),Ce()},[]),setError:Ee(function(e,r="",t){ee(e)?He(Object.assign({name:e},m(r)?{types:r,type:""}:{type:r,message:t})):d(e)&&(e.forEach(e=>He(Object.assign(Object.assign({},e),{preventRender:!0}))),Ce())},[]),errors:g.current,formState:me?new Proxy(Qe,{get:(e,r)=>r in e?(he.current[r]=!0,e[r]):{}}):Qe}}function Ce(e,r){var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&r.indexOf(n)<0&&(t[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var c=0;for(n=Object.getOwnPropertySymbols(e);c<n.length;c++)r.indexOf(n[c])<0&&Object.prototype.propertyIsEnumerable.call(e,n[c])&&(t[n[c]]=e[n[c]])}return t}const Ne=r(null);function Fe(){return t(Ne)}function ke(e){var{children:r,formState:t,errors:c}=e,s=Ce(e,["children","formState","errors"]);return n(Ne.Provider,{value:Object.assign(Object.assign({},s),{formState:t,errors:c})},r)}var Le=()=>{const e=typeof performance===b?Date.now():1e3*performance.now();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(r){const t=(16*Math.random()+e)%16|0;return("x"==r?t:3&t|8).toString(16)})};const $e=(e,r)=>Object.assign(Object.assign({},m(e)?e:{value:e}),{[r]:Le()}),Ae=(e,r)=>(d(e)?e:[]).map(e=>$e(e,r)),Me=(e,r)=>[...e.slice(0,r),...e.slice(r+1)];var Pe=(e,r)=>l(r)?[]:d(r)?r.reduce(({result:e,previousIndex:r},t)=>({result:Me(e,r>-1&&r<t?t-1:t),previousIndex:t}),{result:e,previousIndex:-1}).result:Me(e,r),De=(e,r,t)=>d(e)?e.splice(t,0,e.splice(r,1)[0]):[],We=(e,r,t)=>d(e)&&([e[r],e[t]]=[e[t],e[r]]),Ie=(e,r)=>[...d(r)?r:[r||null],...e],Te=(e,r,t)=>[...e.slice(0,r),...d(t)?t:[t||null],...e.slice(r)],Ue=e=>d(e)?Array(e.length).fill(null):void 0;const{useEffect:ze,useCallback:He,useRef:Ge,useState:_e}=e,qe=({control:e,name:r,keyName:t="id"})=>{const n=Fe(),{resetFieldArrayFunctionRef:c,fieldArrayNamesRef:s,reRender:u,fieldsRef:i,getValues:a,defaultValuesRef:o,removeFieldEventListener:f,errorsRef:g,dirtyFieldsRef:m,isDirtyRef:h,touchedFieldsRef:v,readFormStateRef:b,watchFieldArrayRef:p,validFieldsRef:O,fieldsWithValidationRef:y,validateSchemaIsValid:j}=e||n.control,S=Ge($(o.current,r,[])),[R,w]=_e(Ae(S.current,t)),x=Ge(R),E=e=>e.map(e=>$e(e,t));x.current=R;const V=e=>{p.current=Object.assign(Object.assign({},p.current),{[r]:e}),w(e),b.current.isValid&&j&&j({[r]:e})},B=e=>{b.current.dirty&&(h.current=!!l(e)||Oe(e,S.current));for(const e in i.current)ye(e,r)&&i.current[e]&&f(i.current[e],!0)},C=()=>{const e=a({nest:!0})[r];if(d(e))for(let r=0;r<e.length;r++)x.current[r]=Object.assign(Object.assign({},x.current[r]),e[r])},N=()=>{B(),S.current=$(o.current,r,[]),w(Ae(S.current,t))};return ze(()=>{const e=c.current,t=s.current;return t.add(r),e[r]=N,p.current=Object.assign(Object.assign({},p.current),{[r]:R}),()=>{B(),delete e[r],t.delete(r)}},[]),{swap:He((e,t)=>{C();const n=pe(i.current,r);We(n,e,t),B(n),We(x.current,e,t),V([...x.current]),g.current[r]&&We(g.current[r],e,t),b.current.touched&&v.current[r]&&(We(v.current[r],e,t),u())},[]),move:He((e,t)=>{C();const n=pe(i.current,r);De(n,e,t),B(n),De(x.current,e,t),V([...x.current]),g.current[r]&&De(g.current[r],e,t),b.current.touched&&v.current[r]&&(De(v.current[r],e,t),u())},[]),prepend:He(e=>{B(),V(Ie(x.current,d(e)?E(e):[$e(e,t)])),g.current[r]&&(g.current[r]=Ie(g.current[r],Ue(e))),b.current.touched&&v.current[r]&&(v.current[r]=Ie(v.current[r],Ue(e)),u())},[]),append:He(e=>{b.current.dirty&&(h.current=!0,u()),V([...x.current,...d(e)?E(e):[$e(e,t)]])},[]),remove:He(e=>{let t=!1;if(l(e)||C(),B(Pe(pe(i.current,r),e)),V(Pe(x.current,e)),g.current[r]&&(g.current[r]=Pe(g.current[r],e),g.current[r].filter(Boolean).length||delete g.current[r]),b.current.touched&&v.current[r]&&(v.current[r]=Pe(v.current[r],e),t=!0),b.current.dirty&&(m.current.forEach(t=>{(l(r)||t.startsWith(`${r}[${e}]`))&&m.current.delete(t)}),t=!0),b.current.isValid&&!j){let n=-1,c=!1;const s=l(e);for(;n++<R.length;){const t=n===R.length-1,u=(d(e)?e:[e]).indexOf(n)>=0;if((u||s)&&(c=!0),c)for(const e in R[n]){const c=`${r}[${n}].${e}`;if(u||t||s)O.current.delete(c),y.current.delete(c);else{const t=`${r}[${n-1}].${e}`;O.current.has(c)&&O.current.add(t),y.current.has(c)&&y.current.add(t)}}}t=!0}t&&u()},[R]),insert:He((e,n)=>{C(),B(Te(pe(i.current,r),e)),V(Te(x.current,e,d(n)?E(n):[$e(n,t)])),g.current[r]&&(g.current[r]=Te(g.current[r],e,Ue(n))),b.current.touched&&v.current[r]&&(v.current[r]=Te(v.current[r],e,Ue(n)),u())},[]),fields:R}};const Je=e=>{var{name:r,rules:t,as:o,onBlur:f,onChange:d,onChangeName:g=v.onChange,onBlurName:h=v.onBlur,valueName:b,defaultValue:p,control:O}=e,y=Ce(e,["name","rules","as","onBlur","onChange","onChangeName","onBlurName","valueName","defaultValue","control"]);const j=Fe(),{defaultValuesRef:S,setValue:R,register:w,unregister:x,errorsRef:E,removeFieldEventListener:V,triggerValidation:B,mode:{isOnSubmit:C,isOnBlur:N,isOnChange:F},reValidateMode:{isReValidateOnBlur:k,isReValidateOnSubmit:L},formState:{isSubmitted:A},fieldsRef:M,fieldArrayNamesRef:P}=O||j.control,[D,W]=c(l(p)?$(S.current,r):p),I=s(D),T=ue(D),U=()=>!be({hasError:!!$(E.current,r),isOnBlur:N,isOnSubmit:C,isOnChange:F,isReValidateOnBlur:k,isReValidateOnSubmit:L,isSubmitted:A}),z=e=>{const r=((e,r)=>ge(e)||!m(e.target)||m(e.target)&&!e.type?e:r||l(e.target.value)?e.target.checked:e.target.value)(e,T);return W(r),I.current=r,r},H=()=>{je(P.current,r)&&M.current[r]&&V(M.current[r],!0),w(Object.defineProperty({name:r},"value",{set(e){W(e),I.current=e},get:()=>I.current}),Object.assign({},t))};u(()=>{M.current[r]||(H(),W(l(p)?$(S.current,r):p))}),u(()=>(H(),()=>{je(P.current,r)||x(r)}),[r]),u(()=>{H()},[t]);const G=N||k,_=Object.assign(Object.assign(Object.assign(Object.assign({name:r},y),d?{[g]:(e=>(...t)=>R(r,z(e(t)),U()))(d)}:{[g]:e=>{const t=z(e);R(r,t,U())}}),f||G?{[h]:(...e)=>{f&&f(e),G&&B(r)}}:{}),{[b||(T?"checked":"value")]:D});return i(o)?a(o,_):n(o,_)},Ke=e=>{var{as:r,errors:t,name:c,message:s,children:u}=e,l=Ce(e,["as","errors","name","message","children"]);const f=Fe(),d=$(t||f.errors,c);if(!d)return null;const{message:g,types:m}=d,h=Object.assign(Object.assign({},r?l:{}),{children:u?u({message:g||s,messages:m}):g||s});return r?i(r)?a(r,h):n(r,h):n(o,Object.assign({},h))};export{Je as Controller,Ke as ErrorMessage,ke as FormContext,qe as useFieldArray,Be as useForm,Fe as useFormContext};
@@ -625,7 +625,8 @@
625
625
  : value;
626
626
  };
627
627
 
628
- var skipValidation = ({ hasError, isBlurEvent, isOnSubmit, isReValidateOnSubmit, isOnBlur, isReValidateOnBlur, isSubmitted, }) => (isOnSubmit && isReValidateOnSubmit) ||
628
+ var skipValidation = ({ isOnChange, hasError, isBlurEvent, isOnSubmit, isReValidateOnSubmit, isOnBlur, isReValidateOnBlur, isSubmitted, }) => (isOnChange && isBlurEvent) ||
629
+ (isOnSubmit && isReValidateOnSubmit) ||
629
630
  (isOnSubmit && !isSubmitted) ||
630
631
  (isOnBlur && !isBlurEvent && !hasError) ||
631
632
  (isReValidateOnBlur && !isBlurEvent && hasError) ||
@@ -714,7 +715,7 @@
714
715
  const validationContextRef = useRef(validationContext);
715
716
  const fieldArrayNamesRef = useRef(new Set());
716
717
  const [, render] = useState();
717
- const { isOnBlur, isOnSubmit } = useRef(modeChecker(mode)).current;
718
+ const { isOnBlur, isOnSubmit, isOnChange } = useRef(modeChecker(mode)).current;
718
719
  const isWindowUndefined = typeof window === UNDEFINED;
719
720
  const shouldValidateCallback = !!(validationSchema || validationResolver);
720
721
  const isWeb = typeof document !== UNDEFINED &&
@@ -910,14 +911,9 @@
910
911
  reRender,
911
912
  shouldValidateCallback,
912
913
  ]);
913
- const isFieldWatched = (name) => {
914
- const preFixName = (name.match(/\w+/) || [])[0];
915
- return (isWatchAllRef.current ||
916
- watchFieldsRef.current.has(name) ||
917
- (watchFieldsRef.current.has(preFixName) &&
918
- !isKey(name) &&
919
- fieldArrayNamesRef.current.has(preFixName)));
920
- };
914
+ const isFieldWatched = (name) => isWatchAllRef.current ||
915
+ watchFieldsRef.current.has(name) ||
916
+ watchFieldsRef.current.has((name.match(/\w+/) || [])[0]);
921
917
  function setValue(names, valueOrShouldValidate, shouldValidate) {
922
918
  let shouldRender = false;
923
919
  const isMultiple = isArray(names);
@@ -954,6 +950,7 @@
954
950
  const isBlurEvent = type === EVENTS.BLUR;
955
951
  const shouldSkipValidation = skipValidation({
956
952
  hasError: !!currentError,
953
+ isOnChange,
957
954
  isBlurEvent,
958
955
  isOnSubmit,
959
956
  isReValidateOnSubmit,
@@ -1237,19 +1234,19 @@
1237
1234
  const resolvedPrevious = await previous;
1238
1235
  const { ref, ref: { name }, } = field;
1239
1236
  if (!fields[name]) {
1240
- return Promise.resolve(resolvedPrevious);
1237
+ return resolvedPrevious;
1241
1238
  }
1242
1239
  const fieldError = await validateField(fieldsRef, validateAllFieldCriteria, field);
1243
1240
  if (fieldError[name]) {
1244
1241
  set(resolvedPrevious.errors, name, fieldError[name]);
1245
1242
  validFieldsRef.current.delete(name);
1246
- return Promise.resolve(resolvedPrevious);
1243
+ return resolvedPrevious;
1247
1244
  }
1248
1245
  if (fieldsWithValidationRef.current.has(name)) {
1249
1246
  validFieldsRef.current.add(name);
1250
1247
  }
1251
1248
  resolvedPrevious.values[name] = getFieldValue(fields, ref);
1252
- return Promise.resolve(resolvedPrevious);
1249
+ return resolvedPrevious;
1253
1250
  }, Promise.resolve({
1254
1251
  errors: {},
1255
1252
  values: {},
@@ -1341,6 +1338,7 @@
1341
1338
  useEffect(() => () => {
1342
1339
  isUnMount.current = true;
1343
1340
  fieldsRef.current &&
1341
+ process.env.NODE_ENV === 'production' &&
1344
1342
  Object.values(fieldsRef.current).forEach((field) => removeFieldEventListenerAndRef(field, true));
1345
1343
  }, [removeFieldEventListenerAndRef]);
1346
1344
  if (!shouldValidateCallback) {
@@ -1368,6 +1366,7 @@
1368
1366
  triggerValidation }, (shouldValidateCallback ? { validateSchemaIsValid } : {})), { formState, mode: {
1369
1367
  isOnBlur,
1370
1368
  isOnSubmit,
1369
+ isOnChange,
1371
1370
  }, reValidateMode: {
1372
1371
  isReValidateOnBlur,
1373
1372
  isReValidateOnSubmit,
@@ -1447,12 +1446,7 @@
1447
1446
 
1448
1447
  const FormGlobalContext = React.createContext(null);
1449
1448
  function useFormContext() {
1450
- const context = React.useContext(FormGlobalContext);
1451
- if (isNullOrUndefined(context)) {
1452
- // eslint-disable-next-line no-console
1453
- console.warn('Missing FormContext');
1454
- }
1455
- return context;
1449
+ return React.useContext(FormGlobalContext);
1456
1450
  }
1457
1451
  function FormContext(_a) {
1458
1452
  var { children, formState, errors } = _a, restMethods = __rest(_a, ["children", "formState", "errors"]);
@@ -1540,14 +1534,14 @@
1540
1534
  const currentFieldsValue = getValues({ nest: true })[name];
1541
1535
  if (isArray(currentFieldsValue)) {
1542
1536
  for (let i = 0; i < currentFieldsValue.length; i++) {
1543
- fields[i] = Object.assign(Object.assign({}, fields[i]), currentFieldsValue[i]);
1537
+ allFields.current[i] = Object.assign(Object.assign({}, allFields.current[i]), currentFieldsValue[i]);
1544
1538
  }
1545
1539
  }
1546
1540
  };
1547
1541
  const append = (value) => {
1548
- mapCurrentFieldsValueWithState();
1549
1542
  if (readFormStateRef.current.dirty) {
1550
1543
  isDirtyRef.current = true;
1544
+ reRender();
1551
1545
  }
1552
1546
  commonTasks([
1553
1547
  ...allFields.current,
@@ -1557,7 +1551,6 @@
1557
1551
  ]);
1558
1552
  };
1559
1553
  const prepend = (value) => {
1560
- mapCurrentFieldsValueWithState();
1561
1554
  resetFields();
1562
1555
  commonTasks(prependAt(allFields.current, isArray(value) ? appendValueWithKey(value) : [appendId(value, keyName)]));
1563
1556
  if (errorsRef.current[name]) {
@@ -1565,9 +1558,11 @@
1565
1558
  }
1566
1559
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1567
1560
  touchedFieldsRef.current[name] = prependAt(touchedFieldsRef.current[name], fillEmptyArray(value));
1561
+ reRender();
1568
1562
  }
1569
1563
  };
1570
1564
  const remove = (index) => {
1565
+ let shouldRender = false;
1571
1566
  if (!isUndefined(index)) {
1572
1567
  mapCurrentFieldsValueWithState();
1573
1568
  }
@@ -1581,6 +1576,7 @@
1581
1576
  }
1582
1577
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1583
1578
  touchedFieldsRef.current[name] = removeArrayAt(touchedFieldsRef.current[name], index);
1579
+ shouldRender = true;
1584
1580
  }
1585
1581
  if (readFormStateRef.current.dirty) {
1586
1582
  dirtyFieldsRef.current.forEach(dirtyField => {
@@ -1588,6 +1584,7 @@
1588
1584
  dirtyFieldsRef.current.delete(dirtyField);
1589
1585
  }
1590
1586
  });
1587
+ shouldRender = true;
1591
1588
  }
1592
1589
  if (readFormStateRef.current.isValid && !validateSchemaIsValid) {
1593
1590
  let fieldIndex = -1;
@@ -1619,6 +1616,9 @@
1619
1616
  }
1620
1617
  }
1621
1618
  }
1619
+ shouldRender = true;
1620
+ }
1621
+ if (shouldRender) {
1622
1622
  reRender();
1623
1623
  }
1624
1624
  };
@@ -1631,6 +1631,7 @@
1631
1631
  }
1632
1632
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1633
1633
  touchedFieldsRef.current[name] = insertAt(touchedFieldsRef.current[name], index, fillEmptyArray(value));
1634
+ reRender();
1634
1635
  }
1635
1636
  };
1636
1637
  const swap = (indexA, indexB) => {
@@ -1645,6 +1646,7 @@
1645
1646
  }
1646
1647
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1647
1648
  swapArrayAt(touchedFieldsRef.current[name], indexA, indexB);
1649
+ reRender();
1648
1650
  }
1649
1651
  };
1650
1652
  const move = (from, to) => {
@@ -1659,6 +1661,7 @@
1659
1661
  }
1660
1662
  if (readFormStateRef.current.touched && touchedFieldsRef.current[name]) {
1661
1663
  moveArrayAt(touchedFieldsRef.current[name], from, to);
1664
+ reRender();
1662
1665
  }
1663
1666
  };
1664
1667
  const reset = () => {
@@ -1701,7 +1704,7 @@
1701
1704
  const Controller = (_a) => {
1702
1705
  var { name, rules, as: InnerComponent, onBlur, onChange, onChangeName = VALIDATION_MODE.onChange, onBlurName = VALIDATION_MODE.onBlur, valueName, defaultValue, control } = _a, rest = __rest(_a, ["name", "rules", "as", "onBlur", "onChange", "onChangeName", "onBlurName", "valueName", "defaultValue", "control"]);
1703
1706
  const methods = useFormContext();
1704
- const { defaultValuesRef, setValue, register, unregister, errorsRef, removeFieldEventListener, triggerValidation, mode: { isOnSubmit, isOnBlur }, reValidateMode: { isReValidateOnBlur, isReValidateOnSubmit }, formState: { isSubmitted }, fieldsRef, fieldArrayNamesRef, } = control || methods.control;
1707
+ const { defaultValuesRef, setValue, register, unregister, errorsRef, removeFieldEventListener, triggerValidation, mode: { isOnSubmit, isOnBlur, isOnChange }, reValidateMode: { isReValidateOnBlur, isReValidateOnSubmit }, formState: { isSubmitted }, fieldsRef, fieldArrayNamesRef, } = control || methods.control;
1705
1708
  const [value, setInputStateValue] = React.useState(isUndefined(defaultValue)
1706
1709
  ? get(defaultValuesRef.current, name)
1707
1710
  : defaultValue);
@@ -1711,6 +1714,7 @@
1711
1714
  hasError: !!get(errorsRef.current, name),
1712
1715
  isOnBlur,
1713
1716
  isOnSubmit,
1717
+ isOnChange,
1714
1718
  isReValidateOnBlur,
1715
1719
  isReValidateOnSubmit,
1716
1720
  isSubmitted,
package/dist/types.d.ts CHANGED
@@ -21,12 +21,20 @@ export declare type SchemaValidateOptions = Partial<{
21
21
  recursive: boolean;
22
22
  context: any;
23
23
  }>;
24
- export declare type ValidationResolverResponse<FormValues> = {
25
- values: FormValues | {};
26
- errors: FieldErrors<FormValues> | {};
24
+ export declare type EmptyObject = {
25
+ [key in string | number]: never;
27
26
  };
28
- export declare type ValidationResolver<FormValues, ValidationContext> = (values: FormValues, validationContext?: ValidationContext) => ValidationResolverResponse<FormValues> | Promise<ValidationResolverResponse<FormValues>>;
29
- export declare type UseFormOptions<FormValues extends FieldValues = FieldValues, ValidationContext = any> = Partial<{
27
+ export declare type SchemaValidationSuccess<FormValues extends FieldValues = FieldValues> = {
28
+ values: FormValues;
29
+ errors: EmptyObject;
30
+ };
31
+ export declare type SchemaValidationError<FormValues extends FieldValues = FieldValues> = {
32
+ values: EmptyObject;
33
+ errors: FieldErrors<FormValues>;
34
+ };
35
+ export declare type SchemaValidationResult<FormValues extends FieldValues = FieldValues> = SchemaValidationSuccess<FormValues> | SchemaValidationError<FormValues>;
36
+ export declare type ValidationResolver<FormValues extends FieldValues = FieldValues, ValidationContext extends object = object> = (values: FormValues, validationContext?: ValidationContext) => SchemaValidationResult<FormValues> | Promise<SchemaValidationResult<FormValues>>;
37
+ export declare type UseFormOptions<FormValues extends FieldValues = FieldValues, ValidationContext extends object = object> = Partial<{
30
38
  mode: Mode;
31
39
  reValidateMode: Mode;
32
40
  defaultValues: DeepPartial<FormValues>;
@@ -76,11 +84,11 @@ export declare type Field = {
76
84
  options?: RadioOrCheckboxOption[];
77
85
  } & ValidationOptions;
78
86
  export declare type FieldRefs<FormValues extends FieldValues> = Partial<Record<FieldName<FormValues>, Field>>;
79
- export declare type NestDataObject<FormValues> = {
80
- [Key in keyof FormValues]?: FormValues[Key] extends Array<infer U> ? 0 extends 1 & U ? any : unknown extends U ? FieldError[] : object extends U ? FieldError[] : U extends Date ? FieldError[] : U extends object ? FieldErrors<U>[] : FieldError[] : 0 extends 1 & FormValues[Key] ? any : unknown extends FormValues[Key] ? FieldError : object extends FormValues[Key] ? FieldError : FormValues[Key] extends Date ? FieldError : FormValues[Key] extends object ? FieldErrors<FormValues[Key]> : FieldError;
87
+ export declare type NestDataObject<FormValues, Value> = {
88
+ [Key in keyof FormValues]?: FormValues[Key] extends Array<infer U> ? 0 extends 1 & U ? any : unknown extends U ? Value[] : object extends U ? Value[] : U extends Date ? Value[] : U extends object ? NestDataObject<U, Value>[] : Value[] : 0 extends 1 & FormValues[Key] ? any : unknown extends FormValues[Key] ? Value : object extends FormValues[Key] ? Value : FormValues[Key] extends Date ? Value : FormValues[Key] extends object ? NestDataObject<FormValues[Key], Value> : Value;
81
89
  };
82
- export declare type FieldErrors<FormValues> = NestDataObject<FormValues>;
83
- export declare type Touched<FormValues> = NestDataObject<FormValues>;
90
+ export declare type FieldErrors<FormValues> = NestDataObject<FormValues, FieldError>;
91
+ export declare type Touched<FormValues> = NestDataObject<FormValues, true>;
84
92
  export declare type SubmitPromiseResult<FormValues extends FieldValues> = {
85
93
  errors: FieldErrors<FormValues>;
86
94
  values: FormValues;
@@ -136,6 +144,7 @@ export declare type Control<FormValues extends FieldValues = FieldValues> = {
136
144
  mode: {
137
145
  isOnBlur: boolean;
138
146
  isOnSubmit: boolean;
147
+ isOnChange: boolean;
139
148
  };
140
149
  reValidateMode: {
141
150
  isReValidateOnBlur: boolean;
package/dist/useForm.d.ts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { FormContextValues } from './contextTypes';
2
2
  import { FieldValues, UseFormOptions } from './types';
3
- export declare function useForm<FormValues extends FieldValues = FieldValues, ValidationContext = any>({ mode, reValidateMode, validationSchema, validationResolver, validationContext, defaultValues, submitFocusError, validateCriteriaMode, }?: UseFormOptions<FormValues, ValidationContext>): FormContextValues<FormValues>;
3
+ export declare function useForm<FormValues extends FieldValues = FieldValues, ValidationContext extends object = object>({ mode, reValidateMode, validationSchema, validationResolver, validationContext, defaultValues, submitFocusError, validateCriteriaMode, }?: UseFormOptions<FormValues, ValidationContext>): FormContextValues<FormValues>;
@@ -1,2 +1,3 @@
1
- declare const _default: (value: unknown) => boolean;
1
+ import { EmptyObject } from './../types';
2
+ declare const _default: (value: unknown) => value is EmptyObject;
2
3
  export default _default;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "react-hook-form",
3
3
  "description": "Performant, flexible and extensible forms library for React Hooks",
4
- "version": "5.1.0",
4
+ "version": "5.1.3",
5
5
  "main": "dist/react-hook-form.js",
6
6
  "module": "dist/react-hook-form.es.js",
7
7
  "types": "dist/index.d.ts",
@@ -43,25 +43,25 @@
43
43
  "license": "MIT",
44
44
  "unpkg": "dist/react-hook-form.umd.js",
45
45
  "devDependencies": {
46
- "@babel/core": "^7.8.6",
46
+ "@babel/core": "^7.8.7",
47
47
  "@babel/plugin-transform-runtime": "^7.8.3",
48
- "@babel/runtime-corejs3": "^7.8.4",
48
+ "@babel/runtime-corejs3": "^7.8.7",
49
49
  "@rollup/plugin-commonjs": "^11.0.2",
50
50
  "@rollup/plugin-node-resolve": "^7.1.1",
51
- "@testing-library/react": "^9.4.1",
51
+ "@testing-library/react": "^10.0.1",
52
52
  "@testing-library/react-hooks": "^3.2.1",
53
- "@types/jest": "^25.1.3",
53
+ "@types/jest": "^25.1.4",
54
54
  "@types/react": "^16.9.23",
55
55
  "@types/react-dom": "^16.9.5",
56
56
  "@types/react-test-renderer": "^16.9.2",
57
- "@typescript-eslint/eslint-plugin": "^2.21.0",
58
- "@typescript-eslint/parser": "^2.21.0",
57
+ "@typescript-eslint/eslint-plugin": "^2.23.0",
58
+ "@typescript-eslint/parser": "^2.23.0",
59
59
  "bundlesize": "^0.18.0",
60
60
  "core-js": "^3.6.4",
61
61
  "coveralls": "^3.0.9",
62
- "cypress": "^4.0.2",
62
+ "cypress": "^4.1.0",
63
63
  "eslint": "^6.8.0",
64
- "eslint-plugin-react": "^7.18.3",
64
+ "eslint-plugin-react": "^7.19.0",
65
65
  "eslint-plugin-react-hooks": "^2.5.0",
66
66
  "husky": "^4.2.3",
67
67
  "jest": "^25.1.0",
@@ -71,12 +71,12 @@
71
71
  "react": "^16.13.0",
72
72
  "react-dom": "^16.13.0",
73
73
  "react-test-renderer": "^16.13.0",
74
- "rollup": "^1.31.1",
75
- "rollup-plugin-babel": "^4.3.3",
74
+ "rollup": "^2.0.6",
75
+ "rollup-plugin-babel": "^4.4.0",
76
76
  "rollup-plugin-terser": "^5.1.1",
77
77
  "rollup-plugin-typescript2": "^0.26.0",
78
78
  "ts-jest": "^25.2.1",
79
- "typescript": "^3.8.2"
79
+ "typescript": "^3.8.3"
80
80
  },
81
81
  "bundlesize": [
82
82
  {