formik
Version:
Forms in React, without tears
3 lines (2 loc) • 14.8 kB
JavaScript
import{Children as e,useContext as t,createContext as r,useRef as n,useEffect as i,useReducer as a,useCallback as s,useMemo as o,createElement as l,Component as u}from"react";import c from"react-fast-compare";import d from"deepmerge";import p from"lodash-es/clone";import h from"lodash-es/toPath";import"tiny-warning";import m from"hoist-non-react-statics";import v from"lodash-es/cloneDeep";const f=e=>"function"==typeof e,S=e=>null!==e&&"object"==typeof e,y=e=>String(Math.floor(Number(e)))===e,E=e=>"[object String]"===Object.prototype.toString.call(e),T=e=>e!=e,g=t=>0===e.count(t),_=e=>S(e)&&f(e.then),b=e=>e&&S(e)&&S(e.target);function F(e){if(e=e||("undefined"!=typeof document?document:void 0),void 0===e)return null;try{return e.activeElement||e.body}catch(t){return e.body}}function I(e){let t=!1;const r=new Promise((r,n)=>{e.then(e=>t?n({isCanceled:!0}):r(e),e=>n(t?{isCanceled:!0}:e))});return[r,function(){t=!0}]}function O(e,t,r,n=0){const i=h(t);for(;e&&n<i.length;)e=e[i[n++]];return void 0===e?r:e}function R(e,t,r){let n=p(e),i=n,a=0,s=h(t);for(;a<s.length-1;a++){const t=s[a];let r=O(e,s.slice(0,a+1));if(r)i=i[t]=p(r);else{const e=s[a+1];i=i[t]=y(e)&&Number(e)>=0?[]:{}}}return(0===a?e:i)[s[a]]===r?e:(void 0===r?delete i[s[a]]:i[s[a]]=r,0===a&&void 0===r&&delete n[s[a]],n)}function A(e,t,r=new WeakMap,n={}){for(let i of Object.keys(e)){const a=e[i];S(a)?r.get(a)||(r.set(a,!0),n[i]=Array.isArray(a)?[]:{},A(a,t,r,n[i])):n[i]=t}return n}const P=r({}),C=P.Provider,U=P.Consumer;function L(){return t(P)}function D(e,t){switch(t.type){case"SET_VALUES":return{...e,values:t.payload};case"SET_TOUCHED":return{...e,touched:t.payload};case"SET_ERRORS":return{...e,errors:t.payload};case"SET_STATUS":return{...e,status:t.payload};case"SET_ISSUBMITTING":return{...e,isSubmitting:t.payload};case"SET_ISVALIDATING":return{...e,isValidating:t.payload};case"SET_FIELD_VALUE":return{...e,values:R(e.values,t.payload.field,t.payload.value)};case"SET_FIELD_TOUCHED":return{...e,touched:R(e.touched,t.payload.field,t.payload.value)};case"SET_FIELD_ERROR":return{...e,errors:R(e.errors,t.payload.field,t.payload.value)};case"RESET_FORM":case"SET_FORMIK_STATE":return{...e,...t.payload};case"SUBMIT_ATTEMPT":return{...e,touched:A(e.values,!0),isSubmitting:!0,submitCount:e.submitCount+1};case"SUBMIT_FAILURE":case"SUBMIT_SUCCESS":return{...e,isSubmitting:!1};default:return e}}function V({validateOnChange:e=!0,validateOnBlur:t=!0,isInitialValid:r,enableReinitialize:l=!1,onSubmit:u,...p}){const h={validateOnChange:e,validateOnBlur:t,onSubmit:u,...p},m=n(h.initialValues),v=n(h.initialErrors||{}),S=n(h.initialTouched||{}),y=n(h.initialStatus),T=n(!1),g=n({});i(()=>{},[r]),i(()=>(T.current=!0,()=>{T.current=!1}),[]);const[b,F]=a(D,{values:h.initialValues,errors:h.initialErrors||{},touched:h.initialTouched||{},status:h.initialStatus,isSubmitting:!1,isValidating:!1,submitCount:0}),A=function(e){const t=n(e);return i(()=>{t.current=e},[e]),t.current}(b),P=s((e,t)=>new Promise(r=>{const n=h.validate(e,t);void 0===n?r({}):_(n)?n.then(()=>{r({})},e=>{r(e)}):r(n)}),[h.validate]),C=s((e,t)=>new Promise(r=>{const n=h.validationSchema,i=f(n)?n(t):n;let a=t&&i.validateAt?i.validateAt(t,e):N(e,i);a.then(()=>{r({})},e=>{r(k(e))})}),[h.validationSchema]),U=s((e,t)=>new Promise(r=>r(g.current[e].validate(t))).then(e=>e,e=>e),[g]),L=s(e=>{if(null===g.current)return Promise.resolve({});const t=Object.keys(g.current).filter(e=>null!==g.current&&g.current[e]&&g.current[e].validate&&f(g.current[e].validate)),r=t.length>0?t.map(t=>U(t,O(e,t))):[Promise.resolve("DO_NOT_DELETE_YOU_WILL_BE_FIRED")];return Promise.all(r).then(e=>e.reduce((e,r,n)=>"DO_NOT_DELETE_YOU_WILL_BE_FIRED"===r?e:(r&&(e=R(e,t[n],r)),e),{}))},[U,g]),V=s((e=b.values)=>h.validationSchema||h.validate||g.current&&Object.keys(g.current).filter(e=>!!g.current[e].validate).length>0?(F({type:"SET_ISVALIDATING",payload:!0}),Promise.all([L(e),h.validationSchema?C(e):{},h.validate?P(e):{}]).then(([e,t,r])=>{const n=d.all([e,t,r],{arrayMerge:j});return c(b.errors,n)||F({type:"SET_ERRORS",payload:n}),F({type:"SET_ISVALIDATING",payload:!1}),n})):Promise.resolve({}),[h.validate,h.validationSchema,L,P,C,b.errors,b.values,g]);i(()=>{if(A.values!==b.values&&e&&!b.isSubmitting&&null!=T.current){const[e,t]=I(V());return e.then(e=>e).catch(e=>e),t}},[A.values,b.isSubmitting,b.values,V,e,T]),i(()=>{if(A.touched!==b.touched&&t&&!b.isSubmitting&&null!=T.current){const[e,t]=I(V());return e.then(e=>e).catch(e=>e),t}},[A.touched,b.isSubmitting,b.touched,V,t,T]);const M=s(e=>{const t=e&&e.values?e.values:m.current?m.current:h.initialValues,r=e&&e.errors?e.values:v.current?v.current:h.initialErrors||{},n=e&&e.touched?e.values:S.current?S.current:h.initialTouched||{},i=e&&e.status?e.status:y.current?y.current:h.initialStatus;m.current=t,v.current=r,S.current=n,y.current=i,F({type:"RESET_FORM",payload:{isSubmitting:!!e&&!!e.isSubmitting,errors:r,touched:n,status:i,values:t,isValidating:!!e&&!!e.isValidating,submitCount:e&&e.submitCount&&"number"==typeof e.submitCount?e.submitCount:0}})},[h.initialErrors,h.initialStatus,h.initialTouched,h.initialValues]);i(()=>{l&&T.current&&!c(m.current,h.initialValues)&&M()},[l,h.initialValues,M]);const w=s(e=>{if(null!==g.current&&g.current[e]&&g.current[e].validate&&f(g.current[e].validate)){const t=O(b.values,e),r=g.current[e].validate(t);return _(r)?(F({type:"SET_ISVALIDATING",payload:!0}),r.then(e=>e,e=>e).then(t=>{F({type:"SET_FIELD_ERROR",payload:{field:e,value:t}}),F({type:"SET_ISVALIDATING",payload:!1})})):(F({type:"SET_FIELD_ERROR",payload:{field:e,value:r}}),Promise.resolve(r))}return Promise.resolve()},[b.values,g]),B=s((e,{validate:t})=>{null!==g.current&&(g.current[e]={validate:t})},[g]),x=s(e=>{null!==g.current&&delete g.current[e]},[g]),G=s(e=>{if(E(e))return r=>t(r,e);function t(e,t){e.persist&&e.persist();const{name:r,id:n,outerHTML:i}=e.target,a=t||(r||n);F({type:"SET_FIELD_TOUCHED",payload:{field:a,value:!0}})}t(e)},[]),H=s(e=>{if(E(e))return r=>t(r,e);function t(e,t){let r,n=t,i=e;if(!E(e)){e.persist&&e.persist();const{type:a,name:s,id:o,value:l,checked:u,outerHTML:c}=e.target;n=t||(s||o),i=/number|range/.test(a)?(r=parseFloat(l),isNaN(r)?"":r):/checkbox/.test(a)?u:l}n&&F({type:"SET_FIELD_VALUE",payload:{field:n,value:i}})}t(e)},[]),W=s(e=>{F({type:"SET_TOUCHED",payload:e})},[]),K=s(e=>{F({type:"SET_ERRORS",payload:e})},[]),Y=s(e=>{F({type:"SET_VALUES",payload:e})},[]),$=s((e,t)=>{F({type:"SET_FIELD_ERROR",payload:{field:e,value:t}})},[]),z=s((e,t)=>{F({type:"SET_FIELD_VALUE",payload:{field:e,value:t}})},[]),q=s((e,t=!0)=>{F({type:"SET_FIELD_TOUCHED",payload:{field:e,value:t}})},[]);function J(e){f(e)?F({type:"SET_FORMIK_STATE",payload:e(b)}):F({type:"SET_FORMIK_STATE",payload:e})}const Q=s(e=>{F({type:"SET_STATUS",payload:e})},[]),X=s(e=>{F({type:"SET_ISSUBMITTING",payload:e})},[]),Z={resetForm:M,validateForm:V,validateField:w,setErrors:K,setFieldError:$,setFieldTouched:q,setFieldValue:z,setStatus:Q,setSubmitting:X,setTouched:W,setValues:Y,setFormikState:J},ee=s(()=>u(b.values,Z),[Z,u,b.values]),te=s(()=>(F({type:"SUBMIT_ATTEMPT"}),V().then(e=>{const t=0===Object.keys(e).length;t?Promise.resolve(ee()).then(()=>{T.current&&F({type:"SUBMIT_SUCCESS"})}).catch(e=>{T.current&&F({type:"SUBMIT_FAILURE"})}):T.current&&F({type:"SUBMIT_FAILURE"})})),[ee,V]),re=s(e=>{e&&e.preventDefault&&f(e.preventDefault)&&e.preventDefault(),e&&e.stopPropagation&&f(e.stopPropagation)&&e.stopPropagation(),te()},[te]),ne=s(()=>{if(h.onReset){const e=h.onReset(b.values,Z);_(e)?e.then(M):M()}else M()},[Z,h.onReset,M,b.values]),ie=s(e=>({value:O(b.values,e),error:O(b.errors,e),touched:!!O(b.touched,e),initialValue:O(m.current,e),initialTouched:!!O(S.current,e),initialError:O(v.current,e)}),[b.errors,b.touched,b.values]),ae=s((e,t)=>{const r={name:e,value:!t||"radio"!==t&&"checkbox"!==t?O(b.values,e):void 0,onChange:H,onBlur:G};return[r,ie(e)]},[ie,G,H,b.values]),se=o(()=>!c(m.current,b.values),[b.values]),oe=o(()=>void 0!==r?se?b.errors&&0===Object.keys(b.errors).length:!1!==r&&f(r)?r(h):r:b.errors&&0===Object.keys(b.errors).length,[r,se,b.errors,h]),le={...b,initialValues:m.current,initialErrors:v.current,initialTouched:S.current,initialStatus:y.current,handleBlur:G,handleChange:H,handleReset:ne,handleSubmit:re,resetForm:M,setErrors:K,setFormikState:J,setFieldTouched:q,setFieldValue:z,setFieldError:$,setStatus:Q,setSubmitting:X,setTouched:W,setValues:Y,submitForm:te,validateForm:V,validateField:w,isValid:oe,dirty:se,unregisterField:x,registerField:B,getFieldProps:ae,validateOnBlur:t,validateOnChange:e};return le}function M(t){const r=V(t),{component:n,children:i,render:a}=t;return l(C,{value:r},n?l(n,r):a?a(r):i?f(i)?i(r):g(i)?null:e.only(i):null)}function k(e){let t={};if(0===e.inner.length)return R(t,e.path,e.message);for(let r of e.inner)t[r.path]||(t=R(t,r.path,r.message));return t}function N(e,t,r=!1,n={}){let i={};for(let t in e)if(e.hasOwnProperty(t)){const r=String(t);i[r]=""!==e[r]?e[r]:void 0}return t[r?"validateSync":"validate"](i,{abortEarly:!1,context:n})}function j(e,t,r){const n=e.slice();return t.forEach(function(t,i){if(void 0===n[i]){const e=!1!==r.clone,a=e&&r.isMergeableObject(t);n[i]=a?d(Array.isArray(t)?[]:{},t,r):t}else r.isMergeableObject(t)?n[i]=d(e[i],t,r):-1===e.indexOf(t)&&n.push(t)}),n}function w(e,t){const r=L();return r.getFieldProps(e,t)}function B({validate:e,name:t,render:r,children:n,as:a="input",component:s,...o}){const{...u}=L();i(()=>{},[]),i(()=>(u.registerField(t,{validate:e}),()=>{u.unregisterField(t)}),[u,t,e]);const[c,d]=u.getFieldProps(t,o.type),p={field:c,form:u};if(r)return r(p);if(f(n))return n({...p,meta:d});if(s){if("string"==typeof s){const{innerRef:e,...t}=o;return l(s,{ref:e,...c,...t},n)}return l(s,{field:c,form:u,...o},n)}if("string"==typeof a){const{innerRef:e,...t}=o;return l(a,{ref:e,...c,...t},n)}return l(a,{...c,...o},n)}const x=B;function G(e){const{handleReset:t,handleSubmit:r}=L();return l("form",Object.assign({onSubmit:r,onReset:t},e))}function H({mapPropsToValues:e=(e=>{let t={};for(let r in e)e.hasOwnProperty(r)&&"function"!=typeof e[r]&&(t[r]=e[r]);return t}),...t}){return function(r){const n=r.displayName||r.name||r.constructor&&r.constructor.name||"Component";class i extends u{constructor(){super(...arguments),this.validate=(e=>t.validate(e,this.props)),this.validationSchema=(()=>f(t.validationSchema)?t.validationSchema(this.props):t.validationSchema),this.handleSubmit=((e,r)=>t.handleSubmit(e,{...r,props:this.props})),this.renderFormComponent=(e=>l(r,Object.assign({},this.props,e)))}render(){const{...r}=this.props;return l(M,Object.assign({},r,t,{validate:t.validate&&this.validate,validationSchema:t.validationSchema&&this.validationSchema,initialValues:e(this.props),initialStatus:t.mapPropsToStatus&&t.mapPropsToStatus(this.props),initialErrors:t.mapPropsToErrors&&t.mapPropsToErrors(this.props),initialTouched:t.mapPropsToTouched&&t.mapPropsToTouched(this.props),onSubmit:this.handleSubmit,render:this.renderFormComponent}))}}return i.displayName=`WithFormik(${n})`,m(i,r)}}function W(e){const t=t=>l(U,null,r=>l(e,Object.assign({},t,{formik:r}))),r=e.displayName||e.name||e.constructor&&e.constructor.name||"Component";return t.WrappedComponent=e,t.displayName=`FormikConnect(${r})`,m(t,e)}G.displayName="Form";const K=(e,t,r)=>{const n=[...e||[]],i=n[t];return n.splice(t,1),n.splice(r,0,i),n},Y=(e,t,r)=>{const n=[...e||[]],i=n[t];return n[t]=n[r],n[r]=i,n},$=(e,t,r)=>{const n=[...e||[]];return n.splice(t,0,r),n},z=(e,t,r)=>{const n=[...e||[]];return n[t]=r,n};class q extends u{constructor(e){super(e),this.updateArrayField=((e,t,r)=>{const{name:n,validateOnChange:i,formik:{setFormikState:a,validateForm:s}}=this.props;a(i=>{let a="function"==typeof r?r:e,s="function"==typeof t?t:e;return{...i,values:R(i.values,n,e(O(i.values,n))),errors:r?R(i.errors,n,a(O(i.errors,n))):i.errors,touched:t?R(i.touched,n,s(O(i.touched,n))):i.touched}},()=>{i&&s()})}),this.push=(e=>this.updateArrayField(t=>[...t||[],v(e)],!1,!1)),this.handlePush=(e=>()=>this.push(e)),this.swap=((e,t)=>this.updateArrayField(r=>Y(r,e,t),!0,!0)),this.handleSwap=((e,t)=>()=>this.swap(e,t)),this.move=((e,t)=>this.updateArrayField(r=>K(r,e,t),!0,!0)),this.handleMove=((e,t)=>()=>this.move(e,t)),this.insert=((e,t)=>this.updateArrayField(r=>$(r,e,t),t=>$(t,e,null),t=>$(t,e,null))),this.handleInsert=((e,t)=>()=>this.insert(e,t)),this.replace=((e,t)=>this.updateArrayField(r=>z(r,e,t),!1,!1)),this.handleReplace=((e,t)=>()=>this.replace(e,t)),this.unshift=(e=>{let t=-1;return this.updateArrayField(r=>{const n=r?[e,...r]:[e];return t<0&&(t=n.length),n},e=>{const r=e?[null,...e]:[null];return t<0&&(t=r.length),r},e=>{const r=e?[null,...e]:[null];return t<0&&(t=r.length),r}),t}),this.handleUnshift=(e=>()=>this.unshift(e)),this.handleRemove=(e=>()=>this.remove(e)),this.handlePop=(()=>()=>this.pop()),this.remove=this.remove.bind(this),this.pop=this.pop.bind(this)}remove(e){let t;return this.updateArrayField(r=>{const n=r?[...r]:[];return t||(t=n[e]),f(n.splice)&&n.splice(e,1),n},!0,!0),t}pop(){let e;return this.updateArrayField(t=>{const r=t;return e||(e=r&&r.pop&&r.pop()),r},!0,!0),e}render(){const t={push:this.push,pop:this.pop,swap:this.swap,move:this.move,insert:this.insert,replace:this.replace,unshift:this.unshift,remove:this.remove,handlePush:this.handlePush,handlePop:this.handlePop,handleSwap:this.handleSwap,handleMove:this.handleMove,handleInsert:this.handleInsert,handleReplace:this.handleReplace,handleUnshift:this.handleUnshift,handleRemove:this.handleRemove},{component:r,render:n,children:i,name:a,formik:{...s}}=this.props,o={...t,form:s,name:a};return r?l(r,o):n?n(o):i?"function"==typeof i?i(o):g(i)?null:e.only(i):null}}q.defaultProps={validateOnChange:!0};const J=W(q);class Q extends u{shouldComponentUpdate(e){return O(this.props.formik.errors,this.props.name)!==O(e.formik.errors,this.props.name)||O(this.props.formik.touched,this.props.name)!==O(e.formik.touched,this.props.name)||Object.keys(this.props).length!==Object.keys(e).length}render(){let{component:e,formik:t,render:r,children:n,name:i,...a}=this.props;const s=O(t.touched,i),o=O(t.errors,i);return s&&o?r?f(r)?r(o):null:n?f(n)?n(o):null:e?l(e,a,o):o:null}}const X=W(Q);export{X as ErrorMessage,x as FastField,B as Field,J as FieldArray,G as Form,M as Formik,U as FormikConsumer,C as FormikProvider,W as connect,F as getActiveElement,O as getIn,$ as insert,g as isEmptyChildren,f as isFunction,b as isInputEvent,y as isInteger,T as isNaN,S as isObject,_ as isPromise,E as isString,I as makeCancelable,K as move,z as replace,R as setIn,A as setNestedObjectValues,Y as swap,w as useField,V as useFormik,L as useFormikContext,N as validateYupSchema,H as withFormik,k as yupToFormErrors};
//# sourceMappingURL=formik.es.production.js.map