mobx-react-hook-form 5.9.0 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,10 @@
1
1
  import { BaseSyntheticEvent } from 'react';
2
2
  import { Control, createFormControl, DeepMap, DeepPartial, DefaultValues, FieldErrors, FieldPath, FieldPathValue, FieldValues, FormState, SetValueConfig, UseFormClearErrors, UseFormGetValues, UseFormRegister, UseFormReset, UseFormResetField, UseFormSetError, UseFormSetFocus, UseFormSetValue, UseFormTrigger, UseFormUnregister } from 'react-hook-form';
3
- import { ErrorWithPath, FormParams } from './mobx-form.types.js';
3
+ import { ErrorWithPath, FormParams } from './form.types.js';
4
4
  type FormFullState<TFieldValues extends FieldValues> = FormState<TFieldValues> & {
5
5
  values: TFieldValues;
6
6
  };
7
7
  export declare class Form<TFieldValues extends FieldValues = FieldValues, TContext = any, TTransformedValues = TFieldValues> implements FormFullState<TFieldValues> {
8
- private config;
9
8
  values: TFieldValues;
10
9
  isDirty: boolean;
11
10
  isLoading: boolean;
@@ -279,6 +278,9 @@ export declare class Form<TFieldValues extends FieldValues = FieldValues, TConte
279
278
  */
280
279
  originalForm: ReturnType<typeof createFormControl<TFieldValues, TContext, TTransformedValues>>;
281
280
  private _observableStruct;
281
+ shouldFocusError: boolean;
282
+ private config;
283
+ private forceFormUpdate;
282
284
  constructor(config: FormParams<TFieldValues, TContext, TTransformedValues>);
283
285
  /**
284
286
  * The same as setValue, but will trigger validation if form was submitted, also marks this field as dirty
@@ -329,10 +331,11 @@ export declare class Form<TFieldValues extends FieldValues = FieldValues, TConte
329
331
  private scheduleUpdateFormState;
330
332
  destroy(): void;
331
333
  }
334
+ export declare const createForm: <TFieldValues extends FieldValues = FieldValues, TContext = any, TTransformedValues = TFieldValues>(config: FormParams<TFieldValues, TContext, TTransformedValues>) => Form<TFieldValues, TContext, TTransformedValues>;
332
335
  /**
333
336
  * @deprecated ⚠️ use `Form`. This export will be removed in next major release
334
337
  */
335
338
  export declare class MobxForm<TFieldValues extends FieldValues = FieldValues, TContext = any, TTransformedValues = TFieldValues> extends Form<TFieldValues, TContext, TTransformedValues> {
336
339
  }
337
340
  export {};
338
- //# sourceMappingURL=mobx-form.d.ts.map
341
+ //# sourceMappingURL=form.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"form.d.ts","sourceRoot":"","sources":["../../src/form/form.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAChD,OAAO,EACL,KAAK,OAAO,EACZ,iBAAiB,EACjB,KAAK,OAAO,EACZ,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,WAAW,EAChB,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACtB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACvB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAEjE,KAAK,aAAa,CAAC,YAAY,SAAS,WAAW,IACjD,SAAS,CAAC,YAAY,CAAC,GAAG;IACxB,MAAM,EAAE,YAAY,CAAC;CACtB,CAAC;AAEJ,qBAAa,IAAI,CACf,YAAY,SAAS,WAAW,GAAG,WAAW,EAC9C,QAAQ,GAAG,GAAG,EACd,kBAAkB,GAAG,YAAY,CACjC,YAAW,aAAa,CAAC,YAAY,CAAC;IAEtC,MAAM,EAAE,YAAY,CAAC;IACrB,OAAO,EAAE,OAAO,CAAS;IACzB,SAAS,EAAE,OAAO,CAAS;IAC3B,WAAW,EAAE,OAAO,CAAS;IAC7B,kBAAkB,EAAE,O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sCzE,OAAO,CAAC,eAAe;IAyBvB,SAAS,CAAC,aAAa,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,GAAG,SAAS,CAAC;IAEnE,OAAO,CAAC,4BAA4B,CAKlC;IAEF,OAAO,CAAC,uBAAuB,CAQ7B;IAEF,OAAO,IAAI,IAAI;CAIhB;AAED,eAAO,MAAM,UAAU,GACrB,YAAY,SAAS,WAAW,GAAG,WAAW,EAC9C,QAAQ,GAAG,GAAG,EACd,kBAAkB,GAAG,YAAY,EAEjC,QAAQ,UAAU,CAAC,YAAY,EAAE,QAAQ,EAAE,kBAAkB,CAAC,qDAC3C,CAAC;AAEtB;;GAEG;AACH,qBAAa,QAAQ,CACnB,YAAY,SAAS,WAAW,GAAG,WAAW,EAC9C,QAAQ,GAAG,GAAG,EACd,kBAAkB,GAAG,YAAY,CACjC,SAAQ,IAAI,CAAC,YAAY,EAAE,QAAQ,EAAE,kBAAkB,CAAC;CAAG"}
@@ -1,5 +1,5 @@
1
1
  import { DeepPartial, FieldError, FieldPath, FieldValues, SubmitErrorHandler, SubmitHandler, UseFormProps } from 'react-hook-form';
2
- import { Form } from './mobx-form.js';
2
+ import { Form } from './form.js';
3
3
  export type AnyForm = Form<any, any, any>;
4
4
  /**
5
5
  * @deprecated ⚠️ use `AnyForm`. This export will be removed in next major release
@@ -54,4 +54,4 @@ export interface ErrorWithPath<TFieldValues extends FieldValues = FieldValues, T
54
54
  path: TFieldName;
55
55
  error: FieldError;
56
56
  }
57
- //# sourceMappingURL=mobx-form.types.d.ts.map
57
+ //# sourceMappingURL=form.types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"form.types.d.ts","sourceRoot":"","sources":["../../src/form/form.types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,UAAU,EACV,SAAS,EACT,WAAW,EACX,kBAAkB,EAClB,aAAa,EACb,YAAY,EACb,MAAM,iBAAiB,CAAC;AAEzB,OAAO,KAAK,EAAE,IAAI,EA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SAAS,OAAO,IAAI,CAAC,SAAS,IAAI,CAC1E,GAAG,EACH,GAAG,EACH,MAAM,kBAAkB,CACzB,GACG,kBAAkB,GAClB,KAAK,CAAC;AAEV,MAAM,WAAW,aAAa,CAC5B,YAAY,SAAS,WAAW,GAAG,WAAW,EAC9C,UAAU,SAAS,SAAS,CAAC,YAAY,CAAC,GAAG,SAAS,CAAC,YAAY,CAAC;IAEpE,IAAI,EAAE,UAAU,CAAC;IACjB,KAAK,EAAE,UAAU,CAAC;CACnB"}
@@ -0,0 +1,3 @@
1
+ export * from './form.js';
2
+ export * from './form.types.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/form/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC"}
package/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("mobx-react-lite"),i=require("react-hook-form"),s=require("linked-abort-controller"),r=require("mobx"),o=require("yummies/mobx"),a=require("yummies/type-guard"),l=t=>a.typeGuard.isObject(t)&&"type"in t;class u{constructor(t){this.config=t,this.abortController=new s.LinkedAbortController(t.abortSignal),this.originalForm=i.createFormControl({...t,defaultValues:{...t.defaultValues}});const e=t.defaultValues?{...t.defaultValues}:{};this.setError=r.action((...t)=>(i.set(this.errors,t[0],t[1]),this.originalForm.setError(...t))),this.clearErrors=this.originalForm.clearErrors,this.trigger=this.originalForm.trigger,this.resetField=r.action((...t)=>(i.set(this.values,t[0],i.get(this.defaultValues,t[0])),this.originalForm.resetField(...t))),this.unregister=this.originalForm.unregister,this.control=this.originalForm.control,this.register=this.originalForm.register,this.setFocus=this.originalForm.setFocus,this.setValue=r.action((...t)=>(i.set(this.values,t[0],t[1]),this.originalForm.setValue(...t))),this.getValues=this.originalForm.getValues,this.resetForm=r.action((...t)=>{let e=t[0]??this.defaultValues;return e=r.isObservableObject(e)?r.toJS(e):structuredClone(e),this.values=e,this.originalForm.reset(...t)}),this._observableStruct=new o.DeepObservableStruct({values:this.originalForm.getValues(),errors:{},dirtyFields:{},touchedFields:{},validatingFields:{}}),this.values=this._observableStruct.data.values,this.errors=this._observableStruct.data.errors,this.validatingFields=this._observableStruct.data.validatingFields,this.dirtyFields=this._observableStruct.data.dirtyFields,this.touchedFields=this._observableStruct.data.touchedFields,Object.assign(this,{defaultValues:e});const a=this.originalForm.subscribe({formState:{values:!0,errors:!0,isValid:!0,isDirty:!0,isValidating:!0,dirtyFields:!0,touchedFields:!0,validatingFields:!0},callback:t=>{!1===this.config.lazyUpdates?this.updateFormState(t):this.scheduleUpdateFormState(t)}});r.observable.ref(this,"isDirty"),r.observable.ref(this,"isLoading"),r.observable.ref(this,"isSubmitted"),r.observable.ref(this,"isSubmitSuccessful"),r.observable.ref(this,"isSubmitting"),r.observable.ref(this,"isValidating"),r.observable.ref(this,"isValid"),r.observable.ref(this,"disabled"),r.observable.ref(this,"submitCount"),r.observable.ref(this,"isReady"),r.observable.deep(this,"defaultValues"),r.computed(this,"hasErrors"),r.action(this,"updateFormState"),r.observable.ref(this,"originalForm"),r.action.bound(this,"submit"),r.action.bound(this,"reset"),r.makeObservable(this),this.abortController.signal.addEventListener("abort",()=>{a(),this.originalForm=null})}values;isDirty=!1;isLoading=!1;isSubmitted=!1;isSubmitSuccessful=!1;isSubmitting=!1;isValidating=!1;isValid=!1;disabled=!1;submitCount=0;defaultValues;dirtyFields;touchedFields;validatingFields;errors;isReady=!1;setError;clearErrors;trigger;resetField;unregister;control;register;setFocus;setValue;getValues;resetForm;abortController;originalForm;_observableStruct;changeField=(t,e,i)=>{this.setValue(t,e,{shouldDirty:!0,shouldValidate:this.isSubmitted,...i})};submit(t){return new Promise((e,i)=>{if(!this.originalForm){const t=this.values??{},i=this.config.onSubmit?.(t);return i instanceof Promise?i.then(()=>e(t)):Promise.resolve(t)}this.originalForm.handleSubmit(async(t,s)=>{if(this.config.strictSubmitChecks){const t=this.getErrorsWithPaths(!0)[0];if(t)return this.setFocus(t.path),await(this.config.onSubmitFailed?.(this.errors,s)),void i(this.errors)}await(this.config.onSubmit?.(t,s)),e(t)},async(t,e)=>{await(this.config.onSubmitFailed?.(t,e)),i(t)})(t)})}reset(t){this.resetForm(),this.config.onReset?.(t)}get hasErrors(){return Object.keys(this.errors).length>0}getErrorsWithPaths(t){const e=[],i=(s,r="")=>{s&&"object"==typeof s&&Object.entries(s).forEach(([s,o])=>{const a=r?`${r}.${s}`:s;if(l(o)){if(e.push({path:a,error:o}),t)return}else Array.isArray(o)?o.forEach((s,r)=>{const o=`${a}.${r}`;if(l(s)){if(e.push({path:o,error:s}),t)return}else"object"==typeof s&&i(s,o)}):"object"==typeof o&&i(o,a)})};return i(this.errors),e}updateFormState({values:t,errors:e,dirtyFields:i,validatingFields:s,touchedFields:r,...o}){Object.entries(o).forEach(([t,e])=>{null!=e&&(this[t]=e)}),this._observableStruct.set({dirtyFields:i,errors:e,touchedFields:r,validatingFields:s,values:t})}lastTimeoutId;stopScheduledFormStateUpdate=()=>{void 0!==this.lastTimeoutId&&(clearTimeout(this.lastTimeoutId),this.lastTimeoutId=void 0)};scheduleUpdateFormState=t=>{this.stopScheduledFormStateUpdate(),this.lastTimeoutId=setTimeout(()=>{this.updateFormState(t),this.lastTimeoutId=void 0},this.config.lazyUpdatesTimer??0)};destroy(){this.abortController.abort(),this.stopScheduledFormStateUpdate()}}exports.Controller=s=>t.jsx(i.Controller,{...s,render:i=>t.jsx(e.Observer,{children:()=>s.render(i)})}),exports.Form=u,exports.MobxForm=class extends u{},exports.isFieldError=l;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),e=require("mobx-react-lite"),r=require("react-hook-form"),i=require("linked-abort-controller"),s=require("mobx"),o=require("yummies/mobx"),a=require("yummies/type-guard"),l=t=>a.typeGuard.isObject(t)&&"type"in t;class d{values;isDirty=!1;isLoading=!1;isSubmitted=!1;isSubmitSuccessful=!1;isSubmitting=!1;isValidating=!1;isValid=!1;disabled=!1;submitCount=0;defaultValues;dirtyFields;touchedFields;validatingFields;errors;isReady=!1;setError;clearErrors;trigger;resetField;unregister;control;register;setFocus;setValue;getValues;resetForm;abortController;originalForm;_observableStruct;shouldFocusError;config;forceFormUpdate;constructor(t){this.abortController=new i.LinkedAbortController(t.abortSignal),this.shouldFocusError=t.shouldFocusError??!0,this.forceFormUpdate=!1,this.config={...t,defaultValues:{...t.defaultValues}},Object.defineProperty(this.config,"shouldFocusError",{get(){return this.shouldFocusError}}),this.originalForm=r.createFormControl(this.config);const e=t.defaultValues?{...t.defaultValues}:{};this.setError=(...t)=>(this.forceFormUpdate=!0,this.originalForm.setError(...t)),this.clearErrors=(...t)=>(this.forceFormUpdate=!0,this.originalForm.clearErrors(...t)),this.trigger=this.originalForm.trigger,this.resetField=(...t)=>(this.forceFormUpdate=!0,this.originalForm.resetField(...t)),this.unregister=this.originalForm.unregister,this.control=this.originalForm.control,this.register=this.originalForm.register,this.setFocus=this.originalForm.setFocus,this.setValue=(...t)=>(this.forceFormUpdate=!0,this.originalForm.setValue(...t)),this.getValues=this.originalForm.getValues,this.resetForm=(...t)=>(this.forceFormUpdate=!0,this.originalForm.reset(...t)),this._observableStruct=new o.DeepObservableStruct({values:this.originalForm.getValues(),errors:{},dirtyFields:{},touchedFields:{},validatingFields:{}}),this.values=this._observableStruct.data.values,this.errors=this._observableStruct.data.errors,this.validatingFields=this._observableStruct.data.validatingFields,this.dirtyFields=this._observableStruct.data.dirtyFields,this.touchedFields=this._observableStruct.data.touchedFields,Object.assign(this,{defaultValues:e});const a=this.originalForm.subscribe({formState:{values:!0,errors:!0,isValid:!0,isDirty:!0,isValidating:!0,dirtyFields:!0,touchedFields:!0,validatingFields:!0},callback:t=>{this.forceFormUpdate||!1===this.config.lazyUpdates?(this.forceFormUpdate=!1,this.updateFormState(t)):this.scheduleUpdateFormState(t)}});s.observable.ref(this,"isDirty"),s.observable.ref(this,"isLoading"),s.observable.ref(this,"isSubmitted"),s.observable.ref(this,"isSubmitSuccessful"),s.observable.ref(this,"isSubmitting"),s.observable.ref(this,"isValidating"),s.observable.ref(this,"isValid"),s.observable.ref(this,"disabled"),s.observable.ref(this,"submitCount"),s.observable.ref(this,"isReady"),s.observable.deep(this,"defaultValues"),s.computed(this,"hasErrors"),s.action(this,"updateFormState"),s.observable.ref(this,"originalForm"),s.action.bound(this,"submit"),s.action.bound(this,"reset"),s.makeObservable(this),this.abortController.signal.addEventListener("abort",()=>{a(),this.originalForm=null})}changeField=(t,e,r)=>this.setValue(t,e,{shouldDirty:!0,shouldValidate:this.isSubmitted,...r});submit(t){return new Promise((e,r)=>{if(!this.originalForm){const t=this.values??{},r=this.config.onSubmit?.(t);return r instanceof Promise?r.then(()=>e(t)):Promise.resolve(t)}this.originalForm.handleSubmit(async(t,i)=>{if(this.config.strictSubmitChecks){const t=this.getErrorsWithPaths(!0)[0];if(t)return this.setFocus(t.path),await(this.config.onSubmitFailed?.(this.errors,i)),void r(this.errors)}await(this.config.onSubmit?.(t,i)),e(t)},async(t,e)=>{await(this.config.onSubmitFailed?.(t,e)),r(t)})(t)})}reset(t){this.resetForm(),this.config.onReset?.(t)}get hasErrors(){return Object.keys(this.errors).length>0}getErrorsWithPaths(t){const e=[],r=(i,s="")=>{i&&"object"==typeof i&&Object.entries(i).forEach(([i,o])=>{const a=s?`${s}.${i}`:i;if(l(o)){if(e.push({path:a,error:o}),t)return}else Array.isArray(o)?o.forEach((i,s)=>{const o=`${a}.${s}`;if(l(i)){if(e.push({path:o,error:i}),t)return}else"object"==typeof i&&r(i,o)}):"object"==typeof o&&r(o,a)})};return r(this.errors),e}updateFormState({values:t,errors:e,dirtyFields:r,validatingFields:i,touchedFields:s,...o}){this.stopScheduledFormStateUpdate(),Object.entries(o).forEach(([t,e])=>{null!=e&&(this[t]=e)}),this._observableStruct.set({dirtyFields:r,errors:e,touchedFields:s,validatingFields:i,values:t})}lastTimeoutId;stopScheduledFormStateUpdate=()=>{void 0!==this.lastTimeoutId&&(clearTimeout(this.lastTimeoutId),this.lastTimeoutId=void 0)};scheduleUpdateFormState=t=>{this.stopScheduledFormStateUpdate(),this.lastTimeoutId=setTimeout(()=>{this.updateFormState(t),this.lastTimeoutId=void 0},this.config.lazyUpdatesTimer??0)};destroy(){this.abortController.abort(),this.stopScheduledFormStateUpdate()}}exports.Controller=i=>t.jsx(r.Controller,{...i,render:r=>t.jsx(e.Observer,{children:()=>i.render(r)})}),exports.Form=d,exports.MobxForm=class extends d{},exports.createForm=t=>new d(t),exports.isFieldError=l;
2
2
  //# sourceMappingURL=index.cjs.map
package/index.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/utils/is-field-error.ts","../src/mobx-form/mobx-form.ts","../src/components/controller.tsx"],"sourcesContent":["import type { FieldError } from 'react-hook-form';\nimport { typeGuard } from 'yummies/type-guard';\n\nexport const isFieldError = (value: unknown): value is FieldError => {\n return typeGuard.isObject(value) && 'type' in value;\n};\n","import { LinkedAbortController } from 'linked-abort-controller';\nimport {\n action,\n computed,\n isObservableObject,\n makeObservable,\n observable,\n toJS,\n} from 'mobx';\nimport type { BaseSyntheticEvent } from 'react';\nimport {\n type Control,\n createFormControl,\n type DeepMap,\n type DeepPartial,\n type DefaultValues,\n type FieldErrors,\n type FieldPath,\n type FieldPathValue,\n type FieldValues,\n type FormState,\n get,\n type SetValueConfig,\n set,\n type UseFormClearErrors,\n type UseFormGetValues,\n type UseFormRegister,\n type UseFormReset,\n type UseFormResetField,\n type UseFormSetError,\n type UseFormSetFocus,\n type UseFormSetValue,\n type UseFormTrigger,\n type UseFormUnregister,\n} from 'react-hook-form';\nimport { DeepObservableStruct } from 'yummies/mobx';\nimport { isFieldError } from '../utils/index.js';\nimport type { ErrorWithPath, FormParams } from './mobx-form.types.js';\n\ntype FormFullState<TFieldValues extends FieldValues> =\n FormState<TFieldValues> & {\n values: TFieldValues;\n };\n\nexport class Form<\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n> implements FormFullState<TFieldValues>\n{\n values: TFieldValues;\n isDirty: boolean = false;\n isLoading: boolean = false;\n isSubmitted: boolean = false;\n isSubmitSuccessful: boolean = false;\n isSubmitting: boolean = false;\n isValidating: boolean = false;\n isValid: boolean = false;\n disabled: boolean = false;\n submitCount: number = 0;\n /**\n * If you want to change this property\n * Use {resetForm} method\n */\n defaultValues!: Readonly<DefaultValues<TFieldValues>>;\n dirtyFields: Partial<Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>>;\n touchedFields: Partial<Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>>;\n validatingFields: Partial<\n Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>\n >;\n errors: FieldErrors<TFieldValues>;\n isReady: boolean = false;\n\n /**\n * Set an error for the field. When set an error which is not associated to a field then manual `clearErrors` invoke is required.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/seterror) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-seterror-nfxxu) • [Video](https://www.youtube.com/watch?v=raMqvE0YyIY)\n *\n * @param name - the path name to the form field value.\n * @param error - an error object which contains type and optional message\n * @param options - whether or not to focus on the field\n *\n * @example\n * ```tsx\n * // when the error is not associated with any fields, `clearError` will need to invoke to clear the error\n * const onSubmit = () => setError(\"serverError\", { type: \"server\", message: \"Error occurred\"})\n *\n * <button onClick={() => setError(\"name\", { type: \"min\" })} />\n *\n * // focus on the input after setting the error\n * <button onClick={() => setError(\"name\", { type: \"max\" }, { shouldFocus: true })} />\n * ```\n */\n setError: UseFormSetError<TFieldValues>;\n\n /**\n * Clear the entire form errors.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/clearerrors) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-clearerrors-w3ymx)\n *\n * @param name - the path name to the form field value.\n *\n * @example\n * Clear all errors\n * ```tsx\n * clearErrors(); // clear the entire form error\n * clearErrors([\"name\", \"name1\"]) // clear an array of fields' error\n * clearErrors(\"name2\"); // clear a single field error\n * ```\n */\n clearErrors: UseFormClearErrors<TFieldValues>;\n\n /**\n * Trigger field or form validation\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/trigger) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-triggervalidation-forked-xs7hl) • [Video](https://www.youtube.com/watch?v=-bcyJCDjksE)\n *\n * @param name - provide empty argument will trigger the entire form validation, an array of field names will validate an array of fields, and a single field name will only trigger that field's validation.\n * @param options - should focus on the error field\n *\n * @returns validation result\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * trigger();\n * }, [trigger])\n *\n * <button onClick={async () => {\n * const result = await trigger(); // result will be a boolean value\n * }}>\n * trigger\n * </button>\n * ```\n */\n trigger: UseFormTrigger<TFieldValues>;\n\n /**\n * Reset a field state and reference.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/resetfield) • [Demo](https://codesandbox.io/s/priceless-firefly-d0kuv) • [Video](https://www.youtube.com/watch?v=IdLFcNaEFEo)\n *\n * @param name - the path name to the form field value.\n * @param options - keep form state options\n *\n * @example\n * ```tsx\n * <input {...register(\"firstName\", { required: true })} />\n * <button type=\"button\" onClick={() => resetField(\"firstName\"))}>Reset</button>\n * ```\n */\n resetField: UseFormResetField<TFieldValues>;\n\n /**\n * Unregister a field reference and remove its value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/unregister) • [Demo](https://codesandbox.io/s/react-hook-form-unregister-4k2ey) • [Video](https://www.youtube.com/watch?v=TM99g_NW5Gk&feature=emb_imp_woyt)\n *\n * @param name - the path name to the form field value.\n * @param options - keep form state options\n *\n * @example\n * ```tsx\n * register(\"name\", { required: true })\n *\n * <button onClick={() => unregister(\"name\")} />\n * // there are various keep options to retain formState\n * <button onClick={() => unregister(\"name\", { keepErrors: true })} />\n * ```\n */\n unregister: UseFormUnregister<TFieldValues>;\n\n /**\n * Form control\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/control)\n *\n */\n control: Control<TFieldValues, TContext, TTransformedValues>;\n\n /**\n * Register field into hook form with or without the actual DOM ref. You can invoke register anywhere in the component including at `useEffect`.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/register) • [Demo](https://codesandbox.io/s/react-hook-form-register-ts-ip2j3) • [Video](https://www.youtube.com/watch?v=JFIpCoajYkA)\n *\n * @param name - the path name to the form field value, name is required and unique\n * @param options - register options include validation, disabled, unregister, value as and dependent validation\n *\n * @returns onChange, onBlur, name, ref, and native contribute attribute if browser validation is enabled.\n *\n * @example\n * ```tsx\n * // Register HTML native input\n * <input {...register(\"input\")} />\n * <select {...register(\"select\")} />\n *\n * // Register options\n * <textarea {...register(\"textarea\", { required: \"This is required.\", maxLength: 20 })} />\n * <input type=\"number\" {...register(\"name2\", { valueAsNumber: true })} />\n * <input {...register(\"name3\", { deps: [\"name2\"] })} />\n *\n * // Register custom field at useEffect\n * useEffect(() => {\n * register(\"name4\");\n * register(\"name5\", { value: \"hiddenValue\" });\n * }, [register])\n *\n * // Register without ref\n * const { onChange, onBlur, name } = register(\"name6\")\n * <input onChange={onChange} onBlur={onBlur} name={name} />\n * ```\n */\n register: UseFormRegister<TFieldValues>;\n\n /**\n * Set focus on a registered field. You can start to invoke this method after all fields are mounted to the DOM.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/setfocus) • [Demo](https://codesandbox.io/s/setfocus-rolus)\n *\n * @param name - the path name to the form field value.\n * @param options - input focus behavior options\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * setFocus(\"name\");\n * }, [setFocus])\n * // shouldSelect allows to select input's content on focus\n * <button onClick={() => setFocus(\"name\", { shouldSelect: true })}>Focus</button>\n * ```\n */\n setFocus: UseFormSetFocus<TFieldValues>;\n\n /**\n * Set a single field value, or a group of fields value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/setvalue) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-setvalue-8z9hx) • [Video](https://www.youtube.com/watch?v=qpv51sCH3fI)\n *\n * @param name - the path name to the form field value.\n * @param value - field value\n * @param options - should validate or update form state\n *\n * @example\n * ```tsx\n * // Update a single field\n * setValue('name', 'value', {\n * shouldValidate: true, // trigger validation\n * shouldTouch: true, // update touched fields form state\n * shouldDirty: true, // update dirty and dirty fields form state\n * });\n *\n * // Update a group fields\n * setValue('root', {\n * a: 'test', // setValue('root.a', 'data')\n * b: 'test1', // setValue('root.b', 'data')\n * });\n *\n * // Update a nested object field\n * setValue('select', { label: 'test', value: 'Test' });\n * ```\n */\n setValue: UseFormSetValue<TFieldValues>;\n\n /**\n * Get a single field value, or a group of fields value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/getvalues) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-getvalues-txsfg)\n *\n * @param fieldNames - the path name to the form field value.\n * @param options - returns only dirty fields or return only touchedFields\n *\n * @example\n * ```tsx\n * // Update a single field\n * getValues('name', 'value', {\n * dirtyFields: true, // returns only dirty fields\n * touchedFields: true, // returns only touchedFields\n * });\n *\n * // Get nested values\n * getValues('root.nested.0.value');\n * ```\n */\n getValues: UseFormGetValues<TFieldValues>;\n\n /**\n * Reset at the entire form state.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/reset) • [Demo](https://codesandbox.io/s/react-hook-form-reset-v7-ts-pu901) • [Video](https://www.youtube.com/watch?v=qmCLBjyPwVk)\n *\n * @param values - the entire form values to be reset\n * @param keepStateOptions - keep form state options\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * // reset the entire form after component mount or form defaultValues is ready\n * reset({\n * fieldA: \"test\"\n * fieldB: \"test\"\n * });\n * }, [reset])\n *\n * // reset by combine with existing form values\n * reset({\n * ...getValues(),\n * fieldB: \"test\"\n *});\n *\n * // reset and keep form state\n * reset({\n * ...getValues(),\n *}, {\n * keepErrors: true,\n * keepDirty: true\n *});\n * ```\n */\n resetForm: UseFormReset<TFieldValues>;\n\n protected abortController: AbortController;\n\n /**\n * Original react-hook-form form\n */\n originalForm: ReturnType<\n typeof createFormControl<TFieldValues, TContext, TTransformedValues>\n >;\n\n private _observableStruct: DeepObservableStruct<\n Pick<\n FormFullState<TFieldValues>,\n 'dirtyFields' | 'errors' | 'touchedFields' | 'validatingFields' | 'values'\n >\n >;\n\n constructor(\n private config: FormParams<TFieldValues, TContext, TTransformedValues>,\n ) {\n this.abortController = new LinkedAbortController(config.abortSignal);\n\n this.originalForm = createFormControl<\n TFieldValues,\n TContext,\n TTransformedValues\n >({\n ...config,\n defaultValues: {\n ...config.defaultValues,\n } as DefaultValues<TFieldValues>,\n });\n\n const defaultValues = config.defaultValues\n ? { ...config.defaultValues }\n : ({} as any);\n\n this.setError = action((...args) => {\n set(this.errors, args[0], args[1]);\n return this.originalForm.setError(...args);\n });\n this.clearErrors = this.originalForm.clearErrors;\n this.trigger = this.originalForm.trigger;\n this.resetField = action((...args) => {\n set(this.values, args[0], get(this.defaultValues, args[0]));\n return this.originalForm.resetField(...args);\n });\n this.unregister = this.originalForm.unregister;\n this.control = this.originalForm.control;\n this.register = this.originalForm.register;\n this.setFocus = this.originalForm.setFocus;\n this.setValue = action((...args) => {\n set(this.values, args[0], args[1]);\n return this.originalForm.setValue(...args);\n });\n this.getValues = this.originalForm.getValues;\n this.resetForm = action((...args) => {\n let defaultValues = args[0] ?? this.defaultValues;\n\n if (isObservableObject(defaultValues)) {\n defaultValues = toJS(defaultValues);\n } else {\n defaultValues = structuredClone(defaultValues);\n }\n\n // @ts-expect-error\n this.values = defaultValues;\n return this.originalForm.reset(...args);\n });\n\n this._observableStruct = new DeepObservableStruct({\n values: this.originalForm.getValues(),\n errors: {},\n dirtyFields: {},\n touchedFields: {},\n validatingFields: {},\n });\n\n this.values = this._observableStruct.data.values;\n this.errors = this._observableStruct.data.errors;\n this.validatingFields = this._observableStruct.data.validatingFields;\n this.dirtyFields = this._observableStruct.data.dirtyFields;\n this.touchedFields = this._observableStruct.data.touchedFields;\n\n Object.assign(this, {\n defaultValues,\n });\n\n const subscription = this.originalForm.subscribe({\n formState: {\n values: true,\n errors: true,\n isValid: true,\n isDirty: true,\n isValidating: true,\n dirtyFields: true,\n touchedFields: true,\n validatingFields: true,\n },\n callback: (rawFormState) => {\n if (this.config.lazyUpdates === false) {\n this.updateFormState(rawFormState);\n } else {\n this.scheduleUpdateFormState(rawFormState);\n }\n },\n });\n\n observable.ref(this, 'isDirty');\n observable.ref(this, 'isLoading');\n observable.ref(this, 'isSubmitted');\n observable.ref(this, 'isSubmitSuccessful');\n observable.ref(this, 'isSubmitting');\n observable.ref(this, 'isValidating');\n observable.ref(this, 'isValid');\n observable.ref(this, 'disabled');\n observable.ref(this, 'submitCount');\n observable.ref(this, 'isReady');\n observable.deep(this, 'defaultValues');\n computed(this, 'hasErrors');\n action(this, 'updateFormState');\n\n observable.ref(this, 'originalForm');\n action.bound(this, 'submit');\n action.bound(this, 'reset');\n\n makeObservable(this);\n\n this.abortController.signal.addEventListener('abort', () => {\n subscription();\n // @ts-expect-error\n this.originalForm = null;\n });\n }\n\n /**\n * The same as setValue, but will trigger validation if form was submitted, also marks this field as dirty\n * It should work the same as field.onChange from react-hook-form's Controller\n *\n * @param name - the path name to the form field value.\n * @param value - field value\n * @param options - should validate or update form state\n *\n * @example\n * ```tsx\n * // Update a single field\n * changeField('name', 'value');\n * ->\n * setValue('name', 'value', { shouldDirty: true });\n *\n * ** form submitted **\n *\n * changeField('name', 'value');\n * ->\n * setValue('name', 'value', { shouldDirty: true, shouldValidate: true });\n * ```\n */\n changeField = <\n TFieldName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n >(\n name: TFieldName,\n value: FieldPathValue<TFieldValues, TFieldName> | undefined,\n options?: SetValueConfig,\n ) => {\n this.setValue(name, value as any, {\n shouldDirty: true,\n shouldValidate: this.isSubmitted,\n ...options,\n });\n };\n\n /**\n * Method to manually submit form.\n * Used to attach this method to <form /> element\n *\n * @example\n *\n * <form onSubmit={form.submit} />\n */\n submit(e?: BaseSyntheticEvent) {\n return new Promise<TTransformedValues>((resolve, reject) => {\n if (this.originalForm) {\n this.originalForm.handleSubmit(\n async (data, event) => {\n if (this.config.strictSubmitChecks) {\n const anyErrorWithPath = this.getErrorsWithPaths(true)[0];\n if (anyErrorWithPath) {\n this.setFocus(anyErrorWithPath.path);\n await this.config.onSubmitFailed?.(this.errors, event);\n reject(this.errors);\n return;\n }\n }\n await this.config.onSubmit?.(data, event);\n resolve(data);\n },\n async (errors, event) => {\n await this.config.onSubmitFailed?.(errors, event);\n reject(errors);\n },\n )(e);\n } else {\n const emptyData = (this.values ?? {}) as unknown as TTransformedValues;\n const result = this.config.onSubmit?.(emptyData);\n if (result instanceof Promise) {\n return result.then(() => resolve(emptyData));\n } else {\n return Promise.resolve(emptyData);\n }\n }\n });\n }\n\n /**\n * Method to manually reset all form.\n * Used to attach this method to <form /> element\n *\n * @example\n *\n * <form onReset={form.reset} />\n */\n reset(e?: BaseSyntheticEvent) {\n this.resetForm();\n this.config.onReset?.(e);\n }\n\n get hasErrors() {\n return Object.keys(this.errors).length > 0;\n }\n\n getErrorsWithPaths(getOnlyFirst?: boolean): ErrorWithPath<TFieldValues>[] {\n const result: ErrorWithPath<TFieldValues>[] = [];\n\n const traverse = (obj: any, prefix = '') => {\n if (!obj || typeof obj !== 'object') return;\n\n Object.entries(obj).forEach(([key, value]) => {\n const path = (prefix ? `${prefix}.${key}` : key) as any;\n\n if (isFieldError(value)) {\n result.push({ path, error: value });\n if (getOnlyFirst) {\n return;\n }\n } else if (Array.isArray(value)) {\n value.forEach((item, idx) => {\n const arrayPath = `${path}.${idx}` as any;\n\n if (isFieldError(item)) {\n result.push({ path: arrayPath, error: item });\n if (getOnlyFirst) {\n return;\n }\n } else if (typeof item === 'object') {\n traverse(item, arrayPath);\n }\n });\n } else if (typeof value === 'object') {\n traverse(value, path);\n }\n });\n };\n\n traverse(this.errors);\n\n return result;\n }\n\n private updateFormState({\n values,\n errors,\n dirtyFields,\n validatingFields,\n touchedFields,\n ...simpleProperties\n }: Partial<FormFullState<TFieldValues>>) {\n Object.entries(simpleProperties).forEach(([key, value]) => {\n if (value != null) {\n // @ts-expect-error\n this[key] = value;\n }\n });\n\n this._observableStruct.set({\n dirtyFields,\n errors,\n touchedFields,\n validatingFields,\n values,\n });\n }\n\n protected lastTimeoutId: ReturnType<typeof setTimeout> | undefined;\n\n private stopScheduledFormStateUpdate = () => {\n if (this.lastTimeoutId !== undefined) {\n clearTimeout(this.lastTimeoutId);\n this.lastTimeoutId = undefined;\n }\n };\n\n private scheduleUpdateFormState = (\n rawFormState: Partial<FormFullState<TFieldValues>>,\n ) => {\n this.stopScheduledFormStateUpdate();\n this.lastTimeoutId = setTimeout(() => {\n this.updateFormState(rawFormState);\n this.lastTimeoutId = undefined;\n }, this.config.lazyUpdatesTimer ?? 0);\n };\n\n destroy(): void {\n this.abortController.abort();\n this.stopScheduledFormStateUpdate();\n }\n}\n\n/**\n * @deprecated ⚠️ use `Form`. This export will be removed in next major release\n */\nexport class MobxForm<\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n> extends Form<TFieldValues, TContext, TTransformedValues> {}\n","import { Observer } from 'mobx-react-lite';\nimport { Controller as LibController } from 'react-hook-form';\n\nexport const Controller = ((props: any) => (\n <LibController\n {...props}\n render={(renderProps) => (\n <Observer>{() => props.render(renderProps)}</Observer>\n )}\n />\n)) as unknown as typeof LibController;\n"],"names":["isFieldError","value","typeGuard","isObject","Form","constructor","config","this","abortController","LinkedAbortController","abortSignal","originalForm","createFormControl","defaultValues","setError","action","args","set","errors","clearErrors","trigger","resetField","values","get","unregister","control","register","setFocus","setValue","getValues","resetForm","isObservableObject","toJS","structuredClone","reset","_observableStruct","DeepObservableStruct","dirtyFields","touchedFields","validatingFields","data","Object","assign","subscription","subscribe","formState","isValid","isDirty","isValidating","callback","rawFormState","lazyUpdates","updateFormState","scheduleUpdateFormState","observable","ref","deep","computed","bound","makeObservable","signal","addEventListener","isLoading","isSubmitted","isSubmitSuccessful","isSubmitting","disabled","submitCount","isReady","changeField","name","options","shouldDirty","shouldValidate","submit","e","Promise","resolve","reject","emptyData","result","onSubmit","then","handleSubmit","async","event","strictSubmitChecks","anyErrorWithPath","getErrorsWithPaths","path","onSubmitFailed","onReset","hasErrors","keys","length","getOnlyFirst","traverse","obj","prefix","entries","forEach","key","push","error","Array","isArray","item","idx","arrayPath","simpleProperties","lastTimeoutId","stopScheduledFormStateUpdate","clearTimeout","setTimeout","lazyUpdatesTimer","destroy","abort","props","jsx","LibController","render","renderProps","Observer","children"],"mappings":"gSAGaA,EAAgBC,GACpBC,EAAAA,UAAUC,SAASF,IAAU,SAAUA,ECwCzC,MAAMG,EA+SX,WAAAC,CACUC,GAAAC,KAAAD,OAAAA,EAERC,KAAKC,gBAAkB,IAAIC,wBAAsBH,EAAOI,aAExDH,KAAKI,aAAeC,oBAIlB,IACGN,EACHO,cAAe,IACVP,EAAOO,iBAId,MAAMA,EAAgBP,EAAOO,cACzB,IAAKP,EAAOO,eACX,CAAA,EAELN,KAAKO,SAAWC,SAAO,IAAIC,KACzBC,EAAAA,IAAIV,KAAKW,OAAQF,EAAK,GAAIA,EAAK,IACxBT,KAAKI,aAAaG,YAAYE,KAEvCT,KAAKY,YAAcZ,KAAKI,aAAaQ,YACrCZ,KAAKa,QAAUb,KAAKI,aAAaS,QACjCb,KAAKc,WAAaN,SAAO,IAAIC,KAC3BC,EAAAA,IAAIV,KAAKe,OAAQN,EAAK,GAAIO,MAAIhB,KAAKM,cAAeG,EAAK,KAChDT,KAAKI,aAAaU,cAAcL,KAEzCT,KAAKiB,WAAajB,KAAKI,aAAaa,WACpCjB,KAAKkB,QAAUlB,KAAKI,aAAac,QACjClB,KAAKmB,SAAWnB,KAAKI,aAAae,SAClCnB,KAAKoB,SAAWpB,KAAKI,aAAagB,SAClCpB,KAAKqB,SAAWb,SAAO,IAAIC,KACzBC,EAAAA,I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B,IAAI,CACzBoB,cACAnB,SACAoB,gBACAC,mBACAjB,UAEJ,CAEUwF,cAEFC,6BAA+B,UACV,IAAvBxG,KAAKuG,gBACPE,aAAazG,KAAKuG,eAClBvG,KAAKuG,mBAAgB,IAIjBzD,wBACNH,IAEA3C,KAAKwG,+BACLxG,KAAKuG,cAAgBG,WAAW,KAC9B1G,KAAK6C,gBAAgBF,GACrB3C,KAAKuG,mBAAgB,GACpBvG,KAAKD,OAAO4G,kBAAoB,IAGrC,OAAAC,GACE5G,KAAKC,gBAAgB4G,QACrB7G,KAAKwG,8BACP,qBCjoB0BM,GAC1BC,EAAAA,IAACC,EAAAA,WAAA,IACKF,EACJG,OAASC,GACPH,EAAAA,IAACI,EAAAA,UAAUC,SAAA,IAAMN,EAAMG,OAAOC,uCDmoB7B,cAIGrH"}
1
+ {"version":3,"file":"index.cjs","sources":["../src/utils/is-field-error.ts","../src/form/form.ts","../src/components/controller.tsx"],"sourcesContent":["import type { FieldError } from 'react-hook-form';\nimport { typeGuard } from 'yummies/type-guard';\n\nexport const isFieldError = (value: unknown): value is FieldError => {\n return typeGuard.isObject(value) && 'type' in value;\n};\n","import { LinkedAbortController } from 'linked-abort-controller';\nimport { action, computed, makeObservable, observable } from 'mobx';\nimport type { BaseSyntheticEvent } from 'react';\nimport {\n type Control,\n createFormControl,\n type DeepMap,\n type DeepPartial,\n type DefaultValues,\n type FieldErrors,\n type FieldPath,\n type FieldPathValue,\n type FieldValues,\n type FormState,\n type SetValueConfig,\n type UseFormClearErrors,\n type UseFormGetValues,\n type UseFormRegister,\n type UseFormReset,\n type UseFormResetField,\n type UseFormSetError,\n type UseFormSetFocus,\n type UseFormSetValue,\n type UseFormTrigger,\n type UseFormUnregister,\n} from 'react-hook-form';\nimport { DeepObservableStruct } from 'yummies/mobx';\nimport { isFieldError } from '../utils/index.js';\nimport type { ErrorWithPath, FormParams } from './form.types.js';\n\ntype FormFullState<TFieldValues extends FieldValues> =\n FormState<TFieldValues> & {\n values: TFieldValues;\n };\n\nexport class Form<\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n> implements FormFullState<TFieldValues>\n{\n values: TFieldValues;\n isDirty: boolean = false;\n isLoading: boolean = false;\n isSubmitted: boolean = false;\n isSubmitSuccessful: boolean = false;\n isSubmitting: boolean = false;\n isValidating: boolean = false;\n isValid: boolean = false;\n disabled: boolean = false;\n submitCount: number = 0;\n /**\n * If you want to change this property\n * Use {resetForm} method\n */\n defaultValues!: Readonly<DefaultValues<TFieldValues>>;\n dirtyFields: Partial<Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>>;\n touchedFields: Partial<Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>>;\n validatingFields: Partial<\n Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>\n >;\n errors: FieldErrors<TFieldValues>;\n isReady: boolean = false;\n\n /**\n * Set an error for the field. When set an error which is not associated to a field then manual `clearErrors` invoke is required.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/seterror) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-seterror-nfxxu) • [Video](https://www.youtube.com/watch?v=raMqvE0YyIY)\n *\n * @param name - the path name to the form field value.\n * @param error - an error object which contains type and optional message\n * @param options - whether or not to focus on the field\n *\n * @example\n * ```tsx\n * // when the error is not associated with any fields, `clearError` will need to invoke to clear the error\n * const onSubmit = () => setError(\"serverError\", { type: \"server\", message: \"Error occurred\"})\n *\n * <button onClick={() => setError(\"name\", { type: \"min\" })} />\n *\n * // focus on the input after setting the error\n * <button onClick={() => setError(\"name\", { type: \"max\" }, { shouldFocus: true })} />\n * ```\n */\n setError: UseFormSetError<TFieldValues>;\n\n /**\n * Clear the entire form errors.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/clearerrors) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-clearerrors-w3ymx)\n *\n * @param name - the path name to the form field value.\n *\n * @example\n * Clear all errors\n * ```tsx\n * clearErrors(); // clear the entire form error\n * clearErrors([\"name\", \"name1\"]) // clear an array of fields' error\n * clearErrors(\"name2\"); // clear a single field error\n * ```\n */\n clearErrors: UseFormClearErrors<TFieldValues>;\n\n /**\n * Trigger field or form validation\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/trigger) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-triggervalidation-forked-xs7hl) • [Video](https://www.youtube.com/watch?v=-bcyJCDjksE)\n *\n * @param name - provide empty argument will trigger the entire form validation, an array of field names will validate an array of fields, and a single field name will only trigger that field's validation.\n * @param options - should focus on the error field\n *\n * @returns validation result\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * trigger();\n * }, [trigger])\n *\n * <button onClick={async () => {\n * const result = await trigger(); // result will be a boolean value\n * }}>\n * trigger\n * </button>\n * ```\n */\n trigger: UseFormTrigger<TFieldValues>;\n\n /**\n * Reset a field state and reference.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/resetfield) • [Demo](https://codesandbox.io/s/priceless-firefly-d0kuv) • [Video](https://www.youtube.com/watch?v=IdLFcNaEFEo)\n *\n * @param name - the path name to the form field value.\n * @param options - keep form state options\n *\n * @example\n * ```tsx\n * <input {...register(\"firstName\", { required: true })} />\n * <button type=\"button\" onClick={() => resetField(\"firstName\"))}>Reset</button>\n * ```\n */\n resetField: UseFormResetField<TFieldValues>;\n\n /**\n * Unregister a field reference and remove its value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/unregister) • [Demo](https://codesandbox.io/s/react-hook-form-unregister-4k2ey) • [Video](https://www.youtube.com/watch?v=TM99g_NW5Gk&feature=emb_imp_woyt)\n *\n * @param name - the path name to the form field value.\n * @param options - keep form state options\n *\n * @example\n * ```tsx\n * register(\"name\", { required: true })\n *\n * <button onClick={() => unregister(\"name\")} />\n * // there are various keep options to retain formState\n * <button onClick={() => unregister(\"name\", { keepErrors: true })} />\n * ```\n */\n unregister: UseFormUnregister<TFieldValues>;\n\n /**\n * Form control\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/control)\n *\n */\n control: Control<TFieldValues, TContext, TTransformedValues>;\n\n /**\n * Register field into hook form with or without the actual DOM ref. You can invoke register anywhere in the component including at `useEffect`.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/register) • [Demo](https://codesandbox.io/s/react-hook-form-register-ts-ip2j3) • [Video](https://www.youtube.com/watch?v=JFIpCoajYkA)\n *\n * @param name - the path name to the form field value, name is required and unique\n * @param options - register options include validation, disabled, unregister, value as and dependent validation\n *\n * @returns onChange, onBlur, name, ref, and native contribute attribute if browser validation is enabled.\n *\n * @example\n * ```tsx\n * // Register HTML native input\n * <input {...register(\"input\")} />\n * <select {...register(\"select\")} />\n *\n * // Register options\n * <textarea {...register(\"textarea\", { required: \"This is required.\", maxLength: 20 })} />\n * <input type=\"number\" {...register(\"name2\", { valueAsNumber: true })} />\n * <input {...register(\"name3\", { deps: [\"name2\"] })} />\n *\n * // Register custom field at useEffect\n * useEffect(() => {\n * register(\"name4\");\n * register(\"name5\", { value: \"hiddenValue\" });\n * }, [register])\n *\n * // Register without ref\n * const { onChange, onBlur, name } = register(\"name6\")\n * <input onChange={onChange} onBlur={onBlur} name={name} />\n * ```\n */\n register: UseFormRegister<TFieldValues>;\n\n /**\n * Set focus on a registered field. You can start to invoke this method after all fields are mounted to the DOM.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/setfocus) • [Demo](https://codesandbox.io/s/setfocus-rolus)\n *\n * @param name - the path name to the form field value.\n * @param options - input focus behavior options\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * setFocus(\"name\");\n * }, [setFocus])\n * // shouldSelect allows to select input's content on focus\n * <button onClick={() => setFocus(\"name\", { shouldSelect: true })}>Focus</button>\n * ```\n */\n setFocus: UseFormSetFocus<TFieldValues>;\n\n /**\n * Set a single field value, or a group of fields value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/setvalue) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-setvalue-8z9hx) • [Video](https://www.youtube.com/watch?v=qpv51sCH3fI)\n *\n * @param name - the path name to the form field value.\n * @param value - field value\n * @param options - should validate or update form state\n *\n * @example\n * ```tsx\n * // Update a single field\n * setValue('name', 'value', {\n * shouldValidate: true, // trigger validation\n * shouldTouch: true, // update touched fields form state\n * shouldDirty: true, // update dirty and dirty fields form state\n * });\n *\n * // Update a group fields\n * setValue('root', {\n * a: 'test', // setValue('root.a', 'data')\n * b: 'test1', // setValue('root.b', 'data')\n * });\n *\n * // Update a nested object field\n * setValue('select', { label: 'test', value: 'Test' });\n * ```\n */\n setValue: UseFormSetValue<TFieldValues>;\n\n /**\n * Get a single field value, or a group of fields value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/getvalues) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-getvalues-txsfg)\n *\n * @param fieldNames - the path name to the form field value.\n * @param options - returns only dirty fields or return only touchedFields\n *\n * @example\n * ```tsx\n * // Update a single field\n * getValues('name', 'value', {\n * dirtyFields: true, // returns only dirty fields\n * touchedFields: true, // returns only touchedFields\n * });\n *\n * // Get nested values\n * getValues('root.nested.0.value');\n * ```\n */\n getValues: UseFormGetValues<TFieldValues>;\n\n /**\n * Reset at the entire form state.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/reset) • [Demo](https://codesandbox.io/s/react-hook-form-reset-v7-ts-pu901) • [Video](https://www.youtube.com/watch?v=qmCLBjyPwVk)\n *\n * @param values - the entire form values to be reset\n * @param keepStateOptions - keep form state options\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * // reset the entire form after component mount or form defaultValues is ready\n * reset({\n * fieldA: \"test\"\n * fieldB: \"test\"\n * });\n * }, [reset])\n *\n * // reset by combine with existing form values\n * reset({\n * ...getValues(),\n * fieldB: \"test\"\n *});\n *\n * // reset and keep form state\n * reset({\n * ...getValues(),\n *}, {\n * keepErrors: true,\n * keepDirty: true\n *});\n * ```\n */\n resetForm: UseFormReset<TFieldValues>;\n\n protected abortController: AbortController;\n\n /**\n * Original react-hook-form form\n */\n originalForm: ReturnType<\n typeof createFormControl<TFieldValues, TContext, TTransformedValues>\n >;\n\n private _observableStruct: DeepObservableStruct<\n Pick<\n FormFullState<TFieldValues>,\n 'dirtyFields' | 'errors' | 'touchedFields' | 'validatingFields' | 'values'\n >\n >;\n\n shouldFocusError: boolean;\n\n private config: FormParams<TFieldValues, TContext, TTransformedValues>;\n\n // special hack to apply the same form value changes from the original form\n // using subscription\n private forceFormUpdate: boolean;\n\n constructor(config: FormParams<TFieldValues, TContext, TTransformedValues>) {\n this.abortController = new LinkedAbortController(config.abortSignal);\n\n this.shouldFocusError = config.shouldFocusError ?? true;\n this.forceFormUpdate = false;\n\n this.config = {\n ...config,\n defaultValues: {\n ...config.defaultValues,\n } as DefaultValues<TFieldValues>,\n };\n\n Object.defineProperty(this.config, 'shouldFocusError', {\n get() {\n return this.shouldFocusError;\n },\n });\n\n this.originalForm = createFormControl<\n TFieldValues,\n TContext,\n TTransformedValues\n >(this.config as any);\n\n const defaultValues = config.defaultValues\n ? { ...config.defaultValues }\n : ({} as any);\n\n this.setError = (...args) => {\n this.forceFormUpdate = true;\n return this.originalForm.setError(...args);\n };\n this.clearErrors = (...args) => {\n this.forceFormUpdate = true;\n return this.originalForm.clearErrors(...args);\n };\n this.trigger = this.originalForm.trigger;\n this.resetField = (...args) => {\n this.forceFormUpdate = true;\n return this.originalForm.resetField(...args);\n };\n this.unregister = this.originalForm.unregister;\n this.control = this.originalForm.control;\n this.register = this.originalForm.register;\n this.setFocus = this.originalForm.setFocus;\n this.setValue = (...args) => {\n this.forceFormUpdate = true;\n return this.originalForm.setValue(...args);\n };\n this.getValues = this.originalForm.getValues;\n this.resetForm = (...args) => {\n this.forceFormUpdate = true;\n return this.originalForm.reset(...args);\n };\n\n this._observableStruct = new DeepObservableStruct({\n values: this.originalForm.getValues(),\n errors: {},\n dirtyFields: {},\n touchedFields: {},\n validatingFields: {},\n });\n\n this.values = this._observableStruct.data.values;\n this.errors = this._observableStruct.data.errors;\n this.validatingFields = this._observableStruct.data.validatingFields;\n this.dirtyFields = this._observableStruct.data.dirtyFields;\n this.touchedFields = this._observableStruct.data.touchedFields;\n\n Object.assign(this, {\n defaultValues,\n });\n\n const subscription = this.originalForm.subscribe({\n formState: {\n values: true,\n errors: true,\n isValid: true,\n isDirty: true,\n isValidating: true,\n dirtyFields: true,\n touchedFields: true,\n validatingFields: true,\n },\n callback: (rawFormState) => {\n if (this.forceFormUpdate || this.config.lazyUpdates === false) {\n this.forceFormUpdate = false;\n this.updateFormState(rawFormState);\n } else {\n this.scheduleUpdateFormState(rawFormState);\n }\n },\n });\n\n observable.ref(this, 'isDirty');\n observable.ref(this, 'isLoading');\n observable.ref(this, 'isSubmitted');\n observable.ref(this, 'isSubmitSuccessful');\n observable.ref(this, 'isSubmitting');\n observable.ref(this, 'isValidating');\n observable.ref(this, 'isValid');\n observable.ref(this, 'disabled');\n observable.ref(this, 'submitCount');\n observable.ref(this, 'isReady');\n observable.deep(this, 'defaultValues');\n computed(this, 'hasErrors');\n action(this, 'updateFormState');\n\n observable.ref(this, 'originalForm');\n action.bound(this, 'submit');\n action.bound(this, 'reset');\n\n makeObservable(this);\n\n this.abortController.signal.addEventListener('abort', () => {\n subscription();\n // @ts-expect-error\n this.originalForm = null;\n });\n }\n\n /**\n * The same as setValue, but will trigger validation if form was submitted, also marks this field as dirty\n * It should work the same as field.onChange from react-hook-form's Controller\n *\n * @param name - the path name to the form field value.\n * @param value - field value\n * @param options - should validate or update form state\n *\n * @example\n * ```tsx\n * // Update a single field\n * changeField('name', 'value');\n * ->\n * setValue('name', 'value', { shouldDirty: true });\n *\n * ** form submitted **\n *\n * changeField('name', 'value');\n * ->\n * setValue('name', 'value', { shouldDirty: true, shouldValidate: true });\n * ```\n */\n changeField = <\n TFieldName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n >(\n name: TFieldName,\n value: FieldPathValue<TFieldValues, TFieldName> | undefined,\n options?: SetValueConfig,\n ) => {\n return this.setValue(name, value as any, {\n shouldDirty: true,\n shouldValidate: this.isSubmitted,\n ...options,\n });\n };\n\n /**\n * Method to manually submit form.\n * Used to attach this method to <form /> element\n *\n * @example\n *\n * <form onSubmit={form.submit} />\n */\n submit(e?: BaseSyntheticEvent) {\n return new Promise<TTransformedValues>((resolve, reject) => {\n if (this.originalForm) {\n this.originalForm.handleSubmit(\n async (data, event) => {\n if (this.config.strictSubmitChecks) {\n const anyErrorWithPath = this.getErrorsWithPaths(true)[0];\n if (anyErrorWithPath) {\n this.setFocus(anyErrorWithPath.path);\n await this.config.onSubmitFailed?.(this.errors, event);\n reject(this.errors);\n return;\n }\n }\n await this.config.onSubmit?.(data, event);\n resolve(data);\n },\n async (errors, event) => {\n await this.config.onSubmitFailed?.(errors, event);\n reject(errors);\n },\n )(e);\n } else {\n const emptyData = (this.values ?? {}) as unknown as TTransformedValues;\n const result = this.config.onSubmit?.(emptyData);\n if (result instanceof Promise) {\n return result.then(() => resolve(emptyData));\n } else {\n return Promise.resolve(emptyData);\n }\n }\n });\n }\n\n /**\n * Method to manually reset all form.\n * Used to attach this method to <form /> element\n *\n * @example\n *\n * <form onReset={form.reset} />\n */\n reset(e?: BaseSyntheticEvent) {\n this.resetForm();\n this.config.onReset?.(e);\n }\n\n get hasErrors() {\n return Object.keys(this.errors).length > 0;\n }\n\n getErrorsWithPaths(getOnlyFirst?: boolean): ErrorWithPath<TFieldValues>[] {\n const result: ErrorWithPath<TFieldValues>[] = [];\n\n const traverse = (obj: any, prefix = '') => {\n if (!obj || typeof obj !== 'object') return;\n\n Object.entries(obj).forEach(([key, value]) => {\n const path = (prefix ? `${prefix}.${key}` : key) as any;\n\n if (isFieldError(value)) {\n result.push({ path, error: value });\n if (getOnlyFirst) {\n return;\n }\n } else if (Array.isArray(value)) {\n value.forEach((item, idx) => {\n const arrayPath = `${path}.${idx}` as any;\n\n if (isFieldError(item)) {\n result.push({ path: arrayPath, error: item });\n if (getOnlyFirst) {\n return;\n }\n } else if (typeof item === 'object') {\n traverse(item, arrayPath);\n }\n });\n } else if (typeof value === 'object') {\n traverse(value, path);\n }\n });\n };\n\n traverse(this.errors);\n\n return result;\n }\n\n private updateFormState({\n values,\n errors,\n dirtyFields,\n validatingFields,\n touchedFields,\n ...simpleProperties\n }: Partial<FormFullState<TFieldValues>>) {\n this.stopScheduledFormStateUpdate();\n Object.entries(simpleProperties).forEach(([key, value]) => {\n if (value != null) {\n // @ts-expect-error\n this[key] = value;\n }\n });\n\n this._observableStruct.set({\n dirtyFields,\n errors,\n touchedFields,\n validatingFields,\n values,\n });\n }\n\n protected lastTimeoutId: ReturnType<typeof setTimeout> | undefined;\n\n private stopScheduledFormStateUpdate = () => {\n if (this.lastTimeoutId !== undefined) {\n clearTimeout(this.lastTimeoutId);\n this.lastTimeoutId = undefined;\n }\n };\n\n private scheduleUpdateFormState = (\n rawFormState: Partial<FormFullState<TFieldValues>>,\n ) => {\n this.stopScheduledFormStateUpdate();\n this.lastTimeoutId = setTimeout(() => {\n this.updateFormState(rawFormState);\n this.lastTimeoutId = undefined;\n }, this.config.lazyUpdatesTimer ?? 0);\n };\n\n destroy(): void {\n this.abortController.abort();\n this.stopScheduledFormStateUpdate();\n }\n}\n\nexport const createForm = <\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n>(\n config: FormParams<TFieldValues, TContext, TTransformedValues>,\n) => new Form(config);\n\n/**\n * @deprecated ⚠️ use `Form`. This export will be removed in next major release\n */\nexport class MobxForm<\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n> extends Form<TFieldValues, TContext, TTransformedValues> {}\n","import { Observer } from 'mobx-react-lite';\nimport { Controller as LibController } from 'react-hook-form';\n\nexport const Controller = ((props: any) => (\n <LibController\n {...props}\n render={(renderProps) => (\n <Observer>{() => props.render(renderProps)}</Observer>\n )}\n />\n)) as unknown as typeof LibController;\n"],"names":["isFieldError","value","typeGuard","isObject","Form","values","isDirty","isLoading","isSubmitted","isSubmitSuccessful","isSubmitting","isValidating","isValid","disabled","submitCount","defaultValues","dirtyFields","touchedFields","validatingFields","errors","isReady","setError","clearErrors","trigger","resetField","unregister","control","register","setFocus","setValue","getValues","resetForm","abortController","originalForm","_observableStruct","shouldFocusError","config","forceFormUpdate","constructor","this","LinkedAbortController","abortSignal","Object","defineProperty","get","createFormControl","args","reset","DeepObservableStruct","data","assign","subscription","subscribe","formState","callback","rawFormState","lazyUpdates","updateFormState","scheduleUpdateFormState","observable","ref","deep","computed","action","bound","makeObservable","signal","addEventListener","changeField","name","options","shouldDirty","shouldValidate","submit","e","Promise","resolve","reject","emptyData","result","onSubmit","then","handleSubmit","async","event","strictSubmitChecks","anyErrorWithPath","getErrorsWithPaths","path","onSubmitFailed","onReset","hasErrors","keys","length","getOnlyFirst","traverse","obj","prefix","entries","forEach","key","push","error","Array","isArray","item","idx","arrayPath","simpleProperties","stopScheduledFormStateUpdate","set","lastTimeoutId","clearTimeout","setTimeout","lazyUpdatesTimer","destroy","abort","props","jsx","LibController","render","renderProps","Observer","children"],"mappings":"gSAGaA,EAAgBC,GACpBC,EAAAA,UAAUC,SAASF,IAAU,SAAUA,EC+BzC,MAAMG,EAMXC,OACAC,SAAmB,EACnBC,WAAqB,EACrBC,aAAuB,EACvBC,oBAA8B,EAC9BC,cAAwB,EACxBC,cAAwB,EACxBC,SAAmB,EACnBC,UAAoB,EACpBC,YAAsB,EAKtBC,cACAC,YACAC,cACAC,iBAGAC,OACAC,SAAmB,EAuBnBC,SAkBAC,YA0BAC,QAiBAC,WAoBAC,WASAC,QAmCAC,SAoBAC,SA+BAC,SAuBAC,UAoCAC,UAEUC,gBAKVC,aAIQC,kBAORC,iBAEQC,OAIAC,gBAER,WAAAC,CAAYF,GACVG,KAAKP,gBAAkB,IAAIQ,wBAAsBJ,EAAOK,aAExDF,KAAKJ,iBAAmBC,EAAOD,mBAAoB,EACnDI,KAAKF,iBAAkB,EAEvBE,KAA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AChB8F,EAAS9F,EAAOuF,MAOtB,OAFAO,EAASxD,KAAKpB,QAEP4D,CACT,CAEQ,eAAAtB,EAAgBpD,OACtBA,EAAAc,OACAA,EAAAH,YACAA,EAAAE,iBACAA,EAAAD,cACAA,KACG2F,IAEHrE,KAAKsE,+BACLnE,OAAOwD,QAAQU,GAAkBT,QAAQ,EAAEC,EAAKnG,MACjC,MAATA,IAEFsC,KAAK6D,GAAOnG,KAIhBsC,KAAKL,kBAAkB4E,IAAI,CACzB9F,cACAG,SACAF,gBACAC,mBACAb,UAEJ,CAEU0G,cAEFF,6BAA+B,UACV,IAAvBtE,KAAKwE,gBACPC,aAAazE,KAAKwE,eAClBxE,KAAKwE,mBAAgB,IAIjBrD,wBACNH,IAEAhB,KAAKsE,+BACLtE,KAAKwE,cAAgBE,WAAW,KAC9B1E,KAAKkB,gBAAgBF,GACrBhB,KAAKwE,mBAAgB,GACpBxE,KAAKH,OAAO8E,kBAAoB,IAGrC,OAAAC,GACE5E,KAAKP,gBAAgBoF,QACrB7E,KAAKsE,8BACP,qBCroB0BQ,GAC1BC,EAAAA,IAACC,EAAAA,WAAA,IACKF,EACJG,OAASC,GACPH,EAAAA,IAACI,EAAAA,UAAUC,SAAA,IAAMN,EAAMG,OAAOC,uCD+oB7B,cAIGrH,uBAVRgC,GACG,IAAIhC,EAAKgC"}
package/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  export * from './components/index.js';
2
- export * from './mobx-form/index.js';
2
+ export * from './form/index.js';
3
3
  export * from './utils/index.js';
4
4
  //# sourceMappingURL=index.d.ts.map
package/index.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,sBAAsB,CAAC;AACrC,cAAc,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC"}
package/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { jsx } from "react/jsx-runtime";
2
2
  import { Observer } from "mobx-react-lite";
3
- import { Controller as Controller$1, createFormControl, set, get } from "react-hook-form";
3
+ import { Controller as Controller$1, createFormControl } from "react-hook-form";
4
4
  import { LinkedAbortController } from "linked-abort-controller";
5
- import { action, isObservableObject, toJS, observable, computed, makeObservable } from "mobx";
5
+ import { observable, computed, action, makeObservable } from "mobx";
6
6
  import { DeepObservableStruct } from "yummies/mobx";
7
7
  import { typeGuard } from "yummies/type-guard";
8
8
  const Controller = ((props) => /* @__PURE__ */ jsx(
@@ -16,101 +16,6 @@ const isFieldError = (value) => {
16
16
  return typeGuard.isObject(value) && "type" in value;
17
17
  };
18
18
  class Form {
19
- constructor(config) {
20
- this.config = config;
21
- this.abortController = new LinkedAbortController(config.abortSignal);
22
- this.originalForm = createFormControl({
23
- ...config,
24
- defaultValues: {
25
- ...config.defaultValues
26
- }
27
- });
28
- const defaultValues = config.defaultValues ? { ...config.defaultValues } : {};
29
- this.setError = action((...args) => {
30
- set(this.errors, args[0], args[1]);
31
- return this.originalForm.setError(...args);
32
- });
33
- this.clearErrors = this.originalForm.clearErrors;
34
- this.trigger = this.originalForm.trigger;
35
- this.resetField = action((...args) => {
36
- set(this.values, args[0], get(this.defaultValues, args[0]));
37
- return this.originalForm.resetField(...args);
38
- });
39
- this.unregister = this.originalForm.unregister;
40
- this.control = this.originalForm.control;
41
- this.register = this.originalForm.register;
42
- this.setFocus = this.originalForm.setFocus;
43
- this.setValue = action((...args) => {
44
- set(this.values, args[0], args[1]);
45
- return this.originalForm.setValue(...args);
46
- });
47
- this.getValues = this.originalForm.getValues;
48
- this.resetForm = action((...args) => {
49
- let defaultValues2 = args[0] ?? this.defaultValues;
50
- if (isObservableObject(defaultValues2)) {
51
- defaultValues2 = toJS(defaultValues2);
52
- } else {
53
- defaultValues2 = structuredClone(defaultValues2);
54
- }
55
- this.values = defaultValues2;
56
- return this.originalForm.reset(...args);
57
- });
58
- this._observableStruct = new DeepObservableStruct({
59
- values: this.originalForm.getValues(),
60
- errors: {},
61
- dirtyFields: {},
62
- touchedFields: {},
63
- validatingFields: {}
64
- });
65
- this.values = this._observableStruct.data.values;
66
- this.errors = this._observableStruct.data.errors;
67
- this.validatingFields = this._observableStruct.data.validatingFields;
68
- this.dirtyFields = this._observableStruct.data.dirtyFields;
69
- this.touchedFields = this._observableStruct.data.touchedFields;
70
- Object.assign(this, {
71
- defaultValues
72
- });
73
- const subscription = this.originalForm.subscribe({
74
- formState: {
75
- values: true,
76
- errors: true,
77
- isValid: true,
78
- isDirty: true,
79
- isValidating: true,
80
- dirtyFields: true,
81
- touchedFields: true,
82
- validatingFields: true
83
- },
84
- callback: (rawFormState) => {
85
- if (this.config.lazyUpdates === false) {
86
- this.updateFormState(rawFormState);
87
- } else {
88
- this.scheduleUpdateFormState(rawFormState);
89
- }
90
- }
91
- });
92
- observable.ref(this, "isDirty");
93
- observable.ref(this, "isLoading");
94
- observable.ref(this, "isSubmitted");
95
- observable.ref(this, "isSubmitSuccessful");
96
- observable.ref(this, "isSubmitting");
97
- observable.ref(this, "isValidating");
98
- observable.ref(this, "isValid");
99
- observable.ref(this, "disabled");
100
- observable.ref(this, "submitCount");
101
- observable.ref(this, "isReady");
102
- observable.deep(this, "defaultValues");
103
- computed(this, "hasErrors");
104
- action(this, "updateFormState");
105
- observable.ref(this, "originalForm");
106
- action.bound(this, "submit");
107
- action.bound(this, "reset");
108
- makeObservable(this);
109
- this.abortController.signal.addEventListener("abort", () => {
110
- subscription();
111
- this.originalForm = null;
112
- });
113
- }
114
19
  values;
115
20
  isDirty = false;
116
21
  isLoading = false;
@@ -384,6 +289,111 @@ class Form {
384
289
  */
385
290
  originalForm;
386
291
  _observableStruct;
292
+ shouldFocusError;
293
+ config;
294
+ // special hack to apply the same form value changes from the original form
295
+ // using subscription
296
+ forceFormUpdate;
297
+ constructor(config) {
298
+ this.abortController = new LinkedAbortController(config.abortSignal);
299
+ this.shouldFocusError = config.shouldFocusError ?? true;
300
+ this.forceFormUpdate = false;
301
+ this.config = {
302
+ ...config,
303
+ defaultValues: {
304
+ ...config.defaultValues
305
+ }
306
+ };
307
+ Object.defineProperty(this.config, "shouldFocusError", {
308
+ get() {
309
+ return this.shouldFocusError;
310
+ }
311
+ });
312
+ this.originalForm = createFormControl(this.config);
313
+ const defaultValues = config.defaultValues ? { ...config.defaultValues } : {};
314
+ this.setError = (...args) => {
315
+ this.forceFormUpdate = true;
316
+ return this.originalForm.setError(...args);
317
+ };
318
+ this.clearErrors = (...args) => {
319
+ this.forceFormUpdate = true;
320
+ return this.originalForm.clearErrors(...args);
321
+ };
322
+ this.trigger = this.originalForm.trigger;
323
+ this.resetField = (...args) => {
324
+ this.forceFormUpdate = true;
325
+ return this.originalForm.resetField(...args);
326
+ };
327
+ this.unregister = this.originalForm.unregister;
328
+ this.control = this.originalForm.control;
329
+ this.register = this.originalForm.register;
330
+ this.setFocus = this.originalForm.setFocus;
331
+ this.setValue = (...args) => {
332
+ this.forceFormUpdate = true;
333
+ return this.originalForm.setValue(...args);
334
+ };
335
+ this.getValues = this.originalForm.getValues;
336
+ this.resetForm = (...args) => {
337
+ this.forceFormUpdate = true;
338
+ return this.originalForm.reset(...args);
339
+ };
340
+ this._observableStruct = new DeepObservableStruct({
341
+ values: this.originalForm.getValues(),
342
+ errors: {},
343
+ dirtyFields: {},
344
+ touchedFields: {},
345
+ validatingFields: {}
346
+ });
347
+ this.values = this._observableStruct.data.values;
348
+ this.errors = this._observableStruct.data.errors;
349
+ this.validatingFields = this._observableStruct.data.validatingFields;
350
+ this.dirtyFields = this._observableStruct.data.dirtyFields;
351
+ this.touchedFields = this._observableStruct.data.touchedFields;
352
+ Object.assign(this, {
353
+ defaultValues
354
+ });
355
+ const subscription = this.originalForm.subscribe({
356
+ formState: {
357
+ values: true,
358
+ errors: true,
359
+ isValid: true,
360
+ isDirty: true,
361
+ isValidating: true,
362
+ dirtyFields: true,
363
+ touchedFields: true,
364
+ validatingFields: true
365
+ },
366
+ callback: (rawFormState) => {
367
+ if (this.forceFormUpdate || this.config.lazyUpdates === false) {
368
+ this.forceFormUpdate = false;
369
+ this.updateFormState(rawFormState);
370
+ } else {
371
+ this.scheduleUpdateFormState(rawFormState);
372
+ }
373
+ }
374
+ });
375
+ observable.ref(this, "isDirty");
376
+ observable.ref(this, "isLoading");
377
+ observable.ref(this, "isSubmitted");
378
+ observable.ref(this, "isSubmitSuccessful");
379
+ observable.ref(this, "isSubmitting");
380
+ observable.ref(this, "isValidating");
381
+ observable.ref(this, "isValid");
382
+ observable.ref(this, "disabled");
383
+ observable.ref(this, "submitCount");
384
+ observable.ref(this, "isReady");
385
+ observable.deep(this, "defaultValues");
386
+ computed(this, "hasErrors");
387
+ action(this, "updateFormState");
388
+ observable.ref(this, "originalForm");
389
+ action.bound(this, "submit");
390
+ action.bound(this, "reset");
391
+ makeObservable(this);
392
+ this.abortController.signal.addEventListener("abort", () => {
393
+ subscription();
394
+ this.originalForm = null;
395
+ });
396
+ }
387
397
  /**
388
398
  * The same as setValue, but will trigger validation if form was submitted, also marks this field as dirty
389
399
  * It should work the same as field.onChange from react-hook-form's Controller
@@ -407,7 +417,7 @@ class Form {
407
417
  * ```
408
418
  */
409
419
  changeField = (name, value, options) => {
410
- this.setValue(name, value, {
420
+ return this.setValue(name, value, {
411
421
  shouldDirty: true,
412
422
  shouldValidate: this.isSubmitted,
413
423
  ...options
@@ -508,6 +518,7 @@ class Form {
508
518
  touchedFields,
509
519
  ...simpleProperties
510
520
  }) {
521
+ this.stopScheduledFormStateUpdate();
511
522
  Object.entries(simpleProperties).forEach(([key, value]) => {
512
523
  if (value != null) {
513
524
  this[key] = value;
@@ -540,12 +551,14 @@ class Form {
540
551
  this.stopScheduledFormStateUpdate();
541
552
  }
542
553
  }
554
+ const createForm = (config) => new Form(config);
543
555
  class MobxForm extends Form {
544
556
  }
545
557
  export {
546
558
  Controller,
547
559
  Form,
548
560
  MobxForm,
561
+ createForm,
549
562
  isFieldError
550
563
  };
551
564
  //# sourceMappingURL=index.js.map
package/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/components/controller.tsx","../src/utils/is-field-error.ts","../src/mobx-form/mobx-form.ts"],"sourcesContent":["import { Observer } from 'mobx-react-lite';\nimport { Controller as LibController } from 'react-hook-form';\n\nexport const Controller = ((props: any) => (\n <LibController\n {...props}\n render={(renderProps) => (\n <Observer>{() => props.render(renderProps)}</Observer>\n )}\n />\n)) as unknown as typeof LibController;\n","import type { FieldError } from 'react-hook-form';\nimport { typeGuard } from 'yummies/type-guard';\n\nexport const isFieldError = (value: unknown): value is FieldError => {\n return typeGuard.isObject(value) && 'type' in value;\n};\n","import { LinkedAbortController } from 'linked-abort-controller';\nimport {\n action,\n computed,\n isObservableObject,\n makeObservable,\n observable,\n toJS,\n} from 'mobx';\nimport type { BaseSyntheticEvent } from 'react';\nimport {\n type Control,\n createFormControl,\n type DeepMap,\n type DeepPartial,\n type DefaultValues,\n type FieldErrors,\n type FieldPath,\n type FieldPathValue,\n type FieldValues,\n type FormState,\n get,\n type SetValueConfig,\n set,\n type UseFormClearErrors,\n type UseFormGetValues,\n type UseFormRegister,\n type UseFormReset,\n type UseFormResetField,\n type UseFormSetError,\n type UseFormSetFocus,\n type UseFormSetValue,\n type UseFormTrigger,\n type UseFormUnregister,\n} from 'react-hook-form';\nimport { DeepObservableStruct } from 'yummies/mobx';\nimport { isFieldError } from '../utils/index.js';\nimport type { ErrorWithPath, FormParams } from './mobx-form.types.js';\n\ntype FormFullState<TFieldValues extends FieldValues> =\n FormState<TFieldValues> & {\n values: TFieldValues;\n };\n\nexport class Form<\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n> implements FormFullState<TFieldValues>\n{\n values: TFieldValues;\n isDirty: boolean = false;\n isLoading: boolean = false;\n isSubmitted: boolean = false;\n isSubmitSuccessful: boolean = false;\n isSubmitting: boolean = false;\n isValidating: boolean = false;\n isValid: boolean = false;\n disabled: boolean = false;\n submitCount: number = 0;\n /**\n * If you want to change this property\n * Use {resetForm} method\n */\n defaultValues!: Readonly<DefaultValues<TFieldValues>>;\n dirtyFields: Partial<Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>>;\n touchedFields: Partial<Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>>;\n validatingFields: Partial<\n Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>\n >;\n errors: FieldErrors<TFieldValues>;\n isReady: boolean = false;\n\n /**\n * Set an error for the field. When set an error which is not associated to a field then manual `clearErrors` invoke is required.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/seterror) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-seterror-nfxxu) • [Video](https://www.youtube.com/watch?v=raMqvE0YyIY)\n *\n * @param name - the path name to the form field value.\n * @param error - an error object which contains type and optional message\n * @param options - whether or not to focus on the field\n *\n * @example\n * ```tsx\n * // when the error is not associated with any fields, `clearError` will need to invoke to clear the error\n * const onSubmit = () => setError(\"serverError\", { type: \"server\", message: \"Error occurred\"})\n *\n * <button onClick={() => setError(\"name\", { type: \"min\" })} />\n *\n * // focus on the input after setting the error\n * <button onClick={() => setError(\"name\", { type: \"max\" }, { shouldFocus: true })} />\n * ```\n */\n setError: UseFormSetError<TFieldValues>;\n\n /**\n * Clear the entire form errors.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/clearerrors) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-clearerrors-w3ymx)\n *\n * @param name - the path name to the form field value.\n *\n * @example\n * Clear all errors\n * ```tsx\n * clearErrors(); // clear the entire form error\n * clearErrors([\"name\", \"name1\"]) // clear an array of fields' error\n * clearErrors(\"name2\"); // clear a single field error\n * ```\n */\n clearErrors: UseFormClearErrors<TFieldValues>;\n\n /**\n * Trigger field or form validation\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/trigger) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-triggervalidation-forked-xs7hl) • [Video](https://www.youtube.com/watch?v=-bcyJCDjksE)\n *\n * @param name - provide empty argument will trigger the entire form validation, an array of field names will validate an array of fields, and a single field name will only trigger that field's validation.\n * @param options - should focus on the error field\n *\n * @returns validation result\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * trigger();\n * }, [trigger])\n *\n * <button onClick={async () => {\n * const result = await trigger(); // result will be a boolean value\n * }}>\n * trigger\n * </button>\n * ```\n */\n trigger: UseFormTrigger<TFieldValues>;\n\n /**\n * Reset a field state and reference.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/resetfield) • [Demo](https://codesandbox.io/s/priceless-firefly-d0kuv) • [Video](https://www.youtube.com/watch?v=IdLFcNaEFEo)\n *\n * @param name - the path name to the form field value.\n * @param options - keep form state options\n *\n * @example\n * ```tsx\n * <input {...register(\"firstName\", { required: true })} />\n * <button type=\"button\" onClick={() => resetField(\"firstName\"))}>Reset</button>\n * ```\n */\n resetField: UseFormResetField<TFieldValues>;\n\n /**\n * Unregister a field reference and remove its value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/unregister) • [Demo](https://codesandbox.io/s/react-hook-form-unregister-4k2ey) • [Video](https://www.youtube.com/watch?v=TM99g_NW5Gk&feature=emb_imp_woyt)\n *\n * @param name - the path name to the form field value.\n * @param options - keep form state options\n *\n * @example\n * ```tsx\n * register(\"name\", { required: true })\n *\n * <button onClick={() => unregister(\"name\")} />\n * // there are various keep options to retain formState\n * <button onClick={() => unregister(\"name\", { keepErrors: true })} />\n * ```\n */\n unregister: UseFormUnregister<TFieldValues>;\n\n /**\n * Form control\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/control)\n *\n */\n control: Control<TFieldValues, TContext, TTransformedValues>;\n\n /**\n * Register field into hook form with or without the actual DOM ref. You can invoke register anywhere in the component including at `useEffect`.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/register) • [Demo](https://codesandbox.io/s/react-hook-form-register-ts-ip2j3) • [Video](https://www.youtube.com/watch?v=JFIpCoajYkA)\n *\n * @param name - the path name to the form field value, name is required and unique\n * @param options - register options include validation, disabled, unregister, value as and dependent validation\n *\n * @returns onChange, onBlur, name, ref, and native contribute attribute if browser validation is enabled.\n *\n * @example\n * ```tsx\n * // Register HTML native input\n * <input {...register(\"input\")} />\n * <select {...register(\"select\")} />\n *\n * // Register options\n * <textarea {...register(\"textarea\", { required: \"This is required.\", maxLength: 20 })} />\n * <input type=\"number\" {...register(\"name2\", { valueAsNumber: true })} />\n * <input {...register(\"name3\", { deps: [\"name2\"] })} />\n *\n * // Register custom field at useEffect\n * useEffect(() => {\n * register(\"name4\");\n * register(\"name5\", { value: \"hiddenValue\" });\n * }, [register])\n *\n * // Register without ref\n * const { onChange, onBlur, name } = register(\"name6\")\n * <input onChange={onChange} onBlur={onBlur} name={name} />\n * ```\n */\n register: UseFormRegister<TFieldValues>;\n\n /**\n * Set focus on a registered field. You can start to invoke this method after all fields are mounted to the DOM.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/setfocus) • [Demo](https://codesandbox.io/s/setfocus-rolus)\n *\n * @param name - the path name to the form field value.\n * @param options - input focus behavior options\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * setFocus(\"name\");\n * }, [setFocus])\n * // shouldSelect allows to select input's content on focus\n * <button onClick={() => setFocus(\"name\", { shouldSelect: true })}>Focus</button>\n * ```\n */\n setFocus: UseFormSetFocus<TFieldValues>;\n\n /**\n * Set a single field value, or a group of fields value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/setvalue) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-setvalue-8z9hx) • [Video](https://www.youtube.com/watch?v=qpv51sCH3fI)\n *\n * @param name - the path name to the form field value.\n * @param value - field value\n * @param options - should validate or update form state\n *\n * @example\n * ```tsx\n * // Update a single field\n * setValue('name', 'value', {\n * shouldValidate: true, // trigger validation\n * shouldTouch: true, // update touched fields form state\n * shouldDirty: true, // update dirty and dirty fields form state\n * });\n *\n * // Update a group fields\n * setValue('root', {\n * a: 'test', // setValue('root.a', 'data')\n * b: 'test1', // setValue('root.b', 'data')\n * });\n *\n * // Update a nested object field\n * setValue('select', { label: 'test', value: 'Test' });\n * ```\n */\n setValue: UseFormSetValue<TFieldValues>;\n\n /**\n * Get a single field value, or a group of fields value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/getvalues) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-getvalues-txsfg)\n *\n * @param fieldNames - the path name to the form field value.\n * @param options - returns only dirty fields or return only touchedFields\n *\n * @example\n * ```tsx\n * // Update a single field\n * getValues('name', 'value', {\n * dirtyFields: true, // returns only dirty fields\n * touchedFields: true, // returns only touchedFields\n * });\n *\n * // Get nested values\n * getValues('root.nested.0.value');\n * ```\n */\n getValues: UseFormGetValues<TFieldValues>;\n\n /**\n * Reset at the entire form state.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/reset) • [Demo](https://codesandbox.io/s/react-hook-form-reset-v7-ts-pu901) • [Video](https://www.youtube.com/watch?v=qmCLBjyPwVk)\n *\n * @param values - the entire form values to be reset\n * @param keepStateOptions - keep form state options\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * // reset the entire form after component mount or form defaultValues is ready\n * reset({\n * fieldA: \"test\"\n * fieldB: \"test\"\n * });\n * }, [reset])\n *\n * // reset by combine with existing form values\n * reset({\n * ...getValues(),\n * fieldB: \"test\"\n *});\n *\n * // reset and keep form state\n * reset({\n * ...getValues(),\n *}, {\n * keepErrors: true,\n * keepDirty: true\n *});\n * ```\n */\n resetForm: UseFormReset<TFieldValues>;\n\n protected abortController: AbortController;\n\n /**\n * Original react-hook-form form\n */\n originalForm: ReturnType<\n typeof createFormControl<TFieldValues, TContext, TTransformedValues>\n >;\n\n private _observableStruct: DeepObservableStruct<\n Pick<\n FormFullState<TFieldValues>,\n 'dirtyFields' | 'errors' | 'touchedFields' | 'validatingFields' | 'values'\n >\n >;\n\n constructor(\n private config: FormParams<TFieldValues, TContext, TTransformedValues>,\n ) {\n this.abortController = new LinkedAbortController(config.abortSignal);\n\n this.originalForm = createFormControl<\n TFieldValues,\n TContext,\n TTransformedValues\n >({\n ...config,\n defaultValues: {\n ...config.defaultValues,\n } as DefaultValues<TFieldValues>,\n });\n\n const defaultValues = config.defaultValues\n ? { ...config.defaultValues }\n : ({} as any);\n\n this.setError = action((...args) => {\n set(this.errors, args[0], args[1]);\n return this.originalForm.setError(...args);\n });\n this.clearErrors = this.originalForm.clearErrors;\n this.trigger = this.originalForm.trigger;\n this.resetField = action((...args) => {\n set(this.values, args[0], get(this.defaultValues, args[0]));\n return this.originalForm.resetField(...args);\n });\n this.unregister = this.originalForm.unregister;\n this.control = this.originalForm.control;\n this.register = this.originalForm.register;\n this.setFocus = this.originalForm.setFocus;\n this.setValue = action((...args) => {\n set(this.values, args[0], args[1]);\n return this.originalForm.setValue(...args);\n });\n this.getValues = this.originalForm.getValues;\n this.resetForm = action((...args) => {\n let defaultValues = args[0] ?? this.defaultValues;\n\n if (isObservableObject(defaultValues)) {\n defaultValues = toJS(defaultValues);\n } else {\n defaultValues = structuredClone(defaultValues);\n }\n\n // @ts-expect-error\n this.values = defaultValues;\n return this.originalForm.reset(...args);\n });\n\n this._observableStruct = new DeepObservableStruct({\n values: this.originalForm.getValues(),\n errors: {},\n dirtyFields: {},\n touchedFields: {},\n validatingFields: {},\n });\n\n this.values = this._observableStruct.data.values;\n this.errors = this._observableStruct.data.errors;\n this.validatingFields = this._observableStruct.data.validatingFields;\n this.dirtyFields = this._observableStruct.data.dirtyFields;\n this.touchedFields = this._observableStruct.data.touchedFields;\n\n Object.assign(this, {\n defaultValues,\n });\n\n const subscription = this.originalForm.subscribe({\n formState: {\n values: true,\n errors: true,\n isValid: true,\n isDirty: true,\n isValidating: true,\n dirtyFields: true,\n touchedFields: true,\n validatingFields: true,\n },\n callback: (rawFormState) => {\n if (this.config.lazyUpdates === false) {\n this.updateFormState(rawFormState);\n } else {\n this.scheduleUpdateFormState(rawFormState);\n }\n },\n });\n\n observable.ref(this, 'isDirty');\n observable.ref(this, 'isLoading');\n observable.ref(this, 'isSubmitted');\n observable.ref(this, 'isSubmitSuccessful');\n observable.ref(this, 'isSubmitting');\n observable.ref(this, 'isValidating');\n observable.ref(this, 'isValid');\n observable.ref(this, 'disabled');\n observable.ref(this, 'submitCount');\n observable.ref(this, 'isReady');\n observable.deep(this, 'defaultValues');\n computed(this, 'hasErrors');\n action(this, 'updateFormState');\n\n observable.ref(this, 'originalForm');\n action.bound(this, 'submit');\n action.bound(this, 'reset');\n\n makeObservable(this);\n\n this.abortController.signal.addEventListener('abort', () => {\n subscription();\n // @ts-expect-error\n this.originalForm = null;\n });\n }\n\n /**\n * The same as setValue, but will trigger validation if form was submitted, also marks this field as dirty\n * It should work the same as field.onChange from react-hook-form's Controller\n *\n * @param name - the path name to the form field value.\n * @param value - field value\n * @param options - should validate or update form state\n *\n * @example\n * ```tsx\n * // Update a single field\n * changeField('name', 'value');\n * ->\n * setValue('name', 'value', { shouldDirty: true });\n *\n * ** form submitted **\n *\n * changeField('name', 'value');\n * ->\n * setValue('name', 'value', { shouldDirty: true, shouldValidate: true });\n * ```\n */\n changeField = <\n TFieldName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n >(\n name: TFieldName,\n value: FieldPathValue<TFieldValues, TFieldName> | undefined,\n options?: SetValueConfig,\n ) => {\n this.setValue(name, value as any, {\n shouldDirty: true,\n shouldValidate: this.isSubmitted,\n ...options,\n });\n };\n\n /**\n * Method to manually submit form.\n * Used to attach this method to <form /> element\n *\n * @example\n *\n * <form onSubmit={form.submit} />\n */\n submit(e?: BaseSyntheticEvent) {\n return new Promise<TTransformedValues>((resolve, reject) => {\n if (this.originalForm) {\n this.originalForm.handleSubmit(\n async (data, event) => {\n if (this.config.strictSubmitChecks) {\n const anyErrorWithPath = this.getErrorsWithPaths(true)[0];\n if (anyErrorWithPath) {\n this.setFocus(anyErrorWithPath.path);\n await this.config.onSubmitFailed?.(this.errors, event);\n reject(this.errors);\n return;\n }\n }\n await this.config.onSubmit?.(data, event);\n resolve(data);\n },\n async (errors, event) => {\n await this.config.onSubmitFailed?.(errors, event);\n reject(errors);\n },\n )(e);\n } else {\n const emptyData = (this.values ?? {}) as unknown as TTransformedValues;\n const result = this.config.onSubmit?.(emptyData);\n if (result instanceof Promise) {\n return result.then(() => resolve(emptyData));\n } else {\n return Promise.resolve(emptyData);\n }\n }\n });\n }\n\n /**\n * Method to manually reset all form.\n * Used to attach this method to <form /> element\n *\n * @example\n *\n * <form onReset={form.reset} />\n */\n reset(e?: BaseSyntheticEvent) {\n this.resetForm();\n this.config.onReset?.(e);\n }\n\n get hasErrors() {\n return Object.keys(this.errors).length > 0;\n }\n\n getErrorsWithPaths(getOnlyFirst?: boolean): ErrorWithPath<TFieldValues>[] {\n const result: ErrorWithPath<TFieldValues>[] = [];\n\n const traverse = (obj: any, prefix = '') => {\n if (!obj || typeof obj !== 'object') return;\n\n Object.entries(obj).forEach(([key, value]) => {\n const path = (prefix ? `${prefix}.${key}` : key) as any;\n\n if (isFieldError(value)) {\n result.push({ path, error: value });\n if (getOnlyFirst) {\n return;\n }\n } else if (Array.isArray(value)) {\n value.forEach((item, idx) => {\n const arrayPath = `${path}.${idx}` as any;\n\n if (isFieldError(item)) {\n result.push({ path: arrayPath, error: item });\n if (getOnlyFirst) {\n return;\n }\n } else if (typeof item === 'object') {\n traverse(item, arrayPath);\n }\n });\n } else if (typeof value === 'object') {\n traverse(value, path);\n }\n });\n };\n\n traverse(this.errors);\n\n return result;\n }\n\n private updateFormState({\n values,\n errors,\n dirtyFields,\n validatingFields,\n touchedFields,\n ...simpleProperties\n }: Partial<FormFullState<TFieldValues>>) {\n Object.entries(simpleProperties).forEach(([key, value]) => {\n if (value != null) {\n // @ts-expect-error\n this[key] = value;\n }\n });\n\n this._observableStruct.set({\n dirtyFields,\n errors,\n touchedFields,\n validatingFields,\n values,\n });\n }\n\n protected lastTimeoutId: ReturnType<typeof setTimeout> | undefined;\n\n private stopScheduledFormStateUpdate = () => {\n if (this.lastTimeoutId !== undefined) {\n clearTimeout(this.lastTimeoutId);\n this.lastTimeoutId = undefined;\n }\n };\n\n private scheduleUpdateFormState = (\n rawFormState: Partial<FormFullState<TFieldValues>>,\n ) => {\n this.stopScheduledFormStateUpdate();\n this.lastTimeoutId = setTimeout(() => {\n this.updateFormState(rawFormState);\n this.lastTimeoutId = undefined;\n }, this.config.lazyUpdatesTimer ?? 0);\n };\n\n destroy(): void {\n this.abortController.abort();\n this.stopScheduledFormStateUpdate();\n }\n}\n\n/**\n * @deprecated ⚠️ use `Form`. This export will be removed in next major release\n */\nexport class MobxForm<\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n> extends Form<TFieldValues, TContext, TTransformedValues> {}\n"],"names":["LibController","defaultValues"],"mappings":";;;;;;;AAGO,MAAM,cAAc,CAAC,UAC1B;AAAA,EAACA;AAAAA,EAAA;AAAA,IACE,GAAG;AAAA,IACJ,QAAQ,CAAC,gBACP,oBAAC,YAAU,UAAA,MAAM,MAAM,OAAO,WAAW,EAAA,CAAE;AAAA,EAAA;AAE/C;ACNK,MAAM,eAAe,CAAC,UAAwC;AACnE,SAAO,UAAU,SAAS,KAAK,KAAK,UAAU;AAChD;ACuCO,MAAM,KAKb;AAAA,EA0SE,YACU,QACR;AADQ,SAAA,SAAA;AAER,SAAK,kBAAkB,IAAI,sBAAsB,OAAO,WAAW;AAEnE,SAAK,eAAe,kBAIlB;AAAA,MACA,GAAG;AAAA,MACH,eAAe;AAAA,QACb,GAAG,OAAO;AAAA,MAAA;AAAA,IACZ,CACD;AAED,UAAM,gBAAgB,OAAO,gBACzB,EAAE,GAAG,OAAO,cAAA,IACX,CAAA;AAEL,SAAK,WAAW,OAAO,IAAI,SAAS;AAClC,UAAI,KA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}
1
+ {"version":3,"file":"index.js","sources":["../src/components/controller.tsx","../src/utils/is-field-error.ts","../src/form/form.ts"],"sourcesContent":["import { Observer } from 'mobx-react-lite';\nimport { Controller as LibController } from 'react-hook-form';\n\nexport const Controller = ((props: any) => (\n <LibController\n {...props}\n render={(renderProps) => (\n <Observer>{() => props.render(renderProps)}</Observer>\n )}\n />\n)) as unknown as typeof LibController;\n","import type { FieldError } from 'react-hook-form';\nimport { typeGuard } from 'yummies/type-guard';\n\nexport const isFieldError = (value: unknown): value is FieldError => {\n return typeGuard.isObject(value) && 'type' in value;\n};\n","import { LinkedAbortController } from 'linked-abort-controller';\nimport { action, computed, makeObservable, observable } from 'mobx';\nimport type { BaseSyntheticEvent } from 'react';\nimport {\n type Control,\n createFormControl,\n type DeepMap,\n type DeepPartial,\n type DefaultValues,\n type FieldErrors,\n type FieldPath,\n type FieldPathValue,\n type FieldValues,\n type FormState,\n type SetValueConfig,\n type UseFormClearErrors,\n type UseFormGetValues,\n type UseFormRegister,\n type UseFormReset,\n type UseFormResetField,\n type UseFormSetError,\n type UseFormSetFocus,\n type UseFormSetValue,\n type UseFormTrigger,\n type UseFormUnregister,\n} from 'react-hook-form';\nimport { DeepObservableStruct } from 'yummies/mobx';\nimport { isFieldError } from '../utils/index.js';\nimport type { ErrorWithPath, FormParams } from './form.types.js';\n\ntype FormFullState<TFieldValues extends FieldValues> =\n FormState<TFieldValues> & {\n values: TFieldValues;\n };\n\nexport class Form<\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n> implements FormFullState<TFieldValues>\n{\n values: TFieldValues;\n isDirty: boolean = false;\n isLoading: boolean = false;\n isSubmitted: boolean = false;\n isSubmitSuccessful: boolean = false;\n isSubmitting: boolean = false;\n isValidating: boolean = false;\n isValid: boolean = false;\n disabled: boolean = false;\n submitCount: number = 0;\n /**\n * If you want to change this property\n * Use {resetForm} method\n */\n defaultValues!: Readonly<DefaultValues<TFieldValues>>;\n dirtyFields: Partial<Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>>;\n touchedFields: Partial<Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>>;\n validatingFields: Partial<\n Readonly<DeepMap<DeepPartial<TFieldValues>, boolean>>\n >;\n errors: FieldErrors<TFieldValues>;\n isReady: boolean = false;\n\n /**\n * Set an error for the field. When set an error which is not associated to a field then manual `clearErrors` invoke is required.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/seterror) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-seterror-nfxxu) • [Video](https://www.youtube.com/watch?v=raMqvE0YyIY)\n *\n * @param name - the path name to the form field value.\n * @param error - an error object which contains type and optional message\n * @param options - whether or not to focus on the field\n *\n * @example\n * ```tsx\n * // when the error is not associated with any fields, `clearError` will need to invoke to clear the error\n * const onSubmit = () => setError(\"serverError\", { type: \"server\", message: \"Error occurred\"})\n *\n * <button onClick={() => setError(\"name\", { type: \"min\" })} />\n *\n * // focus on the input after setting the error\n * <button onClick={() => setError(\"name\", { type: \"max\" }, { shouldFocus: true })} />\n * ```\n */\n setError: UseFormSetError<TFieldValues>;\n\n /**\n * Clear the entire form errors.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/clearerrors) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-clearerrors-w3ymx)\n *\n * @param name - the path name to the form field value.\n *\n * @example\n * Clear all errors\n * ```tsx\n * clearErrors(); // clear the entire form error\n * clearErrors([\"name\", \"name1\"]) // clear an array of fields' error\n * clearErrors(\"name2\"); // clear a single field error\n * ```\n */\n clearErrors: UseFormClearErrors<TFieldValues>;\n\n /**\n * Trigger field or form validation\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/trigger) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-triggervalidation-forked-xs7hl) • [Video](https://www.youtube.com/watch?v=-bcyJCDjksE)\n *\n * @param name - provide empty argument will trigger the entire form validation, an array of field names will validate an array of fields, and a single field name will only trigger that field's validation.\n * @param options - should focus on the error field\n *\n * @returns validation result\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * trigger();\n * }, [trigger])\n *\n * <button onClick={async () => {\n * const result = await trigger(); // result will be a boolean value\n * }}>\n * trigger\n * </button>\n * ```\n */\n trigger: UseFormTrigger<TFieldValues>;\n\n /**\n * Reset a field state and reference.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/resetfield) • [Demo](https://codesandbox.io/s/priceless-firefly-d0kuv) • [Video](https://www.youtube.com/watch?v=IdLFcNaEFEo)\n *\n * @param name - the path name to the form field value.\n * @param options - keep form state options\n *\n * @example\n * ```tsx\n * <input {...register(\"firstName\", { required: true })} />\n * <button type=\"button\" onClick={() => resetField(\"firstName\"))}>Reset</button>\n * ```\n */\n resetField: UseFormResetField<TFieldValues>;\n\n /**\n * Unregister a field reference and remove its value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/unregister) • [Demo](https://codesandbox.io/s/react-hook-form-unregister-4k2ey) • [Video](https://www.youtube.com/watch?v=TM99g_NW5Gk&feature=emb_imp_woyt)\n *\n * @param name - the path name to the form field value.\n * @param options - keep form state options\n *\n * @example\n * ```tsx\n * register(\"name\", { required: true })\n *\n * <button onClick={() => unregister(\"name\")} />\n * // there are various keep options to retain formState\n * <button onClick={() => unregister(\"name\", { keepErrors: true })} />\n * ```\n */\n unregister: UseFormUnregister<TFieldValues>;\n\n /**\n * Form control\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/control)\n *\n */\n control: Control<TFieldValues, TContext, TTransformedValues>;\n\n /**\n * Register field into hook form with or without the actual DOM ref. You can invoke register anywhere in the component including at `useEffect`.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/register) • [Demo](https://codesandbox.io/s/react-hook-form-register-ts-ip2j3) • [Video](https://www.youtube.com/watch?v=JFIpCoajYkA)\n *\n * @param name - the path name to the form field value, name is required and unique\n * @param options - register options include validation, disabled, unregister, value as and dependent validation\n *\n * @returns onChange, onBlur, name, ref, and native contribute attribute if browser validation is enabled.\n *\n * @example\n * ```tsx\n * // Register HTML native input\n * <input {...register(\"input\")} />\n * <select {...register(\"select\")} />\n *\n * // Register options\n * <textarea {...register(\"textarea\", { required: \"This is required.\", maxLength: 20 })} />\n * <input type=\"number\" {...register(\"name2\", { valueAsNumber: true })} />\n * <input {...register(\"name3\", { deps: [\"name2\"] })} />\n *\n * // Register custom field at useEffect\n * useEffect(() => {\n * register(\"name4\");\n * register(\"name5\", { value: \"hiddenValue\" });\n * }, [register])\n *\n * // Register without ref\n * const { onChange, onBlur, name } = register(\"name6\")\n * <input onChange={onChange} onBlur={onBlur} name={name} />\n * ```\n */\n register: UseFormRegister<TFieldValues>;\n\n /**\n * Set focus on a registered field. You can start to invoke this method after all fields are mounted to the DOM.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/setfocus) • [Demo](https://codesandbox.io/s/setfocus-rolus)\n *\n * @param name - the path name to the form field value.\n * @param options - input focus behavior options\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * setFocus(\"name\");\n * }, [setFocus])\n * // shouldSelect allows to select input's content on focus\n * <button onClick={() => setFocus(\"name\", { shouldSelect: true })}>Focus</button>\n * ```\n */\n setFocus: UseFormSetFocus<TFieldValues>;\n\n /**\n * Set a single field value, or a group of fields value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/setvalue) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-setvalue-8z9hx) • [Video](https://www.youtube.com/watch?v=qpv51sCH3fI)\n *\n * @param name - the path name to the form field value.\n * @param value - field value\n * @param options - should validate or update form state\n *\n * @example\n * ```tsx\n * // Update a single field\n * setValue('name', 'value', {\n * shouldValidate: true, // trigger validation\n * shouldTouch: true, // update touched fields form state\n * shouldDirty: true, // update dirty and dirty fields form state\n * });\n *\n * // Update a group fields\n * setValue('root', {\n * a: 'test', // setValue('root.a', 'data')\n * b: 'test1', // setValue('root.b', 'data')\n * });\n *\n * // Update a nested object field\n * setValue('select', { label: 'test', value: 'Test' });\n * ```\n */\n setValue: UseFormSetValue<TFieldValues>;\n\n /**\n * Get a single field value, or a group of fields value.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/getvalues) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-getvalues-txsfg)\n *\n * @param fieldNames - the path name to the form field value.\n * @param options - returns only dirty fields or return only touchedFields\n *\n * @example\n * ```tsx\n * // Update a single field\n * getValues('name', 'value', {\n * dirtyFields: true, // returns only dirty fields\n * touchedFields: true, // returns only touchedFields\n * });\n *\n * // Get nested values\n * getValues('root.nested.0.value');\n * ```\n */\n getValues: UseFormGetValues<TFieldValues>;\n\n /**\n * Reset at the entire form state.\n *\n * @remarks\n * [API](https://react-hook-form.com/docs/useform/reset) • [Demo](https://codesandbox.io/s/react-hook-form-reset-v7-ts-pu901) • [Video](https://www.youtube.com/watch?v=qmCLBjyPwVk)\n *\n * @param values - the entire form values to be reset\n * @param keepStateOptions - keep form state options\n *\n * @example\n * ```tsx\n * useEffect(() => {\n * // reset the entire form after component mount or form defaultValues is ready\n * reset({\n * fieldA: \"test\"\n * fieldB: \"test\"\n * });\n * }, [reset])\n *\n * // reset by combine with existing form values\n * reset({\n * ...getValues(),\n * fieldB: \"test\"\n *});\n *\n * // reset and keep form state\n * reset({\n * ...getValues(),\n *}, {\n * keepErrors: true,\n * keepDirty: true\n *});\n * ```\n */\n resetForm: UseFormReset<TFieldValues>;\n\n protected abortController: AbortController;\n\n /**\n * Original react-hook-form form\n */\n originalForm: ReturnType<\n typeof createFormControl<TFieldValues, TContext, TTransformedValues>\n >;\n\n private _observableStruct: DeepObservableStruct<\n Pick<\n FormFullState<TFieldValues>,\n 'dirtyFields' | 'errors' | 'touchedFields' | 'validatingFields' | 'values'\n >\n >;\n\n shouldFocusError: boolean;\n\n private config: FormParams<TFieldValues, TContext, TTransformedValues>;\n\n // special hack to apply the same form value changes from the original form\n // using subscription\n private forceFormUpdate: boolean;\n\n constructor(config: FormParams<TFieldValues, TContext, TTransformedValues>) {\n this.abortController = new LinkedAbortController(config.abortSignal);\n\n this.shouldFocusError = config.shouldFocusError ?? true;\n this.forceFormUpdate = false;\n\n this.config = {\n ...config,\n defaultValues: {\n ...config.defaultValues,\n } as DefaultValues<TFieldValues>,\n };\n\n Object.defineProperty(this.config, 'shouldFocusError', {\n get() {\n return this.shouldFocusError;\n },\n });\n\n this.originalForm = createFormControl<\n TFieldValues,\n TContext,\n TTransformedValues\n >(this.config as any);\n\n const defaultValues = config.defaultValues\n ? { ...config.defaultValues }\n : ({} as any);\n\n this.setError = (...args) => {\n this.forceFormUpdate = true;\n return this.originalForm.setError(...args);\n };\n this.clearErrors = (...args) => {\n this.forceFormUpdate = true;\n return this.originalForm.clearErrors(...args);\n };\n this.trigger = this.originalForm.trigger;\n this.resetField = (...args) => {\n this.forceFormUpdate = true;\n return this.originalForm.resetField(...args);\n };\n this.unregister = this.originalForm.unregister;\n this.control = this.originalForm.control;\n this.register = this.originalForm.register;\n this.setFocus = this.originalForm.setFocus;\n this.setValue = (...args) => {\n this.forceFormUpdate = true;\n return this.originalForm.setValue(...args);\n };\n this.getValues = this.originalForm.getValues;\n this.resetForm = (...args) => {\n this.forceFormUpdate = true;\n return this.originalForm.reset(...args);\n };\n\n this._observableStruct = new DeepObservableStruct({\n values: this.originalForm.getValues(),\n errors: {},\n dirtyFields: {},\n touchedFields: {},\n validatingFields: {},\n });\n\n this.values = this._observableStruct.data.values;\n this.errors = this._observableStruct.data.errors;\n this.validatingFields = this._observableStruct.data.validatingFields;\n this.dirtyFields = this._observableStruct.data.dirtyFields;\n this.touchedFields = this._observableStruct.data.touchedFields;\n\n Object.assign(this, {\n defaultValues,\n });\n\n const subscription = this.originalForm.subscribe({\n formState: {\n values: true,\n errors: true,\n isValid: true,\n isDirty: true,\n isValidating: true,\n dirtyFields: true,\n touchedFields: true,\n validatingFields: true,\n },\n callback: (rawFormState) => {\n if (this.forceFormUpdate || this.config.lazyUpdates === false) {\n this.forceFormUpdate = false;\n this.updateFormState(rawFormState);\n } else {\n this.scheduleUpdateFormState(rawFormState);\n }\n },\n });\n\n observable.ref(this, 'isDirty');\n observable.ref(this, 'isLoading');\n observable.ref(this, 'isSubmitted');\n observable.ref(this, 'isSubmitSuccessful');\n observable.ref(this, 'isSubmitting');\n observable.ref(this, 'isValidating');\n observable.ref(this, 'isValid');\n observable.ref(this, 'disabled');\n observable.ref(this, 'submitCount');\n observable.ref(this, 'isReady');\n observable.deep(this, 'defaultValues');\n computed(this, 'hasErrors');\n action(this, 'updateFormState');\n\n observable.ref(this, 'originalForm');\n action.bound(this, 'submit');\n action.bound(this, 'reset');\n\n makeObservable(this);\n\n this.abortController.signal.addEventListener('abort', () => {\n subscription();\n // @ts-expect-error\n this.originalForm = null;\n });\n }\n\n /**\n * The same as setValue, but will trigger validation if form was submitted, also marks this field as dirty\n * It should work the same as field.onChange from react-hook-form's Controller\n *\n * @param name - the path name to the form field value.\n * @param value - field value\n * @param options - should validate or update form state\n *\n * @example\n * ```tsx\n * // Update a single field\n * changeField('name', 'value');\n * ->\n * setValue('name', 'value', { shouldDirty: true });\n *\n * ** form submitted **\n *\n * changeField('name', 'value');\n * ->\n * setValue('name', 'value', { shouldDirty: true, shouldValidate: true });\n * ```\n */\n changeField = <\n TFieldName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,\n >(\n name: TFieldName,\n value: FieldPathValue<TFieldValues, TFieldName> | undefined,\n options?: SetValueConfig,\n ) => {\n return this.setValue(name, value as any, {\n shouldDirty: true,\n shouldValidate: this.isSubmitted,\n ...options,\n });\n };\n\n /**\n * Method to manually submit form.\n * Used to attach this method to <form /> element\n *\n * @example\n *\n * <form onSubmit={form.submit} />\n */\n submit(e?: BaseSyntheticEvent) {\n return new Promise<TTransformedValues>((resolve, reject) => {\n if (this.originalForm) {\n this.originalForm.handleSubmit(\n async (data, event) => {\n if (this.config.strictSubmitChecks) {\n const anyErrorWithPath = this.getErrorsWithPaths(true)[0];\n if (anyErrorWithPath) {\n this.setFocus(anyErrorWithPath.path);\n await this.config.onSubmitFailed?.(this.errors, event);\n reject(this.errors);\n return;\n }\n }\n await this.config.onSubmit?.(data, event);\n resolve(data);\n },\n async (errors, event) => {\n await this.config.onSubmitFailed?.(errors, event);\n reject(errors);\n },\n )(e);\n } else {\n const emptyData = (this.values ?? {}) as unknown as TTransformedValues;\n const result = this.config.onSubmit?.(emptyData);\n if (result instanceof Promise) {\n return result.then(() => resolve(emptyData));\n } else {\n return Promise.resolve(emptyData);\n }\n }\n });\n }\n\n /**\n * Method to manually reset all form.\n * Used to attach this method to <form /> element\n *\n * @example\n *\n * <form onReset={form.reset} />\n */\n reset(e?: BaseSyntheticEvent) {\n this.resetForm();\n this.config.onReset?.(e);\n }\n\n get hasErrors() {\n return Object.keys(this.errors).length > 0;\n }\n\n getErrorsWithPaths(getOnlyFirst?: boolean): ErrorWithPath<TFieldValues>[] {\n const result: ErrorWithPath<TFieldValues>[] = [];\n\n const traverse = (obj: any, prefix = '') => {\n if (!obj || typeof obj !== 'object') return;\n\n Object.entries(obj).forEach(([key, value]) => {\n const path = (prefix ? `${prefix}.${key}` : key) as any;\n\n if (isFieldError(value)) {\n result.push({ path, error: value });\n if (getOnlyFirst) {\n return;\n }\n } else if (Array.isArray(value)) {\n value.forEach((item, idx) => {\n const arrayPath = `${path}.${idx}` as any;\n\n if (isFieldError(item)) {\n result.push({ path: arrayPath, error: item });\n if (getOnlyFirst) {\n return;\n }\n } else if (typeof item === 'object') {\n traverse(item, arrayPath);\n }\n });\n } else if (typeof value === 'object') {\n traverse(value, path);\n }\n });\n };\n\n traverse(this.errors);\n\n return result;\n }\n\n private updateFormState({\n values,\n errors,\n dirtyFields,\n validatingFields,\n touchedFields,\n ...simpleProperties\n }: Partial<FormFullState<TFieldValues>>) {\n this.stopScheduledFormStateUpdate();\n Object.entries(simpleProperties).forEach(([key, value]) => {\n if (value != null) {\n // @ts-expect-error\n this[key] = value;\n }\n });\n\n this._observableStruct.set({\n dirtyFields,\n errors,\n touchedFields,\n validatingFields,\n values,\n });\n }\n\n protected lastTimeoutId: ReturnType<typeof setTimeout> | undefined;\n\n private stopScheduledFormStateUpdate = () => {\n if (this.lastTimeoutId !== undefined) {\n clearTimeout(this.lastTimeoutId);\n this.lastTimeoutId = undefined;\n }\n };\n\n private scheduleUpdateFormState = (\n rawFormState: Partial<FormFullState<TFieldValues>>,\n ) => {\n this.stopScheduledFormStateUpdate();\n this.lastTimeoutId = setTimeout(() => {\n this.updateFormState(rawFormState);\n this.lastTimeoutId = undefined;\n }, this.config.lazyUpdatesTimer ?? 0);\n };\n\n destroy(): void {\n this.abortController.abort();\n this.stopScheduledFormStateUpdate();\n }\n}\n\nexport const createForm = <\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n>(\n config: FormParams<TFieldValues, TContext, TTransformedValues>,\n) => new Form(config);\n\n/**\n * @deprecated ⚠️ use `Form`. This export will be removed in next major release\n */\nexport class MobxForm<\n TFieldValues extends FieldValues = FieldValues,\n TContext = any,\n TTransformedValues = TFieldValues,\n> extends Form<TFieldValues, TContext, TTransformedValues> {}\n"],"names":["LibController"],"mappings":";;;;;;;AAGO,MAAM,cAAc,CAAC,UAC1B;AAAA,EAACA;AAAAA,EAAA;AAAA,IACE,GAAG;AAAA,IACJ,QAAQ,CAAC,gBACP,oBAAC,YAAU,UAAA,MAAM,MAAM,OAAO,WAAW,EAAA,CAAE;AAAA,EAAA;AAE/C;ACNK,MAAM,eAAe,CAAC,UAAwC;AACnE,SAAO,UAAU,SAAS,KAAK,KAAK,UAAU;AAChD;AC8BO,MAAM,KAKb;AAAA,EACE;AAAA,EACA,UAAmB;AAAA,EACnB,YAAqB;AAAA,EACrB,cAAuB;AAAA,EACvB,qBAA8B;AAAA,EAC9B,eAAwB;AAAA,EACxB,eAAwB;AAAA,EACxB,UAAmB;AAAA,EACnB,WAAoB;AAAA,EACpB,cAAsB;AAAA;AAAA;AAAA;AAAA;AAAA,EAKtB;AAAA,EAC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,gBAAgB,MAAA;AACrB,SAAK,6BAAA;AAAA,EACP;AACF;AAEO,MAAM,aAAa,CAKxB,WACG,IAAI,KAAK,MAAM;AAKb,MAAM,iBAIH,KAAiD;AAAC;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mobx-react-hook-form",
3
- "version": "5.9.0",
3
+ "version": "6.0.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "keywords": [],
@@ -1,3 +0,0 @@
1
- export * from './mobx-form.js';
2
- export * from './mobx-form.types.js';
3
- //# sourceMappingURL=index.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/mobx-form/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,sBAAsB,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"mobx-form.d.ts","sourceRoot":"","sources":["../../src/mobx-form/mobx-form.ts"],"names":[],"mappings":"AASA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,OAAO,CAAC;AAChD,OAAO,EACL,KAAK,OAAO,EACZ,iBAAiB,EACjB,KAAK,OAAO,EACZ,KAAK,WAAW,EAChB,KAAK,aAAa,EAClB,KAAK,WAAW,EAChB,KAAK,SAAS,EACd,KAAK,cAAc,EACnB,KAAK,WAAW,EAChB,KAAK,SAAS,EAEd,KAAK,cAAc,EAEnB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACtB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACvB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,KAAK,EAAE,aAAa,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAEtE,KAAK,aAAa,CAAC,YAAY,SAAS,WAAW,IACjD,SAAS,CAAC,YAAY,CAAC,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