mobx-react-hook-form 5.8.0 → 5.9.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.
- package/index.cjs +1 -1
- package/index.cjs.map +1 -1
- package/index.js +15 -5
- package/index.js.map +1 -1
- package/mobx-form/mobx-form.d.ts +1 -1
- package/mobx-form/mobx-form.d.ts.map +1 -1
- package/mobx-form/mobx-form.types.d.ts +4 -0
- package/mobx-form/mobx-form.types.d.ts.map +1 -1
- package/package.json +1 -1
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"),
|
|
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;
|
|
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.hasErrors) {\n await this.config.onSubmitFailed?.(this.errors, event);\n reject(this.errors);\n return;\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(): 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 } 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 } 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","hasErrors","onSubmitFailed","onReset","keys","length","getErrorsWithPaths","traverse","obj","prefix","entries","forEach","key","path","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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AmB,YACAA,EAAAE,iBACAA,EAAAD,cACAA,KACGoE,IAEHjE,OAAOsD,QAAQW,GAAkBV,QAAQ,EAAEC,EAAKhG,MACjC,MAATA,IAEFM,KAAK0F,GAAOhG,KAIhBM,KAAK4B,kBAAkBlB,IAAI,CACzBoB,cACAnB,SACAoB,gBACAC,mBACAjB,UAEJ,CAEUqF,cAEFC,6BAA+B,UACV,IAAvBrG,KAAKoG,gBACPE,aAAatG,KAAKoG,eAClBpG,KAAKoG,mBAAgB,IAIjBtD,wBACNH,IAEA3C,KAAKqG,+BACLrG,KAAKoG,cAAgBG,WAAW,KAC9BvG,KAAK6C,gBAAgBF,GACrB3C,KAAKoG,mBAAgB,GACpBpG,KAAKD,OAAOyG,kBAAoB,IAGrC,OAAAC,GACEzG,KAAKC,gBAAgByG,QACrB1G,KAAKqG,8BACP,qBCvnB0BM,GAC1BC,EAAAA,IAACC,EAAAA,WAAA,IACKF,EACJG,OAASC,GACPH,EAAAA,IAACI,EAAAA,UAAUC,SAAA,IAAMN,EAAMG,OAAOC,uCDynB7B,cAIGlH"}
|
|
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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B,EAAgB9B,OACtBA,EAAAJ,OACAA,EAAAmB,YACAA,EAAAE,iBACAA,EAAAD,cACAA,KACGuE,IAEHpE,OAAO0D,QAAQU,GAAkBT,QAAQ,EAAEC,EAAKpG,MACjC,MAATA,IAEFM,KAAK8F,GAAOpG,KAIhBM,KAAK4B,kBAAkBlB,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"}
|
package/index.js
CHANGED
|
@@ -426,10 +426,14 @@ class Form {
|
|
|
426
426
|
if (this.originalForm) {
|
|
427
427
|
this.originalForm.handleSubmit(
|
|
428
428
|
async (data, event) => {
|
|
429
|
-
if (this.
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
429
|
+
if (this.config.strictSubmitChecks) {
|
|
430
|
+
const anyErrorWithPath = this.getErrorsWithPaths(true)[0];
|
|
431
|
+
if (anyErrorWithPath) {
|
|
432
|
+
this.setFocus(anyErrorWithPath.path);
|
|
433
|
+
await this.config.onSubmitFailed?.(this.errors, event);
|
|
434
|
+
reject(this.errors);
|
|
435
|
+
return;
|
|
436
|
+
}
|
|
433
437
|
}
|
|
434
438
|
await this.config.onSubmit?.(data, event);
|
|
435
439
|
resolve(data);
|
|
@@ -465,7 +469,7 @@ class Form {
|
|
|
465
469
|
get hasErrors() {
|
|
466
470
|
return Object.keys(this.errors).length > 0;
|
|
467
471
|
}
|
|
468
|
-
getErrorsWithPaths() {
|
|
472
|
+
getErrorsWithPaths(getOnlyFirst) {
|
|
469
473
|
const result = [];
|
|
470
474
|
const traverse = (obj, prefix = "") => {
|
|
471
475
|
if (!obj || typeof obj !== "object") return;
|
|
@@ -473,11 +477,17 @@ class Form {
|
|
|
473
477
|
const path = prefix ? `${prefix}.${key}` : key;
|
|
474
478
|
if (isFieldError(value)) {
|
|
475
479
|
result.push({ path, error: value });
|
|
480
|
+
if (getOnlyFirst) {
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
476
483
|
} else if (Array.isArray(value)) {
|
|
477
484
|
value.forEach((item, idx) => {
|
|
478
485
|
const arrayPath = `${path}.${idx}`;
|
|
479
486
|
if (isFieldError(item)) {
|
|
480
487
|
result.push({ path: arrayPath, error: item });
|
|
488
|
+
if (getOnlyFirst) {
|
|
489
|
+
return;
|
|
490
|
+
}
|
|
481
491
|
} else if (typeof item === "object") {
|
|
482
492
|
traverse(item, arrayPath);
|
|
483
493
|
}
|
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.hasErrors) {\n await this.config.onSubmitFailed?.(this.errors, event);\n reject(this.errors);\n return;\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(): 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 } 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 } 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,EAA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AAM;AACpC,WAAK,gBAAgB,YAAY;AACjC,WAAK,gBAAgB;AAAA,IACvB,GAAG,KAAK,OAAO,oBAAoB,CAAC;AAAA,EACtC;AAAA,EAEA,UAAgB;AACd,SAAK,gBAAgB,MAAA;AACrB,SAAK,6BAAA;AAAA,EACP;AACF;AAKO,MAAM,iBAIH,KAAiD;AAAC;"}
|
|
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,GAA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,MAAA;AACrB,SAAK,6BAAA;AAAA,EACP;AACF;AAKO,MAAM,iBAIH,KAAiD;AAAC;"}
|
package/mobx-form/mobx-form.d.ts
CHANGED
|
@@ -322,7 +322,7 @@ export declare class Form<TFieldValues extends FieldValues = FieldValues, TConte
|
|
|
322
322
|
*/
|
|
323
323
|
reset(e?: BaseSyntheticEvent): void;
|
|
324
324
|
get hasErrors(): boolean;
|
|
325
|
-
getErrorsWithPaths(): ErrorWithPath<TFieldValues>[];
|
|
325
|
+
getErrorsWithPaths(getOnlyFirst?: boolean): ErrorWithPath<TFieldValues>[];
|
|
326
326
|
private updateFormState;
|
|
327
327
|
protected lastTimeoutId: ReturnType<typeof setTimeout> | undefined;
|
|
328
328
|
private stopScheduledFormStateUpdate;
|
|
@@ -1 +1 @@
|
|
|
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,GAAG;IACxB,MAAM,EAAE,YAA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AAO,IAAI,IAAI;CAIhB;AAED;;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"}
|
|
@@ -39,6 +39,10 @@ export interface FormParams<TFieldValues extends FieldValues = FieldValues, TCon
|
|
|
39
39
|
* @defaults `0`
|
|
40
40
|
*/
|
|
41
41
|
lazyUpdatesTimer?: number;
|
|
42
|
+
/**
|
|
43
|
+
* Allows to check on existing errors in submit handler
|
|
44
|
+
*/
|
|
45
|
+
strictSubmitChecks?: boolean;
|
|
42
46
|
}
|
|
43
47
|
/**
|
|
44
48
|
* @deprecated ⚠️ use `FormParams`. This export will be removed in next major release
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mobx-form.types.d.ts","sourceRoot":"","sources":["../../src/mobx-form/mobx-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,EAAE,MAAM,gBAAgB,CAAC;AAE3C,MAAM,MAAM,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC;AAC1C;;GAEG;AACH,MAAM,MAAM,WAAW,GAAG,OAAO,CAAC;AAElC;;GAEG;AACH,MAAM,WAAW,UAAU,CACzB,YAAY,SAAS,WAAW,GAAG,WAAW,EAC9C,QAAQ,GAAG,GAAG,EACd,kBAAkB,GAAG,YAAY,CACjC,SAAQ,IAAI,CACV,YAAY,CAAC,YAAY,EAAE,QAAQ,EAAE,kBAAkB,CAAC,EACxD,eAAe,CAChB;IACD;;OAEG;IACH,aAAa,CAAC,EAAE,WAAW,CAAC,YAA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