vuex-multi-tab-state
Version:
Share and synchronize status between multiple tabs with this plugin for Vuex.
3 lines (2 loc) • 1.92 kB
JavaScript
import{set as t,pick as e,remove as a}from"dot-object";function n(){return(n=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var a=arguments[e];for(var n in a)Object.prototype.hasOwnProperty.call(a,n)&&(t[n]=a[n])}return t}).apply(this,arguments)}class r{constructor(t){this.tabId=Math.random().toString(36).substring(2,15)+Math.random().toString(36).substring(2,15),this.window=t}storageAvailable(){const t="vuex-multi-tab-state-test";try{return this.window.localStorage.setItem(t,t),this.window.localStorage.removeItem(t),!0}catch(t){return!1}}saveState(t,e){const a=JSON.stringify({id:this.tabId,state:e});this.window.localStorage.setItem(t,a)}fetchState(t,e){const a=this.window.localStorage.getItem(t);if(a)try{e(JSON.parse(a).state)}catch(e){console.warn(`State saved in localStorage with key ${t} is invalid!`)}}addEventListener(t,e){return this.window.addEventListener("storage",a=>{if(a.newValue&&a.key===t)try{const t=JSON.parse(a.newValue);t.id!==this.tabId&&e(t.state)}catch(e){console.warn(`New state saved in localStorage with key ${t} is invalid`)}})}}export default function(o){const s=new r(window);let i="vuex-multi-tab",c=[],l=t=>t,u=t=>t;if(o&&(i=o.key?o.key:i,c=o.statesPaths?o.statesPaths:c,l=o.onBeforeReplace||l,u=o.onBeforeSave||u),!s.storageAvailable())throw new Error("Local storage is not available!");function d(r,o){const s=l(o);s&&r.replaceState(function(r,o){if(0===c.length)return n({},o);const s=function t(e){return Array.isArray(e)?e.map(e=>t(e)):"object"==typeof e&&null!==e?Object.keys(e).reduce((a,n)=>(a[n]=t(e[n]),a),{}):e}(r);return c.forEach(n=>{const r=e(n,o);void 0===r?a(n,s):t(n,r,s)}),s}(r.state,s))}return a=>{s.fetchState(i,t=>{d(a,t)}),s.addEventListener(i,t=>{d(a,t)}),a.subscribe((a,n)=>{let r=n;c.length>0&&(r=function(a){const n={};return c.forEach(r=>{t(r,e(r,a),n)}),n}(n)),r=u(r),r&&s.saveState(i,r)})}}
//# sourceMappingURL=index.modern.js.map