UNPKG

flemme

Version:

Framework agnostic form state manager / handler / abstraction

3 lines (2 loc) 2.14 kB
const t=(t,e,r=t.length)=>[...t.slice(0,r),e,...t.slice(r)],e=(t,e)=>t.filter(((t,r)=>r!==e));function r({get:t,set:e,isEqual:r,cloneDeep:s}){return function(n){const{validate:a=()=>{},validationTriggers:i=[]}=n;let o=s(n.initial),l=s(o);const u=new Map,c=new Set,d=new Set;let h,f=!1;const v={blur:new Set,change:new Set,focus:new Set,reset:new Set,validated:new Set,submit:new Set,submitted:new Set},g=(t,e)=>{v[t].forEach((t=>t(e)))},w={get initialValues(){return o},get values(){return l},get errors(){return h},get isValid(){return void 0===h},get isDirty(){return!r(l,o)},get:e=>t(l,e),getInitial:e=>t(o,e),isDirtyAt:e=>!r(t(l,e),t(o,e)),isVisited:t=>t?((t,e)=>{for(const r of t)if(e(r))return!0;return!1})(c,(e=>e.startsWith(t))):c.size>0,set:(...t)=>1===t.length?p(t[0]):b(t[0],t[1]),blur:t=>{g("blur",{path:t})},focus:t=>{c.add(t),f&&d.add(t),g("focus",{path:t})},reset:(t=o)=>{if(f)throw new Error("cannot reset form while submitting");const e=o;o=s(t),l=s(t),c.clear(),h=void 0,g("reset",{path:"",previous:e,next:o})},resetAt:(...r)=>{const[s,n]=r,a=t(o,s);n&&e(o,s,n);const i=t(o,s);e(l,s,i),((t,e)=>{((t,e,r)=>{for(const s of t)e(s)&&r(s)})(t,e,(e=>t.delete(e)))})(c,(t=>t.startsWith(s))),g("reset",{path:s,previous:a,next:i})},on:(...t)=>2===t.length?m(...t):S(...t),submit:async()=>{if(w.validate(),w.errors)throw new Error("invalid form data");f=!0;const t=l;try{g("submit",{values:t});const e=await n.submit(t);return f=!1,g("submitted",{values:t,error:void 0}),w.reset(w.values),e}catch(e){g("submitted",{values:t,error:e})}finally{f=!1,E()}},validate:()=>{h=a(l),g("validated",{errors:h})}},p=t=>{const e=l;l=s(t),f&&u.set("",t),g("change",{path:"",previous:e,next:l})},b=(r,s)=>{const n=t(l,r);e(l,r,s),f&&u.set(r,s),g("change",{path:r,previous:n,next:s})},m=(t,e)=>(v[t].add(e),()=>v[t].delete(e)),S=(t,e,r)=>{const s=t=>{t.path&&!t.path.startsWith(e)||r(t)};return v[t].add(s),()=>v[t].delete(s)},E=()=>{d.forEach((t=>c.add(t))),d.clear(),u.forEach(((t,e)=>w.set(e,t))),u.clear()};return i.forEach((t=>{w.on(t,(()=>w.validate()))})),w}}export{r as Flemme,t as addItem,e as removeItem}; //# sourceMappingURL=main.js.map