-
Notifications
You must be signed in to change notification settings - Fork 4k
/
index.js
226 lines (198 loc) · 5.86 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/**
* External dependencies
*/
import isPlainObject from 'is-plain-obj';
import { merge } from 'lodash';
/**
* Internal dependencies
*/
import defaultStorage from './storage/default';
import { combineReducers } from '../../';
/** @typedef {import('../../registry').WPDataRegistry} WPDataRegistry */
/** @typedef {import('../../registry').WPDataPlugin} WPDataPlugin */
/**
* @typedef {Object} WPDataPersistencePluginOptions Persistence plugin options.
*
* @property {Storage} storage Persistent storage implementation. This must
* at least implement `getItem` and `setItem` of
* the Web Storage API.
* @property {string} storageKey Key on which to set in persistent storage.
*
*/
/**
* Default plugin storage.
*
* @type {Storage}
*/
const DEFAULT_STORAGE = defaultStorage;
/**
* Default plugin storage key.
*
* @type {string}
*/
const DEFAULT_STORAGE_KEY = 'WP_DATA';
/**
* Higher-order reducer which invokes the original reducer only if state is
* inequal from that of the action's `nextState` property, otherwise returning
* the original state reference.
*
* @param {Function} reducer Original reducer.
*
* @return {Function} Enhanced reducer.
*/
export const withLazySameState = ( reducer ) => ( state, action ) => {
if ( action.nextState === state ) {
return state;
}
return reducer( state, action );
};
/**
* Creates a persistence interface, exposing getter and setter methods (`get`
* and `set` respectively).
*
* @param {WPDataPersistencePluginOptions} options Plugin options.
*
* @return {Object} Persistence interface.
*/
export function createPersistenceInterface( options ) {
const { storage = DEFAULT_STORAGE, storageKey = DEFAULT_STORAGE_KEY } =
options;
let data;
/**
* Returns the persisted data as an object, defaulting to an empty object.
*
* @return {Object} Persisted data.
*/
function getData() {
if ( data === undefined ) {
// If unset, getItem is expected to return null. Fall back to
// empty object.
const persisted = storage.getItem( storageKey );
if ( persisted === null ) {
data = {};
} else {
try {
data = JSON.parse( persisted );
} catch ( error ) {
// Similarly, should any error be thrown during parse of
// the string (malformed JSON), fall back to empty object.
data = {};
}
}
}
return data;
}
/**
* Merges an updated reducer state into the persisted data.
*
* @param {string} key Key to update.
* @param {*} value Updated value.
*/
function setData( key, value ) {
data = { ...data, [ key ]: value };
storage.setItem( storageKey, JSON.stringify( data ) );
}
return {
get: getData,
set: setData,
};
}
/**
* Data plugin to persist store state into a single storage key.
*
* @param {WPDataRegistry} registry Data registry.
* @param {?WPDataPersistencePluginOptions} pluginOptions Plugin options.
*
* @return {WPDataPlugin} Data plugin.
*/
function persistencePlugin( registry, pluginOptions ) {
const persistence = createPersistenceInterface( pluginOptions );
/**
* Creates an enhanced store dispatch function, triggering the state of the
* given store name to be persisted when changed.
*
* @param {Function} getState Function which returns current state.
* @param {string} storeName Store name.
* @param {?Array<string>} keys Optional subset of keys to save.
*
* @return {Function} Enhanced dispatch function.
*/
function createPersistOnChange( getState, storeName, keys ) {
let getPersistedState;
if ( Array.isArray( keys ) ) {
// Given keys, the persisted state should by produced as an object
// of the subset of keys. This implementation uses combineReducers
// to leverage its behavior of returning the same object when none
// of the property values changes. This allows a strict reference
// equality to bypass a persistence set on an unchanging state.
const reducers = keys.reduce(
( accumulator, key ) =>
Object.assign( accumulator, {
[ key ]: ( state, action ) => action.nextState[ key ],
} ),
{}
);
getPersistedState = withLazySameState(
combineReducers( reducers )
);
} else {
getPersistedState = ( state, action ) => action.nextState;
}
let lastState = getPersistedState( undefined, {
nextState: getState(),
} );
return () => {
const state = getPersistedState( lastState, {
nextState: getState(),
} );
if ( state !== lastState ) {
persistence.set( storeName, state );
lastState = state;
}
};
}
return {
registerStore( storeName, options ) {
if ( ! options.persist ) {
return registry.registerStore( storeName, options );
}
// Load from persistence to use as initial state.
const persistedState = persistence.get()[ storeName ];
if ( persistedState !== undefined ) {
let initialState = options.reducer( options.initialState, {
type: '@@WP/PERSISTENCE_RESTORE',
} );
if (
isPlainObject( initialState ) &&
isPlainObject( persistedState )
) {
// If state is an object, ensure that:
// - Other keys are left intact when persisting only a
// subset of keys.
// - New keys in what would otherwise be used as initial
// state are deeply merged as base for persisted value.
initialState = merge( {}, initialState, persistedState );
} else {
// If there is a mismatch in object-likeness of default
// initial or persisted state, defer to persisted value.
initialState = persistedState;
}
options = {
...options,
initialState,
};
}
const store = registry.registerStore( storeName, options );
store.subscribe(
createPersistOnChange(
store.getState,
storeName,
options.persist
)
);
return store;
},
};
}
persistencePlugin.__unstableMigrate = () => {};
export default persistencePlugin;