UNPKG

@provydon/vue-auto-save

Version:

A Vue 3 composable that autosaves forms with debounce, optional field skipping, and blockable watchers.

2 lines (1 loc) 1.71 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("vue"),P=["save","applicationId","isDirty","processing","errors","hasErrors","recentlySuccessful","wasSuccessful","data","transform","get","post","put","patch","delete","cancel","reset","clearErrors","setError","setData"];function q(c,h){const{debounce:n=3e3,skipFields:T=[],skipInertiaFields:I=!0,deep:O=!0,debug:u=!1,serialize:D=JSON.stringify,compare:o,saveOnInit:g=!1,onSave:W,onBeforeSave:m,onAfterSave:y,onError:l}=h,a=s.ref(!1),r=s.ref(!0);let i=()=>{},f=()=>{};const j=(t=1e3)=>{r.value=!1,i(),f(),setTimeout(()=>{r.value=!0},t)},z=(t=null)=>{if(r.value=!0,i(),f(),t===null)d(),o?p=null:v=null,S();else{const e=A(S,t);f=e.cancel,e.call()}},d=()=>{const t=s.isRef(c)?s.unref(c):c,e={};for(const b of Object.keys(t))I&&P.includes(b)||T.includes(b)||(e[b]=t[b]);return e};let v=g?null:D(d()),p=o?g?null:d():null;const S=()=>{if(!r.value)return;const t=d();if(o){if(p&&o(p,t))return;p=t}else{const e=D(t);if(v!==null&&e===v)return;v=e}u&&console.log("[AutoSave] Detected changes. Saving..."),a.value=!0;try{m==null||m(),Promise.resolve(W()).then(()=>{y==null||y(),u&&console.log("[AutoSave] Save successful.")}).catch(e=>{l==null||l(e),u&&console.error("[AutoSave] Save failed:",e)}).finally(()=>{a.value=!1})}catch(e){l==null||l(e),u&&console.error("[AutoSave] Immediate error:",e),a.value=!1}},F=A(S,n),w=F.call;i=F.cancel;const k=s.watch(c,w,{deep:O,flush:"post"});return s.onScopeDispose(()=>{k(),i(),f()}),g&&S(),{isAutoSaving:a,blockWatcher:j,unblockWatcher:z,stop:k}}function A(c,h){let n;return{call:()=>{clearTimeout(n),n=setTimeout(()=>c(),h)},cancel:()=>{clearTimeout(n)}}}exports.useAutoSaveForm=q;