|
| 1 | +/** |
| 2 | + * Checks if localStorage is supported. |
| 3 | + * @constant |
| 4 | + * @type {Boolean} |
| 5 | + */ |
| 6 | +const isSupported = !!(window && window.localStorage); |
| 7 | + |
| 8 | +/** |
| 9 | + * List of all reducer names that are synced. |
| 10 | + * @type {string[]} |
| 11 | + */ |
| 12 | +const syncedReducers = []; |
| 13 | + |
| 14 | + |
| 15 | +/** |
| 16 | + * Get the type of the action. |
| 17 | + * @param {string} name |
| 18 | + */ |
| 19 | +function getActionType(name) { |
| 20 | + return `@@sync-reducer/sync/${name}`; |
| 21 | +} |
| 22 | + |
| 23 | +/** |
| 24 | + * Get the key used in localStorage. |
| 25 | + */ |
| 26 | +function getKeyName(name) { |
| 27 | + return `@@sync-reducer/${name}`; |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * Sync data between tabs. |
| 32 | + * @param {string} name |
| 33 | + * @param {object} data |
| 34 | + */ |
| 35 | +function sync(name, data) { |
| 36 | + if(isSupported) { |
| 37 | + window.localStorage.setItem(getKeyName(name), JSON.stringify(data)); |
| 38 | + } |
| 39 | + |
| 40 | + return data; |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * High level reducer to wrap reducers to sync the state between tabs. |
| 45 | + * @param {function} reducer |
| 46 | + * @param {object} config |
| 47 | + */ |
| 48 | +export function syncedReducer(reducer, config = {}) { |
| 49 | + const name = config.name || reducer.toString(); |
| 50 | + const actionType = getActionType(name); |
| 51 | + |
| 52 | + syncedReducers.push(name); |
| 53 | + |
| 54 | + return (state, action = {}, ...slices) => { |
| 55 | + switch(action.type) { |
| 56 | + case actionType: |
| 57 | + return config.skipReducer ? action.payload : reducer(action.payload, action, ...slices); |
| 58 | + default: |
| 59 | + return sync(name, reducer(state, action, ...slices)); |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Registers storage event listener and dispatches actions when the state gets changed in different tabs. |
| 66 | + */ |
| 67 | +export const syncMiddleware = store => { |
| 68 | + isSupported && window.addEventListener('storage', e => { |
| 69 | + syncedReducers.some(name => { |
| 70 | + if(e.key === getKeyName(name)) { |
| 71 | + store.dispatch({ |
| 72 | + type: getActionType(name), |
| 73 | + payload: JSON.parse(e.newValue) |
| 74 | + }); |
| 75 | + |
| 76 | + return true; |
| 77 | + } |
| 78 | + |
| 79 | + return false; |
| 80 | + }) |
| 81 | + }); |
| 82 | + |
| 83 | + return next => action => next(action); |
| 84 | +} |
0 commit comments