redux-state-sync
Advanced tools
Comparing version 2.0.3 to 2.0.4
/* global jest window localStorage describe it test expect */ | ||
import { generateUuidForAction, isActionAllowed } from '../dist/syncState'; | ||
import { generateUuidForAction, isActionAllowed, createStateSyncMiddleware } from '../dist/syncState'; | ||
@@ -47,1 +47,17 @@ describe('action should have uuid', () => { | ||
}); | ||
describe('state should be mapped', () => { | ||
it('state mapped to JSON', () => { | ||
const mockState = { | ||
test: 'Test', | ||
}; | ||
const mockStore = { | ||
getState: () => mockState, | ||
dispatch: () => {}, | ||
}; | ||
const next = action => expect(action.payload).toEqual(JSON.stringify(mockState)); | ||
createStateSyncMiddleware({ prepareState: JSON.stringify })(mockStore)(next)({ type: '&_SEND_INIT_STATE' }); | ||
}); | ||
}); |
@@ -6,3 +6,3 @@ 'use strict'; | ||
}); | ||
exports.initStateWithPrevTab = exports.withReduxStateSync = exports.createStateSyncMiddleware = undefined; | ||
exports.initStateWithPrevTab = exports.withReduxStateSync = exports.createReduxStateSync = exports.createStateSyncMiddleware = undefined; | ||
exports.generateUuidForAction = generateUuidForAction; | ||
@@ -29,3 +29,6 @@ exports.isActionAllowed = isActionAllowed; | ||
whitelist: [], | ||
broadcastChannelOption: null | ||
broadcastChannelOption: null, | ||
prepareState: function prepareState(state) { | ||
return state; | ||
} | ||
}; | ||
@@ -124,2 +127,3 @@ | ||
var channel = new _broadcastChannel2.default(config.channel, config.broadcastChannelOption); | ||
var prepareState = config.prepareState || defaultConfig.prepareState; | ||
@@ -143,3 +147,3 @@ return function (_ref3) { | ||
if (getState()) { | ||
stampedAction.payload = getState(); | ||
stampedAction.payload = prepareState(getState()); | ||
channel.postMessage(stampedAction); | ||
@@ -162,17 +166,26 @@ } | ||
// init state with other tab's state | ||
var withReduxStateSync = exports.withReduxStateSync = function withReduxStateSync(appReducer) { | ||
return function (state, action) { | ||
var initState = state; | ||
if (action.type === RECEIVE_INIT_STATE) { | ||
initState = action.payload; | ||
} | ||
return appReducer(initState, action); | ||
var createReduxStateSync = exports.createReduxStateSync = function createReduxStateSync(_ref4) { | ||
var prepareState = _ref4.prepareState; | ||
return function (appReducer) { | ||
return function (state, action) { | ||
var initState = state; | ||
if (action.type === RECEIVE_INIT_STATE) { | ||
initState = prepareState(action.payload); | ||
} | ||
return appReducer(initState, action); | ||
}; | ||
}; | ||
}; | ||
var initStateWithPrevTab = exports.initStateWithPrevTab = function initStateWithPrevTab(_ref4) { | ||
var dispatch = _ref4.dispatch; | ||
// init state with other tab's state | ||
var withReduxStateSync = exports.withReduxStateSync = createReduxStateSync({ | ||
prepareState: function prepareState(state) { | ||
return state; | ||
} | ||
}); | ||
var initStateWithPrevTab = exports.initStateWithPrevTab = function initStateWithPrevTab(_ref5) { | ||
var dispatch = _ref5.dispatch; | ||
dispatch(getIniteState()); | ||
}; |
@@ -479,3 +479,3 @@ (function webpackUniversalModuleDefinition(root, factory) { | ||
}); | ||
exports.initStateWithPrevTab = exports.withReduxStateSync = exports.createStateSyncMiddleware = undefined; | ||
exports.initStateWithPrevTab = exports.withReduxStateSync = exports.createReduxStateSync = exports.createStateSyncMiddleware = undefined; | ||
exports.generateUuidForAction = generateUuidForAction; | ||
@@ -502,3 +502,6 @@ exports.isActionAllowed = isActionAllowed; | ||
whitelist: [], | ||
broadcastChannelOption: null | ||
broadcastChannelOption: null, | ||
prepareState: function prepareState(state) { | ||
return state; | ||
} | ||
}; | ||
@@ -597,2 +600,3 @@ | ||
var channel = new _broadcastChannel2.default(config.channel, config.broadcastChannelOption); | ||
var prepareState = config.prepareState || defaultConfig.prepareState; | ||
@@ -616,3 +620,3 @@ return function (_ref3) { | ||
if (getState()) { | ||
stampedAction.payload = getState(); | ||
stampedAction.payload = prepareState(getState()); | ||
channel.postMessage(stampedAction); | ||
@@ -635,16 +639,25 @@ } | ||
// init state with other tab's state | ||
var withReduxStateSync = exports.withReduxStateSync = function withReduxStateSync(appReducer) { | ||
return function (state, action) { | ||
var initState = state; | ||
if (action.type === RECEIVE_INIT_STATE) { | ||
initState = action.payload; | ||
} | ||
return appReducer(initState, action); | ||
var createReduxStateSync = exports.createReduxStateSync = function createReduxStateSync(_ref4) { | ||
var prepareState = _ref4.prepareState; | ||
return function (appReducer) { | ||
return function (state, action) { | ||
var initState = state; | ||
if (action.type === RECEIVE_INIT_STATE) { | ||
initState = prepareState(action.payload); | ||
} | ||
return appReducer(initState, action); | ||
}; | ||
}; | ||
}; | ||
var initStateWithPrevTab = exports.initStateWithPrevTab = function initStateWithPrevTab(_ref4) { | ||
var dispatch = _ref4.dispatch; | ||
// init state with other tab's state | ||
var withReduxStateSync = exports.withReduxStateSync = createReduxStateSync({ | ||
prepareState: function prepareState(state) { | ||
return state; | ||
} | ||
}); | ||
var initStateWithPrevTab = exports.initStateWithPrevTab = function initStateWithPrevTab(_ref5) { | ||
var dispatch = _ref5.dispatch; | ||
dispatch(getIniteState()); | ||
@@ -651,0 +664,0 @@ }; |
@@ -1,2 +0,2 @@ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.reduxStateSync=t():e.reduxStateSync=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=5)}([function(e,t,n){"use strict";function r(e){return!(!e||"function"!=typeof e.then)}function o(e){return e||(e=0),new Promise(function(t){return setTimeout(t,e)})}function i(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function a(e){e||(e=5);for(var t="",n="abcdefghijklmnopqrstuvwxzy0123456789",r=0;r<e;r++)t+=n.charAt(Math.floor(Math.random()*n.length));return t}function s(){var e=(new Date).getTime();return e===u?(c++,1e3*e+c):(u=e,c=0,1e3*e)}t.a=r,t.c=o,t.e=i,t.d=a,t.b=s;var u=0,c=0},function(e,t){e.exports=!1},function(e,t,n){"use strict";function r(e){return e||(e={}),e=JSON.parse(JSON.stringify(e)),void 0===e.webWorkerSupport&&(e.webWorkerSupport=!0),e.idb||(e.idb={}),e.idb.ttl||(e.idb.ttl=45e3),e.idb.fallbackInterval||(e.idb.fallbackInterval=150),e.localstorage||(e.localstorage={}),e.localstorage.removeTimeout||(e.localstorage.removeTimeout=6e4),e.node||(e.node={}),e.node.ttl||(e.node.ttl=12e4),void 0===e.node.useFastPath&&(e.node.useFastPath=!0),e}t.a=r},function(e,t,n){"use strict";function r(e){for(var t=o()-e.ttl,n=e.set[Symbol.iterator]();;){var r=n.next().value;if(!r)return;if(!(e.timeMap.get(r)<t))return;e.timeMap.delete(r),e.set.delete(r)}}function o(){return(new Date).getTime()}var i=function(e){this.ttl=e,this.set=new Set,this.timeMap=new Map,this.has=this.set.has.bind(this.set)};i.prototype={add:function(e){this.timeMap.set(e,o()),this.set.add(e),r(this)},clear:function(){this.set.clear(),this.timeMap.clear()}},t.a=i},function(e,t,n){"use strict";function r(e,t,n){var r=e.method.microSeconds(),o={time:r,type:t,data:n};return(e._prepP?e._prepP:Promise.resolve()).then(function(){return e.method.postMessage(e._state,o)})}function o(e){var t=e.method.create(e.name,e.options);n.i(d.a)(t)?(e._prepP=t,t.then(function(t){e._state=t})):e._state=t}function i(e){return e._addEL.message.length>0||e._addEL.internal.length>0}function a(e,t,n){e._addEL[t].push(n),u(e)}function s(e,t,n){e._addEL[t]=e._addEL[t].filter(function(e){return e!==n}),c(e)}function u(e){if(!e._iL&&i(e)){var t=function(t){e._addEL[t.type].forEach(function(e){t.time>=e.time&&e.fn(t.data)})},n=e.method.microSeconds();e._prepP?e._prepP.then(function(){e._iL=!0,e.method.onMessage(e._state,t,n)}):(e._iL=!0,e.method.onMessage(e._state,t,n))}}function c(e){if(e._iL&&!i(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}Object.defineProperty(t,"__esModule",{value:!0});var d=n(0),f=n(6),l=n(2),p=function(e,t){this.name=e,this.options=n.i(l.a)(t),this.method=n.i(f.a)(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._befC=[],this._prepP=null,o(this)};p._pubkey=!0,p.clearNodeFolder=function(e){e=n.i(l.a)(e);var t=n.i(f.a)(e);return"node"===t.type?t.clearNodeFolder().then(function(){return!0}):Promise.resolve(!1)},p.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return r(this,"message",e)},postInternal:function(e){return r(this,"internal",e)},set onmessage(e){var t=this.method.microSeconds(),n={time:t,fn:e};s(this,"message",this._onML),e&&"function"==typeof e?(this._onML=n,a(this,"message",n)):this._onML=null},addEventListener:function(e,t){a(this,e,{time:this.method.microSeconds(),fn:t})},removeEventListener:function(e,t){s(this,e,this._addEL[e].find(function(e){return e.fn===t}))},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP?this._prepP:Promise.resolve();return this._onML=null,this._addEL.message=[],t.then(function(){return Promise.all(e._befC.map(function(e){return e()}))}).then(function(){return e.method.close(e._state)})}},get type(){return this.method.type}},t.default=p},function(e,t,n){"use strict";function r(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function o(){return""+r()+r()+"-"+r()+"-"+r()+"-"+r()+"-"+r()+r()+r()}function i(e){var t=e;return t.$uuid=o(),t.$wuid=w,t}function a(e){var t=e.predicate,n=e.blacklist,r=e.whitelist,o=function(){return!0};return t&&"function"==typeof t?o=t:Array.isArray(n)?o=function(e){return n.indexOf(e)<0}:Array.isArray(r)&&(o=function(e){return r.indexOf(e)>=0}),o}function s(e){var t=e.channel,n=e.dispatch,r=e.allowed,o=!1,i={};t.onmessage=function(e){if(e.$wuid!==w&&e.type!==p&&e.$uuid&&e.$uuid!==d)if(e.type!==f||i[e.$wuid]){if(e.type===l&&!i[e.$wuid])return void(o||(o=!0,n(b(e.payload))));r(e.type)&&(d=e.$uuid,n(e))}else i[e.$wuid]=!0,n(v())}}Object.defineProperty(t,"__esModule",{value:!0}),t.initStateWithPrevTab=t.withReduxStateSync=t.createStateSyncMiddleware=void 0,t.generateUuidForAction=i,t.isActionAllowed=a,t.createMessageListener=s;var u=n(4),c=function(e){return e&&e.__esModule?e:{default:e}}(u),d=0,f="&_GET_INIT_STATE",l="&_SEND_INIT_STATE",p="&_RECEIVE_INIT_STATE",m={channel:"redux_state_sync",predicate:null,blacklist:[],whitelist:[],broadcastChannelOption:null},h=function(){return{type:f}},v=function(){return{type:l}},b=function(e){return{type:p,payload:e}},w=o(),g=!1;t.createStateSyncMiddleware=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m,t=a(e),n=new c.default(e.channel,e.broadcastChannelOption);return function(e){var r=e.getState,o=e.dispatch;return function(e){return function(a){if(g||(g=!0,s({channel:n,dispatch:o,allowed:t})),a&&!a.$uuid){var u=i(a);d=u.$uuid;try{if(a.type===l)return r()&&(u.payload=r(),n.postMessage(u)),e(a);(t(u.type)||a.type===f)&&n.postMessage(u)}catch(e){console.error("Your browser doesn't support cross tab communication")}}return e(a)}}}},t.withReduxStateSync=function(e){return function(t,n){var r=t;return n.type===p&&(r=n.payload),e(r,n)}},t.initStateWithPrevTab=function(e){(0,e.dispatch)(h())}},function(e,t,n){"use strict";function r(e){if(e.type){var t=c.find(function(t){return t.type===e.type});if(t)return t;throw new Error("method-type "+e.type+" not found")}var n=c;e.webWorkerSupport||i.a||(n=c.filter(function(e){return"idb"!==e.type}));var r=n.find(function(e){return e.canBeUsed()});if(r)return r;throw new Error("No useable methode found:"+JSON.stringify(c.map(function(e){return e.type})))}t.a=r;var o=n(1),i=n.n(o),a=n(9),s=n(7),u=n(8),c=[a.a,s.a,u.a];if(i.a){var d=n(10);"function"==typeof d.canBeUsed&&c.push(d)}},function(e,t,n){"use strict";function r(){return"undefined"!=typeof indexedDB?indexedDB:void 0!==window.mozIndexedDB?window.mozIndexedDB:void 0!==window.webkitIndexedDB?window.webkitIndexedDB:void 0!==window.msIndexedDB&&window.msIndexedDB}function o(e){var t=r(),n=P+e,o=t.open(n,1);return o.onupgradeneeded=function(e){e.target.result.createObjectStore(C,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){o.onerror=function(e){return t(e)},o.onsuccess=function(){e(o.result)}})}function i(e,t,n){var r=(new Date).getTime(),o={uuid:t,time:r,data:n},i=e.transaction([C],"readwrite");return new Promise(function(e,t){i.oncomplete=function(){return e()},i.onerror=function(e){return t(e)},i.objectStore(C).add(o)})}function a(e,t){var n=e.transaction(C).objectStore(C),r=[],o=IDBKeyRange.bound(t+1,1/0);return new Promise(function(e){n.openCursor(o).onsuccess=function(t){var n=t.target.result;n?(r.push(n.value),n.continue()):e(r)}})}function s(e,t){var n=e.transaction([C],"readwrite").objectStore(C).delete(t);return new Promise(function(e){n.onsuccess=function(){return e()}})}function u(e,t){var n=(new Date).getTime()-t,r=e.transaction(C).objectStore(C),o=[];return new Promise(function(e){r.openCursor().onsuccess=function(t){var r=t.target.result;if(r){var i=r.value;if(!(i.time<n))return void e(o);o.push(i),r.continue()}else e(o)}})}function c(e,t){return u(e,t).then(function(t){return Promise.all(t.map(function(t){return s(e,t.id)}))})}function d(e,t){return t=n.i(k.a)(t),o(e).then(function(r){var o={closed:!1,lastCursorId:0,channelName:e,options:t,uuid:n.i(_.d)(10),eMIs:new S.a(2*t.idb.ttl),writeBlockPromise:Promise.resolve(),messagesCallback:null,readQueuePromises:[],db:r};return f(o),o})}function f(e){if(!e.closed)return p(e).then(function(){return n.i(_.c)(e.options.idb.fallbackInterval)}).then(function(){return f(e)})}function l(e,t){return e.uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time<t.messagesCallbackTime))}function p(e){return e.closed?Promise.resolve():e.messagesCallback?a(e.db,e.lastCursorId).then(function(t){return t.map(function(t){return t.id>e.lastCursorId&&(e.lastCursorId=t.id),t}).filter(function(t){return l(t,e)}).sort(function(e,t){return e.time-t.time}).forEach(function(t){e.messagesCallback&&(e.eMIs.add(t.id),e.messagesCallback(t.data))}),Promise.resolve()}):Promise.resolve()}function m(e){e.closed=!0,e.db.close()}function h(e,t){return e.writeBlockPromise=e.writeBlockPromise.then(function(){return i(e.db,e.uuid,t)}).then(function(){0===n.i(_.e)(0,10)&&c(e.db,e.options.idb.ttl)}),e.writeBlockPromise}function v(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t,p(e)}function b(){return!y.a&&!!r()}function w(e){return 2*e.idb.fallbackInterval}var g=n(1),y=n.n(g),_=n(0),S=n(3),k=n(2),M=_.b,P="pubkey.broadcast-channel-0-",C="messages";t.a={create:d,close:m,onMessage:v,postMessage:h,canBeUsed:b,type:"idb",averageResponseTime:w,microSeconds:M}},function(e,t,n){"use strict";function r(){var e;if("undefined"==typeof window)return null;try{e=window.localStorage,e=window["ie8-eventlistener/storage"]||window.localStorage}catch(e){}return e}function o(e){return g+e}function i(e,t){return new Promise(function(r){n.i(b.c)().then(function(){var i=o(e.channelName),a={token:n.i(b.d)(10),time:(new Date).getTime(),data:t,uuid:e.uuid},s=JSON.stringify(a);localStorage.setItem(i,s);var u=document.createEvent("Event");u.initEvent("storage",!0,!0),u.key=i,u.newValue=s,window.dispatchEvent(u),r()})})}function a(e,t){var n=o(e),r=function(e){e.key===n&&t(JSON.parse(e.newValue))};return window.addEventListener("storage",r),r}function s(e){window.removeEventListener("storage",e)}function u(e,t){if(t=n.i(v.a)(t),!f())throw new Error("BroadcastChannel: localstorage cannot be used");var r=n.i(b.d)(10),o=new h.a(t.localstorage.removeTimeout),i={channelName:e,uuid:r,eMIs:o};return i.listener=a(e,function(e){i.messagesCallback&&e.uuid!==r&&e.token&&!o.has(e.token)&&(e.data.time&&e.data.time<i.messagesCallbackTime||(o.add(e.token),i.messagesCallback(e.data)))}),i}function c(e){s(e.listener)}function d(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t}function f(){return!m.a&&!!r()}function l(){return 120}var p=n(1),m=n.n(p),h=n(3),v=n(2),b=n(0),w=b.b,g="pubkey.broadcastChannel-";t.a={create:u,close:c,onMessage:d,postMessage:i,canBeUsed:f,type:"localstorage",averageResponseTime:l,microSeconds:w}},function(e,t,n){"use strict";function r(e){var t={messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return t.bc.onmessage=function(e){t.messagesCallback&&t.messagesCallback(e.data)},t}function o(e){e.bc.close(),e.subFns=[]}function i(e,t){e.bc.postMessage(t,!1)}function a(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t}function s(){if(d.a&&"undefined"==typeof window)return!1;if("function"==typeof BroadcastChannel){if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}return!1}function u(){return 100}var c=n(1),d=n.n(c),f=n(0),l=f.b;t.a={create:r,close:o,onMessage:a,postMessage:i,canBeUsed:s,type:"native",averageResponseTime:u,microSeconds:l}},function(e,t){}])}); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.reduxStateSync=t():e.reduxStateSync=t()}(this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.i=function(e){return e},t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=5)}([function(e,t,n){"use strict";function r(e){return!(!e||"function"!=typeof e.then)}function o(e){return e||(e=0),new Promise(function(t){return setTimeout(t,e)})}function i(e,t){return Math.floor(Math.random()*(t-e+1)+e)}function a(e){e||(e=5);for(var t="",n="abcdefghijklmnopqrstuvwxzy0123456789",r=0;r<e;r++)t+=n.charAt(Math.floor(Math.random()*n.length));return t}function s(){var e=(new Date).getTime();return e===u?(c++,1e3*e+c):(u=e,c=0,1e3*e)}t.a=r,t.c=o,t.e=i,t.d=a,t.b=s;var u=0,c=0},function(e,t){e.exports=!1},function(e,t,n){"use strict";function r(e){return e||(e={}),e=JSON.parse(JSON.stringify(e)),void 0===e.webWorkerSupport&&(e.webWorkerSupport=!0),e.idb||(e.idb={}),e.idb.ttl||(e.idb.ttl=45e3),e.idb.fallbackInterval||(e.idb.fallbackInterval=150),e.localstorage||(e.localstorage={}),e.localstorage.removeTimeout||(e.localstorage.removeTimeout=6e4),e.node||(e.node={}),e.node.ttl||(e.node.ttl=12e4),void 0===e.node.useFastPath&&(e.node.useFastPath=!0),e}t.a=r},function(e,t,n){"use strict";function r(e){for(var t=o()-e.ttl,n=e.set[Symbol.iterator]();;){var r=n.next().value;if(!r)return;if(!(e.timeMap.get(r)<t))return;e.timeMap.delete(r),e.set.delete(r)}}function o(){return(new Date).getTime()}var i=function(e){this.ttl=e,this.set=new Set,this.timeMap=new Map,this.has=this.set.has.bind(this.set)};i.prototype={add:function(e){this.timeMap.set(e,o()),this.set.add(e),r(this)},clear:function(){this.set.clear(),this.timeMap.clear()}},t.a=i},function(e,t,n){"use strict";function r(e,t,n){var r=e.method.microSeconds(),o={time:r,type:t,data:n};return(e._prepP?e._prepP:Promise.resolve()).then(function(){return e.method.postMessage(e._state,o)})}function o(e){var t=e.method.create(e.name,e.options);n.i(d.a)(t)?(e._prepP=t,t.then(function(t){e._state=t})):e._state=t}function i(e){return e._addEL.message.length>0||e._addEL.internal.length>0}function a(e,t,n){e._addEL[t].push(n),u(e)}function s(e,t,n){e._addEL[t]=e._addEL[t].filter(function(e){return e!==n}),c(e)}function u(e){if(!e._iL&&i(e)){var t=function(t){e._addEL[t.type].forEach(function(e){t.time>=e.time&&e.fn(t.data)})},n=e.method.microSeconds();e._prepP?e._prepP.then(function(){e._iL=!0,e.method.onMessage(e._state,t,n)}):(e._iL=!0,e.method.onMessage(e._state,t,n))}}function c(e){if(e._iL&&!i(e)){e._iL=!1;var t=e.method.microSeconds();e.method.onMessage(e._state,null,t)}}Object.defineProperty(t,"__esModule",{value:!0});var d=n(0),f=n(6),l=n(2),p=function(e,t){this.name=e,this.options=n.i(l.a)(t),this.method=n.i(f.a)(this.options),this._iL=!1,this._onML=null,this._addEL={message:[],internal:[]},this._befC=[],this._prepP=null,o(this)};p._pubkey=!0,p.clearNodeFolder=function(e){e=n.i(l.a)(e);var t=n.i(f.a)(e);return"node"===t.type?t.clearNodeFolder().then(function(){return!0}):Promise.resolve(!1)},p.prototype={postMessage:function(e){if(this.closed)throw new Error("BroadcastChannel.postMessage(): Cannot post message after channel has closed");return r(this,"message",e)},postInternal:function(e){return r(this,"internal",e)},set onmessage(e){var t=this.method.microSeconds(),n={time:t,fn:e};s(this,"message",this._onML),e&&"function"==typeof e?(this._onML=n,a(this,"message",n)):this._onML=null},addEventListener:function(e,t){a(this,e,{time:this.method.microSeconds(),fn:t})},removeEventListener:function(e,t){s(this,e,this._addEL[e].find(function(e){return e.fn===t}))},close:function(){var e=this;if(!this.closed){this.closed=!0;var t=this._prepP?this._prepP:Promise.resolve();return this._onML=null,this._addEL.message=[],t.then(function(){return Promise.all(e._befC.map(function(e){return e()}))}).then(function(){return e.method.close(e._state)})}},get type(){return this.method.type}},t.default=p},function(e,t,n){"use strict";function r(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}function o(){return""+r()+r()+"-"+r()+"-"+r()+"-"+r()+"-"+r()+r()+r()}function i(e){var t=e;return t.$uuid=o(),t.$wuid=w,t}function a(e){var t=e.predicate,n=e.blacklist,r=e.whitelist,o=function(){return!0};return t&&"function"==typeof t?o=t:Array.isArray(n)?o=function(e){return n.indexOf(e)<0}:Array.isArray(r)&&(o=function(e){return r.indexOf(e)>=0}),o}function s(e){var t=e.channel,n=e.dispatch,r=e.allowed,o=!1,i={};t.onmessage=function(e){if(e.$wuid!==w&&e.type!==p&&e.$uuid&&e.$uuid!==d)if(e.type!==f||i[e.$wuid]){if(e.type===l&&!i[e.$wuid])return void(o||(o=!0,n(b(e.payload))));r(e.type)&&(d=e.$uuid,n(e))}else i[e.$wuid]=!0,n(v())}}Object.defineProperty(t,"__esModule",{value:!0}),t.initStateWithPrevTab=t.withReduxStateSync=t.createReduxStateSync=t.createStateSyncMiddleware=void 0,t.generateUuidForAction=i,t.isActionAllowed=a,t.createMessageListener=s;var u=n(4),c=function(e){return e&&e.__esModule?e:{default:e}}(u),d=0,f="&_GET_INIT_STATE",l="&_SEND_INIT_STATE",p="&_RECEIVE_INIT_STATE",m={channel:"redux_state_sync",predicate:null,blacklist:[],whitelist:[],broadcastChannelOption:null,prepareState:function(e){return e}},h=function(){return{type:f}},v=function(){return{type:l}},b=function(e){return{type:p,payload:e}},w=o(),g=!1,y=(t.createStateSyncMiddleware=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:m,t=a(e),n=new c.default(e.channel,e.broadcastChannelOption),r=e.prepareState||m.prepareState;return function(e){var o=e.getState,a=e.dispatch;return function(e){return function(u){if(g||(g=!0,s({channel:n,dispatch:a,allowed:t})),u&&!u.$uuid){var c=i(u);d=c.$uuid;try{if(u.type===l)return o()&&(c.payload=r(o()),n.postMessage(c)),e(u);(t(c.type)||u.type===f)&&n.postMessage(c)}catch(e){console.error("Your browser doesn't support cross tab communication")}}return e(u)}}}},t.createReduxStateSync=function(e){var t=e.prepareState;return function(e){return function(n,r){var o=n;return r.type===p&&(o=t(r.payload)),e(o,r)}}});t.withReduxStateSync=y({prepareState:function(e){return e}}),t.initStateWithPrevTab=function(e){(0,e.dispatch)(h())}},function(e,t,n){"use strict";function r(e){if(e.type){var t=c.find(function(t){return t.type===e.type});if(t)return t;throw new Error("method-type "+e.type+" not found")}var n=c;e.webWorkerSupport||i.a||(n=c.filter(function(e){return"idb"!==e.type}));var r=n.find(function(e){return e.canBeUsed()});if(r)return r;throw new Error("No useable methode found:"+JSON.stringify(c.map(function(e){return e.type})))}t.a=r;var o=n(1),i=n.n(o),a=n(9),s=n(7),u=n(8),c=[a.a,s.a,u.a];if(i.a){var d=n(10);"function"==typeof d.canBeUsed&&c.push(d)}},function(e,t,n){"use strict";function r(){return"undefined"!=typeof indexedDB?indexedDB:void 0!==window.mozIndexedDB?window.mozIndexedDB:void 0!==window.webkitIndexedDB?window.webkitIndexedDB:void 0!==window.msIndexedDB&&window.msIndexedDB}function o(e){var t=r(),n=P+e,o=t.open(n,1);return o.onupgradeneeded=function(e){e.target.result.createObjectStore(C,{keyPath:"id",autoIncrement:!0})},new Promise(function(e,t){o.onerror=function(e){return t(e)},o.onsuccess=function(){e(o.result)}})}function i(e,t,n){var r=(new Date).getTime(),o={uuid:t,time:r,data:n},i=e.transaction([C],"readwrite");return new Promise(function(e,t){i.oncomplete=function(){return e()},i.onerror=function(e){return t(e)},i.objectStore(C).add(o)})}function a(e,t){var n=e.transaction(C).objectStore(C),r=[],o=IDBKeyRange.bound(t+1,1/0);return new Promise(function(e){n.openCursor(o).onsuccess=function(t){var n=t.target.result;n?(r.push(n.value),n.continue()):e(r)}})}function s(e,t){var n=e.transaction([C],"readwrite").objectStore(C).delete(t);return new Promise(function(e){n.onsuccess=function(){return e()}})}function u(e,t){var n=(new Date).getTime()-t,r=e.transaction(C).objectStore(C),o=[];return new Promise(function(e){r.openCursor().onsuccess=function(t){var r=t.target.result;if(r){var i=r.value;if(!(i.time<n))return void e(o);o.push(i),r.continue()}else e(o)}})}function c(e,t){return u(e,t).then(function(t){return Promise.all(t.map(function(t){return s(e,t.id)}))})}function d(e,t){return t=n.i(k.a)(t),o(e).then(function(r){var o={closed:!1,lastCursorId:0,channelName:e,options:t,uuid:n.i(_.d)(10),eMIs:new S.a(2*t.idb.ttl),writeBlockPromise:Promise.resolve(),messagesCallback:null,readQueuePromises:[],db:r};return f(o),o})}function f(e){if(!e.closed)return p(e).then(function(){return n.i(_.c)(e.options.idb.fallbackInterval)}).then(function(){return f(e)})}function l(e,t){return e.uuid!==t.uuid&&(!t.eMIs.has(e.id)&&!(e.data.time<t.messagesCallbackTime))}function p(e){return e.closed?Promise.resolve():e.messagesCallback?a(e.db,e.lastCursorId).then(function(t){return t.map(function(t){return t.id>e.lastCursorId&&(e.lastCursorId=t.id),t}).filter(function(t){return l(t,e)}).sort(function(e,t){return e.time-t.time}).forEach(function(t){e.messagesCallback&&(e.eMIs.add(t.id),e.messagesCallback(t.data))}),Promise.resolve()}):Promise.resolve()}function m(e){e.closed=!0,e.db.close()}function h(e,t){return e.writeBlockPromise=e.writeBlockPromise.then(function(){return i(e.db,e.uuid,t)}).then(function(){0===n.i(_.e)(0,10)&&c(e.db,e.options.idb.ttl)}),e.writeBlockPromise}function v(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t,p(e)}function b(){return!y.a&&!!r()}function w(e){return 2*e.idb.fallbackInterval}var g=n(1),y=n.n(g),_=n(0),S=n(3),k=n(2),M=_.b,P="pubkey.broadcast-channel-0-",C="messages";t.a={create:d,close:m,onMessage:v,postMessage:h,canBeUsed:b,type:"idb",averageResponseTime:w,microSeconds:M}},function(e,t,n){"use strict";function r(){var e;if("undefined"==typeof window)return null;try{e=window.localStorage,e=window["ie8-eventlistener/storage"]||window.localStorage}catch(e){}return e}function o(e){return g+e}function i(e,t){return new Promise(function(r){n.i(b.c)().then(function(){var i=o(e.channelName),a={token:n.i(b.d)(10),time:(new Date).getTime(),data:t,uuid:e.uuid},s=JSON.stringify(a);localStorage.setItem(i,s);var u=document.createEvent("Event");u.initEvent("storage",!0,!0),u.key=i,u.newValue=s,window.dispatchEvent(u),r()})})}function a(e,t){var n=o(e),r=function(e){e.key===n&&t(JSON.parse(e.newValue))};return window.addEventListener("storage",r),r}function s(e){window.removeEventListener("storage",e)}function u(e,t){if(t=n.i(v.a)(t),!f())throw new Error("BroadcastChannel: localstorage cannot be used");var r=n.i(b.d)(10),o=new h.a(t.localstorage.removeTimeout),i={channelName:e,uuid:r,eMIs:o};return i.listener=a(e,function(e){i.messagesCallback&&e.uuid!==r&&e.token&&!o.has(e.token)&&(e.data.time&&e.data.time<i.messagesCallbackTime||(o.add(e.token),i.messagesCallback(e.data)))}),i}function c(e){s(e.listener)}function d(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t}function f(){return!m.a&&!!r()}function l(){return 120}var p=n(1),m=n.n(p),h=n(3),v=n(2),b=n(0),w=b.b,g="pubkey.broadcastChannel-";t.a={create:u,close:c,onMessage:d,postMessage:i,canBeUsed:f,type:"localstorage",averageResponseTime:l,microSeconds:w}},function(e,t,n){"use strict";function r(e){var t={messagesCallback:null,bc:new BroadcastChannel(e),subFns:[]};return t.bc.onmessage=function(e){t.messagesCallback&&t.messagesCallback(e.data)},t}function o(e){e.bc.close(),e.subFns=[]}function i(e,t){e.bc.postMessage(t,!1)}function a(e,t,n){e.messagesCallbackTime=n,e.messagesCallback=t}function s(){if(d.a&&"undefined"==typeof window)return!1;if("function"==typeof BroadcastChannel){if(BroadcastChannel._pubkey)throw new Error("BroadcastChannel: Do not overwrite window.BroadcastChannel with this module, this is not a polyfill");return!0}return!1}function u(){return 100}var c=n(1),d=n.n(c),f=n(0),l=f.b;t.a={create:r,close:o,onMessage:a,postMessage:i,canBeUsed:s,type:"native",averageResponseTime:u,microSeconds:l}},function(e,t){}])}); | ||
//# sourceMappingURL=syncState.umd.min.js.map |
@@ -1,19 +0,23 @@ | ||
import React from 'react' | ||
import { render } from 'react-dom' | ||
import { Provider } from 'react-redux' | ||
import { createStore, applyMiddleware } from 'redux' | ||
import rootReducer from './reducers' | ||
import App from './components/App' | ||
import registerServiceWorker from './registerServiceWorker' | ||
import { createStateSyncMiddleware, initStateWithPrevTab } from './lib/syncStorage' | ||
import React from "react"; | ||
import { render } from "react-dom"; | ||
import { Provider } from "react-redux"; | ||
import { createStore, applyMiddleware } from "redux"; | ||
import rootReducer from "./reducers"; | ||
import App from "./components/App"; | ||
import registerServiceWorker from "./registerServiceWorker"; | ||
import { | ||
createStateSyncMiddleware, | ||
initStateWithPrevTab, | ||
} from "./lib/syncState"; | ||
const middlewares = [ | ||
// TOGGLE_TODO will not be triggered | ||
createStateSyncMiddleware({ initiateWithState: true, predicate: actionType => actionType !== 'TOGGLE_TODO' }), | ||
createStateSyncMiddleware({ | ||
initiateWithState: true, | ||
predicate: actionType => actionType !== "TOGGLE_TODO", | ||
}), | ||
]; | ||
const store = createStore(rootReducer, {}, applyMiddleware(...middlewares)); | ||
initStateWithPrevTab(store); | ||
render( | ||
@@ -23,5 +27,5 @@ <Provider store={store}> | ||
</Provider>, | ||
document.getElementById('root') | ||
) | ||
document.getElementById("root"), | ||
); | ||
registerServiceWorker(); | ||
registerServiceWorker(); |
@@ -1,13 +0,12 @@ | ||
import { combineReducers } from 'redux' | ||
import todo from './todo' | ||
import todos from './todos' | ||
import visibilityFilter from './visibilityFilter' | ||
import { withReduxStateSync } from '../lib/syncStorage' | ||
import { combineReducers } from "redux"; | ||
import todo from "./todo"; | ||
import todos from "./todos"; | ||
import visibilityFilter from "./visibilityFilter"; | ||
import { withReduxStateSync } from "../lib/syncState"; | ||
const appReducer = combineReducers({ | ||
todo, | ||
todos, | ||
visibilityFilter | ||
}) | ||
visibilityFilter, | ||
}); | ||
export default withReduxStateSync(appReducer) | ||
export default withReduxStateSync(appReducer); |
{ | ||
"name": "redux-state-sync", | ||
"version": "2.0.3", | ||
"version": "2.0.4", | ||
"description": "A middleware for redux to sync state in different tabs", | ||
@@ -44,3 +44,3 @@ "main": "dist/syncState.js", | ||
"cz-conventional-changelog": "^1.2.0", | ||
"eslint": "^3.8.1", | ||
"eslint": "^4.18.2", | ||
"eslint-config-airbnb": "^12.0.0", | ||
@@ -47,0 +47,0 @@ "eslint-plugin-import": "^2.0.1", |
@@ -180,1 +180,17 @@ <p align="center"> | ||
``` | ||
#### prepareState | ||
Prepare state for sending to channel. Will be helpful when using Immutable.js | ||
type: `Function` | ||
default: state => state | ||
```javascript | ||
const config = { | ||
// Map immutable object to js | ||
prepareState: state => state.toJS() | ||
} | ||
const middlewares = [ | ||
createStateSyncMiddleware(config), | ||
]; | ||
``` |
@@ -15,2 +15,3 @@ /* eslint-env browser */ | ||
broadcastChannelOption: null, | ||
prepareState: state => state | ||
}; | ||
@@ -91,2 +92,3 @@ | ||
const channel = new BroadcastChannel(config.channel, config.broadcastChannelOption); | ||
const prepareState = config.prepareState || defaultConfig.prepareState; | ||
@@ -106,3 +108,3 @@ return ({ getState, dispatch }) => next => (action) => { | ||
if (getState()) { | ||
stampedAction.payload = getState(); | ||
stampedAction.payload = prepareState(getState()); | ||
channel.postMessage(stampedAction); | ||
@@ -123,8 +125,7 @@ } | ||
// init state with other tab's state | ||
export const withReduxStateSync = appReducer => | ||
export const createReduxStateSync = ({ prepareState }) => appReducer => | ||
((state, action) => { | ||
let initState = state; | ||
if (action.type === RECEIVE_INIT_STATE) { | ||
initState = action.payload; | ||
initState = prepareState(action.payload); | ||
} | ||
@@ -134,4 +135,9 @@ return appReducer(initState, action); | ||
// init state with other tab's state | ||
export const withReduxStateSync = createReduxStateSync({ | ||
prepareState: state => state | ||
}) | ||
export const initStateWithPrevTab = ({ dispatch }) => { | ||
dispatch(getIniteState()); | ||
}; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
864816
2130
196
1