index.esm.mjs 92 KB

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