-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
296 lines (261 loc) · 7.73 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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/**
* External dependencies
*/
import { merge, isPlainObject, get, has } 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 reducer key to be persisted when changed.
*
* @param {Function} getState Function which returns current state.
* @param {string} reducerKey Reducer key.
* @param {?Array<string>} keys Optional subset of keys to save.
*
* @return {Function} Enhanced dispatch function.
*/
function createPersistOnChange( getState, reducerKey, 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( reducerKey, state );
lastState = state;
}
};
}
return {
registerStore( reducerKey, options ) {
if ( ! options.persist ) {
return registry.registerStore( reducerKey, options );
}
// Load from persistence to use as initial state.
const persistedState = persistence.get()[ reducerKey ];
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( reducerKey, options );
store.subscribe(
createPersistOnChange(
store.getState,
reducerKey,
options.persist
)
);
return store;
},
};
}
/**
* Deprecated: Remove this function and the code in WordPress Core that calls
* it once WordPress 5.4 is released.
*/
persistencePlugin.__unstableMigrate = ( pluginOptions ) => {
const persistence = createPersistenceInterface( pluginOptions );
const state = persistence.get();
// Migrate 'insertUsage' from 'core/editor' to 'core/block-editor'
const insertUsage = get( state, [
'core/editor',
'preferences',
'insertUsage',
] );
if ( insertUsage ) {
persistence.set( 'core/block-editor', {
preferences: {
insertUsage,
},
} );
}
let editPostState = state[ 'core/edit-post' ];
// Default `fullscreenMode` to `false` if any persisted state had existed
// and the user hadn't made an explicit choice about fullscreen mode. This
// is needed since `fullscreenMode` previously did not have a default value
// and was implicitly false by its absence. It is now `true` by default, but
// this change is not intended to affect upgrades from earlier versions.
const hadPersistedState = Object.keys( state ).length > 0;
const hadFullscreenModePreference = has( state, [
'core/edit-post',
'preferences',
'features',
'fullscreenMode',
] );
if ( hadPersistedState && ! hadFullscreenModePreference ) {
editPostState = merge( {}, editPostState, {
preferences: { features: { fullscreenMode: false } },
} );
}
// Migrate 'areTipsEnabled' from 'core/nux' to 'showWelcomeGuide' in 'core/edit-post'
const areTipsEnabled = get( state, [
'core/nux',
'preferences',
'areTipsEnabled',
] );
const hasWelcomeGuide = has( state, [
'core/edit-post',
'preferences',
'features',
'welcomeGuide',
] );
if ( areTipsEnabled !== undefined && ! hasWelcomeGuide ) {
editPostState = merge( {}, editPostState, {
preferences: {
features: {
welcomeGuide: areTipsEnabled,
},
},
} );
}
if ( editPostState !== state[ 'core/edit-post' ] ) {
persistence.set( 'core/edit-post', editPostState );
}
};
export default persistencePlugin;