2017-12-14 17:02:32 +00:00
|
|
|
import _ from 'lodash';
|
|
|
|
|
2020-06-03 14:56:08 +00:00
|
|
|
import MiddlewareRegistry from './MiddlewareRegistry';
|
2018-02-02 19:35:49 +00:00
|
|
|
import PersistenceRegistry from './PersistenceRegistry';
|
2020-06-03 14:56:08 +00:00
|
|
|
import { toState } from './functions';
|
2017-12-14 17:02:32 +00:00
|
|
|
|
|
|
|
/**
|
2018-02-02 19:35:49 +00:00
|
|
|
* The delay in milliseconds that passes between the last state change and the
|
|
|
|
* persisting of that state in the storage.
|
2017-12-14 17:02:32 +00:00
|
|
|
*/
|
2018-01-29 22:20:38 +00:00
|
|
|
const PERSIST_STATE_DELAY = 2000;
|
2017-12-14 17:02:32 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* A throttled function to avoid repetitive state persisting.
|
|
|
|
*/
|
2018-01-29 22:20:38 +00:00
|
|
|
const throttledPersistState
|
|
|
|
= _.throttle(
|
2018-02-02 19:35:49 +00:00
|
|
|
state => PersistenceRegistry.persistState(state),
|
2018-01-29 22:20:38 +00:00
|
|
|
PERSIST_STATE_DELAY);
|
2017-12-14 17:02:32 +00:00
|
|
|
|
2018-08-01 20:37:15 +00:00
|
|
|
// Web only code.
|
2021-03-16 15:59:33 +00:00
|
|
|
// We need the <tt>if</tt> because it appears that on mobile the polyfill is not
|
2018-08-01 20:37:15 +00:00
|
|
|
// executed yet.
|
|
|
|
if (typeof window.addEventListener === 'function') {
|
|
|
|
window.addEventListener('unload', () => {
|
|
|
|
throttledPersistState.flush();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-12-14 17:02:32 +00:00
|
|
|
/**
|
|
|
|
* A master MiddleWare to selectively persist state. Please use the
|
2018-02-02 19:35:49 +00:00
|
|
|
* {@link persisterconfig.json} to set which subtrees of the redux state should
|
2018-01-29 22:20:38 +00:00
|
|
|
* be persisted.
|
2017-12-14 17:02:32 +00:00
|
|
|
*
|
|
|
|
* @param {Store} store - The redux store.
|
|
|
|
* @returns {Function}
|
|
|
|
*/
|
|
|
|
MiddlewareRegistry.register(store => next => action => {
|
2018-02-02 19:35:49 +00:00
|
|
|
const oldState = toState(store);
|
2017-12-14 17:02:32 +00:00
|
|
|
const result = next(action);
|
2018-02-02 19:35:49 +00:00
|
|
|
const newState = toState(store);
|
2017-12-14 17:02:32 +00:00
|
|
|
|
2018-02-02 19:35:49 +00:00
|
|
|
oldState === newState || throttledPersistState(newState);
|
2017-12-14 17:02:32 +00:00
|
|
|
|
|
|
|
return result;
|
|
|
|
});
|