UNPKG

auto-form-sync

Version:

Auto-save and restore form data using Local/Session/Custom Storage.

3 lines (2 loc) 3.83 kB
"use strict";var e=require("react");const o={save(e,o){try{localStorage.setItem(e,o)}catch(e){console.error("[auto-form-sync] Failed to save to localStorage:",e)}},load(e){try{return localStorage.getItem(e)}catch(e){return console.error("[auto-form-sync] Failed to load from localStorage:",e),null}},remove(e){try{localStorage.removeItem(e)}catch(e){console.error("[auto-form-sync] Failed to remove from localStorage:",e)}}},t={save(e,o){try{sessionStorage.setItem(e,o)}catch(e){console.error("[auto-form-sync] Failed to save to sessionStorage:",e)}},load(e){try{return sessionStorage.getItem(e)}catch(e){return console.error("[auto-form-sync] Failed to load from sessionStorage:",e),null}},remove(e){try{sessionStorage.removeItem(e)}catch(e){console.error("[auto-form-sync] Failed to remove from sessionStorage:",e)}}};var r;function n(e,o){const t=e.id||e.classList[0],r=(o?.key||t).trim();if(""==r)throw new Error(`[auto-form-sync] Unable to find the storage key for this form: ${e}`);const n=document.querySelectorAll("form");if(Array.from(n).some(e=>e.dataset.key===r))throw new Error("[auto-form-sync] The key already exists. Please use different key or id name.");return r}function a(e){try{return JSON.parse(e)}catch(e){return null}}function s(e){return JSON.stringify(e)}!function(e){e.LocalStorage="LocalStorage",e.SessionStorage="SessionStorage",e.Custom="Custom"}(r||(r={}));const c=e=>{const{storage:n}=e;if(!n||n===r.SessionStorage)return t;if(n===r.LocalStorage)return o;if("object"==typeof n)return n;throw new Error(`[auto-form-sync] Invalid storage option: ${n}`)},i=(e,o)=>!("submit"===e.type||e instanceof HTMLButtonElement)&&(!e.disabled&&!e.dataset?.nosync&&!((e,o=[])=>o.some(o=>"string"==typeof o?o===e.id||o===e.name:o(e)))(e,o.exclude));async function u(e,o={}){const t=c(o),r=(e=>e.serializer??s)(o),a=(e=>e.debounce??300)(o),u=n(e,o);if(!u)return console.warn("[auto-form-sync] Unable to attach listeners: no storage key."),()=>{};const l=function(e,o=300){let t;return function(...r){clearTimeout(t),t=setTimeout(e,o,...r)}}(()=>{const n=((e,o)=>Array.from(e.elements).filter(e=>i(e,o)).map(e=>({name:e.name,id:e.id,value:"checkbox"==e.type?e.checked?"true":"false":e.value})))(e,o),a=r(n);t.save(u,a),o.onSave?.(n)},a),m=[];for(const t of e.elements){if(!i(t,o))continue;const e=t.type,r="checkbox"===e||"radio"===e||"SELECT"===t.tagName?"change":"input";t.addEventListener(r,()=>l()),m.push(()=>t.removeEventListener(r,()=>l()))}const f=async r=>{if("function"==typeof e.onsubmit){const o=e.onsubmit.call(e,r);o instanceof Promise&&await o}o.clearOnSubmit&&(await t.remove(u),o.onClear?.())};return e.addEventListener("submit",f),m.push(()=>e.removeEventListener("submit",f)),()=>m.forEach(e=>e())}async function l(e,o={}){const t=document.querySelector(e);if(!t)throw console.warn(`[auto-form-sync] Form not found: ${e}`),new Error(`[auto-form-sync] Form not found: ${e}`);return(void 0===o?.restoreOnLoad||o.restoreOnLoad)&&await async function(e,o){const t=c(o),r=o?.deserializer||a,s=n(e,o),i=await t.load(s);if(!i||!r)return void console.warn(`[auto-form-sync] Unable to load serialized data for this form: ${e}`);const u=r(i);u&&(u?.forEach(o=>{const t=e.querySelector(`[name="${o.name}"]`)??(o.id?e.querySelector(`#${o.id}`):null);t&&(t.value=o.value.toString()),"checkbox"==t?.type&&(t.checked="true"===o?.value)}),o?.onRestore?.(u))}(t,o),console.warn("[auto-form-sync] Initialized on form:",t),await u(t,o)}exports.autoFormSync=l,exports.useAutoFormSync=function(o,t={}){const r=e.useRef(null);e.useEffect(()=>{let e=!1;return(async()=>{try{e||null!=r.current||(r.current=await l(o,t))}catch(e){console.error("[useAutoFormSync] Error initializing form sync:",e)}})(),()=>{e=!0,"function"==typeof r.current&&(r.current(),r.current=null)}},[o,t])}; //# sourceMappingURL=index.min.js.map