UNPKG

vuex-multi-tab-state

Version:

Share and synchronize status between multiple tabs with this plugin for Vuex.

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