-
Notifications
You must be signed in to change notification settings - Fork 4.2k
/
registry.js
397 lines (356 loc) · 11.5 KB
/
registry.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
/**
* WordPress dependencies
*/
import deprecated from '@wordpress/deprecated';
/**
* Internal dependencies
*/
import createReduxStore from './redux-store';
import coreDataStore from './store';
import { createEmitter } from './utils/emitter';
import { lock, unlock } from './lock-unlock';
/** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
/**
* @typedef {Object} WPDataRegistry An isolated orchestrator of store registrations.
*
* @property {Function} registerGenericStore Given a namespace key and settings
* object, registers a new generic
* store.
* @property {Function} registerStore Given a namespace key and settings
* object, registers a new namespace
* store.
* @property {Function} subscribe Given a function callback, invokes
* the callback on any change to state
* within any registered store.
* @property {Function} select Given a namespace key, returns an
* object of the store's registered
* selectors.
* @property {Function} dispatch Given a namespace key, returns an
* object of the store's registered
* action dispatchers.
*/
/**
* @typedef {Object} WPDataPlugin An object of registry function overrides.
*
* @property {Function} registerStore registers store.
*/
function getStoreName( storeNameOrDescriptor ) {
return typeof storeNameOrDescriptor === 'string'
? storeNameOrDescriptor
: storeNameOrDescriptor.name;
}
/**
* Creates a new store registry, given an optional object of initial store
* configurations.
*
* @param {Object} storeConfigs Initial store configurations.
* @param {Object?} parent Parent registry.
*
* @return {WPDataRegistry} Data registry.
*/
export function createRegistry( storeConfigs = {}, parent = null ) {
const stores = {};
const emitter = createEmitter();
let listeningStores = null;
/**
* Global listener called for each store's update.
*/
function globalListener() {
emitter.emit();
}
/**
* Subscribe to changes to any data, either in all stores in registry, or
* in one specific store.
*
* @param {Function} listener Listener function.
* @param {string|StoreDescriptor?} storeNameOrDescriptor Optional store name.
*
* @return {Function} Unsubscribe function.
*/
const subscribe = ( listener, storeNameOrDescriptor ) => {
// subscribe to all stores
if ( ! storeNameOrDescriptor ) {
return emitter.subscribe( listener );
}
// subscribe to one store
const storeName = getStoreName( storeNameOrDescriptor );
const store = stores[ storeName ];
if ( store ) {
return store.subscribe( listener );
}
// Trying to access a store that hasn't been registered,
// this is a pattern rarely used but seen in some places.
// We fallback to global `subscribe` here for backward-compatibility for now.
// See https://github.com/WordPress/gutenberg/pull/27466 for more info.
if ( ! parent ) {
return emitter.subscribe( listener );
}
return parent.subscribe( listener, storeNameOrDescriptor );
};
/**
* Calls a selector given the current state and extra arguments.
*
* @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
* or the store descriptor.
*
* @return {*} The selector's returned value.
*/
function select( storeNameOrDescriptor ) {
const storeName = getStoreName( storeNameOrDescriptor );
listeningStores?.add( storeName );
const store = stores[ storeName ];
if ( store ) {
return store.getSelectors();
}
return parent?.select( storeName );
}
function __unstableMarkListeningStores( callback, ref ) {
listeningStores = new Set();
try {
return callback.call( this );
} finally {
ref.current = Array.from( listeningStores );
listeningStores = null;
}
}
/**
* Given a store descriptor, returns an object containing the store's selectors pre-bound to
* state so that you only need to supply additional arguments, and modified so that they return
* promises that resolve to their eventual values, after any resolvers have ran.
*
* @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
* convention of passing the store name is
* also supported.
*
* @return {Object} Each key of the object matches the name of a selector.
*/
function resolveSelect( storeNameOrDescriptor ) {
const storeName = getStoreName( storeNameOrDescriptor );
listeningStores?.add( storeName );
const store = stores[ storeName ];
if ( store ) {
return store.getResolveSelectors();
}
return parent && parent.resolveSelect( storeName );
}
/**
* Given a store descriptor, returns an object containing the store's selectors pre-bound to
* state so that you only need to supply additional arguments, and modified so that they throw
* promises in case the selector is not resolved yet.
*
* @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
* convention of passing the store name is
* also supported.
*
* @return {Object} Object containing the store's suspense-wrapped selectors.
*/
function suspendSelect( storeNameOrDescriptor ) {
const storeName = getStoreName( storeNameOrDescriptor );
listeningStores?.add( storeName );
const store = stores[ storeName ];
if ( store ) {
return store.getSuspendSelectors();
}
return parent && parent.suspendSelect( storeName );
}
/**
* Returns the available actions for a part of the state.
*
* @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
* or the store descriptor.
*
* @return {*} The action's returned value.
*/
function dispatch( storeNameOrDescriptor ) {
const storeName = getStoreName( storeNameOrDescriptor );
const store = stores[ storeName ];
if ( store ) {
return store.getActions();
}
return parent && parent.dispatch( storeName );
}
//
// Deprecated
// TODO: Remove this after `use()` is removed.
function withPlugins( attributes ) {
return Object.fromEntries(
Object.entries( attributes ).map( ( [ key, attribute ] ) => {
if ( typeof attribute !== 'function' ) {
return [ key, attribute ];
}
return [
key,
function () {
return registry[ key ].apply( null, arguments );
},
];
} )
);
}
/**
* Registers a store instance.
*
* @param {string} name Store registry name.
* @param {Function} createStore Function that creates a store object (getSelectors, getActions, subscribe).
*/
function registerStoreInstance( name, createStore ) {
if ( stores[ name ] ) {
// eslint-disable-next-line no-console
console.error( 'Store "' + name + '" is already registered.' );
return stores[ name ];
}
const store = createStore();
if ( typeof store.getSelectors !== 'function' ) {
throw new TypeError( 'store.getSelectors must be a function' );
}
if ( typeof store.getActions !== 'function' ) {
throw new TypeError( 'store.getActions must be a function' );
}
if ( typeof store.subscribe !== 'function' ) {
throw new TypeError( 'store.subscribe must be a function' );
}
// The emitter is used to keep track of active listeners when the registry
// get paused, that way, when resumed we should be able to call all these
// pending listeners.
store.emitter = createEmitter();
const currentSubscribe = store.subscribe;
store.subscribe = ( listener ) => {
const unsubscribeFromEmitter = store.emitter.subscribe( listener );
const unsubscribeFromStore = currentSubscribe( () => {
if ( store.emitter.isPaused ) {
store.emitter.emit();
return;
}
listener();
} );
return () => {
unsubscribeFromStore?.();
unsubscribeFromEmitter?.();
};
};
stores[ name ] = store;
store.subscribe( globalListener );
// Copy private actions and selectors from the parent store.
if ( parent ) {
try {
unlock( store.store ).registerPrivateActions(
unlock( parent ).privateActionsOf( name )
);
unlock( store.store ).registerPrivateSelectors(
unlock( parent ).privateSelectorsOf( name )
);
} catch ( e ) {
// unlock() throws if store.store was not locked.
// The error indicates there's nothing to do here so let's
// ignore it.
}
}
return store;
}
/**
* Registers a new store given a store descriptor.
*
* @param {StoreDescriptor} store Store descriptor.
*/
function register( store ) {
registerStoreInstance( store.name, () =>
store.instantiate( registry )
);
}
function registerGenericStore( name, store ) {
deprecated( 'wp.data.registerGenericStore', {
since: '5.9',
alternative: 'wp.data.register( storeDescriptor )',
} );
registerStoreInstance( name, () => store );
}
/**
* Registers a standard `@wordpress/data` store.
*
* @param {string} storeName Unique namespace identifier.
* @param {Object} options Store description (reducer, actions, selectors, resolvers).
*
* @return {Object} Registered store object.
*/
function registerStore( storeName, options ) {
if ( ! options.reducer ) {
throw new TypeError( 'Must specify store reducer' );
}
const store = registerStoreInstance( storeName, () =>
createReduxStore( storeName, options ).instantiate( registry )
);
return store.store;
}
function batch( callback ) {
// If we're already batching, just call the callback.
if ( emitter.isPaused ) {
callback();
return;
}
emitter.pause();
Object.values( stores ).forEach( ( store ) => store.emitter.pause() );
try {
callback();
} finally {
emitter.resume();
Object.values( stores ).forEach( ( store ) =>
store.emitter.resume()
);
}
}
let registry = {
batch,
stores,
namespaces: stores, // TODO: Deprecate/remove this.
subscribe,
select,
resolveSelect,
suspendSelect,
dispatch,
use,
register,
registerGenericStore,
registerStore,
__unstableMarkListeningStores,
};
//
// TODO:
// This function will be deprecated as soon as it is no longer internally referenced.
function use( plugin, options ) {
if ( ! plugin ) {
return;
}
registry = {
...registry,
...plugin( registry, options ),
};
return registry;
}
registry.register( coreDataStore );
for ( const [ name, config ] of Object.entries( storeConfigs ) ) {
registry.register( createReduxStore( name, config ) );
}
if ( parent ) {
parent.subscribe( globalListener );
}
const registryWithPlugins = withPlugins( registry );
lock( registryWithPlugins, {
privateActionsOf: ( name ) => {
try {
return unlock( stores[ name ].store ).privateActions;
} catch ( e ) {
// unlock() throws an error the store was not locked – this means
// there no private actions are available
return {};
}
},
privateSelectorsOf: ( name ) => {
try {
return unlock( stores[ name ].store ).privateSelectors;
} catch ( e ) {
return {};
}
},
} );
return registryWithPlugins;
}