@wordpress/data 6.6.1 → 6.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,160 @@
1
+ /**
2
+ * External dependencies
3
+ */
4
+ import { render, waitFor } from '@testing-library/react';
5
+
6
+ /**
7
+ * WordPress dependencies
8
+ */
9
+ import {
10
+ createRegistry,
11
+ createReduxStore,
12
+ useSuspenseSelect,
13
+ RegistryProvider,
14
+ } from '@wordpress/data';
15
+ import { Component, Suspense } from '@wordpress/element';
16
+
17
+ jest.useRealTimers();
18
+
19
+ function createRegistryWithStore() {
20
+ const initialState = {
21
+ prefix: 'pre-',
22
+ token: null,
23
+ data: null,
24
+ fails: true,
25
+ };
26
+
27
+ const reducer = ( state = initialState, action ) => {
28
+ switch ( action.type ) {
29
+ case 'RECEIVE_TOKEN':
30
+ return { ...state, token: action.token };
31
+ case 'RECEIVE_DATA':
32
+ return { ...state, data: action.data };
33
+ default:
34
+ return state;
35
+ }
36
+ };
37
+
38
+ const selectors = {
39
+ getPrefix: ( state ) => state.prefix,
40
+ getToken: ( state ) => state.token,
41
+ getData: ( state, token ) => {
42
+ if ( ! token ) {
43
+ throw 'missing token in selector';
44
+ }
45
+ return state.data;
46
+ },
47
+ getThatFails: ( state ) => state.fails,
48
+ };
49
+
50
+ const sleep = ( ms ) => new Promise( ( r ) => setTimeout( () => r(), ms ) );
51
+
52
+ const resolvers = {
53
+ getToken: () => async ( { dispatch } ) => {
54
+ await sleep( 10 );
55
+ dispatch( { type: 'RECEIVE_TOKEN', token: 'token' } );
56
+ },
57
+ getData: ( token ) => async ( { dispatch } ) => {
58
+ await sleep( 10 );
59
+ if ( ! token ) {
60
+ throw 'missing token in resolver';
61
+ }
62
+ dispatch( { type: 'RECEIVE_DATA', data: 'therealdata' } );
63
+ },
64
+ getThatFails: () => async () => {
65
+ await sleep( 10 );
66
+ throw 'resolution failed';
67
+ },
68
+ };
69
+
70
+ const store = createReduxStore( 'test', {
71
+ reducer,
72
+ selectors,
73
+ resolvers,
74
+ } );
75
+
76
+ const registry = createRegistry();
77
+ registry.register( store );
78
+
79
+ return { registry, store };
80
+ }
81
+
82
+ describe( 'useSuspenseSelect', () => {
83
+ it( 'renders after suspending a few times', async () => {
84
+ const { registry, store } = createRegistryWithStore();
85
+ let attempts = 0;
86
+ let renders = 0;
87
+
88
+ const UI = () => {
89
+ attempts++;
90
+ const { result } = useSuspenseSelect( ( select ) => {
91
+ const prefix = select( store ).getPrefix();
92
+ const token = select( store ).getToken();
93
+ const data = select( store ).getData( token );
94
+ return { result: prefix + data };
95
+ }, [] );
96
+ renders++;
97
+ return <div aria-label="loaded">{ result }</div>;
98
+ };
99
+
100
+ const App = () => (
101
+ <RegistryProvider value={ registry }>
102
+ <Suspense fallback="loading">
103
+ <UI />
104
+ </Suspense>
105
+ </RegistryProvider>
106
+ );
107
+
108
+ const rendered = render( <App /> );
109
+ await waitFor( () => rendered.getByLabelText( 'loaded' ) );
110
+
111
+ // Verify there were 3 attempts to render. Suspended twice because of
112
+ // `getToken` and `getData` selectors not being resolved, and then finally
113
+ // rendered after all data got loaded.
114
+ expect( attempts ).toBe( 3 );
115
+ expect( renders ).toBe( 1 );
116
+ } );
117
+
118
+ it( 'shows error when resolution fails', async () => {
119
+ const { registry, store } = createRegistryWithStore();
120
+
121
+ const UI = () => {
122
+ const { token } = useSuspenseSelect( ( select ) => {
123
+ // Call a selector whose resolution fails. The `useSuspenseSelect`
124
+ // is then supposed to throw the resolution error.
125
+ return { token: select( store ).getThatFails() };
126
+ }, [] );
127
+ return <div aria-label="loaded">{ token }</div>;
128
+ };
129
+
130
+ class Error extends Component {
131
+ state = { error: null };
132
+
133
+ static getDerivedStateFromError( error ) {
134
+ return { error };
135
+ }
136
+
137
+ render() {
138
+ if ( this.state.error ) {
139
+ return <div aria-label="error">{ this.state.error }</div>;
140
+ }
141
+ return this.props.children;
142
+ }
143
+ }
144
+
145
+ const App = () => (
146
+ <RegistryProvider value={ registry }>
147
+ <Error>
148
+ <Suspense fallback="loading">
149
+ <UI />
150
+ </Suspense>
151
+ </Error>
152
+ </RegistryProvider>
153
+ );
154
+
155
+ const rendered = render( <App /> );
156
+ const label = await waitFor( () => rendered.getByLabelText( 'error' ) );
157
+ expect( label.textContent ).toBe( 'resolution failed' );
158
+ expect( console ).toHaveErrored();
159
+ } );
160
+ } );
package/src/index.js CHANGED
@@ -19,7 +19,10 @@ export {
19
19
  RegistryConsumer,
20
20
  useRegistry,
21
21
  } from './components/registry-provider';
22
- export { default as useSelect } from './components/use-select';
22
+ export {
23
+ default as useSelect,
24
+ useSuspenseSelect,
25
+ } from './components/use-select';
23
26
  export { useDispatch } from './components/use-dispatch';
24
27
  export { AsyncModeProvider } from './components/async-mode-provider';
25
28
  export { createRegistry } from './registry';
@@ -115,6 +118,18 @@ export const select = defaultRegistry.select;
115
118
  */
116
119
  export const resolveSelect = defaultRegistry.resolveSelect;
117
120
 
121
+ /**
122
+ * Given the name of a registered store, returns an object containing the store's
123
+ * selectors pre-bound to state so that you only need to supply additional arguments,
124
+ * and modified so that they throw promises in case the selector is not resolved yet.
125
+ *
126
+ * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
127
+ * or the store descriptor.
128
+ *
129
+ * @return {Object} Object containing the store's suspense-wrapped selectors.
130
+ */
131
+ export const suspendSelect = defaultRegistry.suspendSelect;
132
+
118
133
  /**
119
134
  * Given the name of a registered store, returns an object of the store's action creators.
120
135
  * Calling an action creator will cause it to be dispatched, updating the state value accordingly.
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * External dependencies
3
3
  */
4
- import { merge, isPlainObject, identity } from 'lodash';
4
+ import { merge, isPlainObject } from 'lodash';
5
5
 
6
6
  /**
7
7
  * Internal dependencies
@@ -222,424 +222,6 @@ function persistencePlugin( registry, pluginOptions ) {
222
222
  };
223
223
  }
224
224
 
225
- /**
226
- * Move the 'features' object in local storage from the sourceStoreName to the
227
- * preferences store.
228
- *
229
- * @param {Object} persistence The persistence interface.
230
- * @param {string} sourceStoreName The name of the store that has persisted
231
- * preferences to migrate to the preferences
232
- * package.
233
- */
234
- export function migrateFeaturePreferencesToPreferencesStore(
235
- persistence,
236
- sourceStoreName
237
- ) {
238
- const preferencesStoreName = 'core/preferences';
239
- const interfaceStoreName = 'core/interface';
240
-
241
- const state = persistence.get();
242
-
243
- // Features most recently (and briefly) lived in the interface package.
244
- // If data exists there, prioritize using that for the migration. If not
245
- // also check the original package as the user may have updated from an
246
- // older block editor version.
247
- const interfaceFeatures =
248
- state[ interfaceStoreName ]?.preferences?.features?.[ sourceStoreName ];
249
- const sourceFeatures = state[ sourceStoreName ]?.preferences?.features;
250
- const featuresToMigrate = interfaceFeatures
251
- ? interfaceFeatures
252
- : sourceFeatures;
253
-
254
- if ( featuresToMigrate ) {
255
- const existingPreferences = state[ preferencesStoreName ]?.preferences;
256
-
257
- // Avoid migrating features again if they've previously been migrated.
258
- if ( ! existingPreferences?.[ sourceStoreName ] ) {
259
- // Set the feature values in the interface store, the features
260
- // object is keyed by 'scope', which matches the store name for
261
- // the source.
262
- persistence.set( preferencesStoreName, {
263
- preferences: {
264
- ...existingPreferences,
265
- [ sourceStoreName ]: featuresToMigrate,
266
- },
267
- } );
268
-
269
- // Remove migrated feature preferences from `interface`.
270
- if ( interfaceFeatures ) {
271
- const otherInterfaceState = state[ interfaceStoreName ];
272
- const otherInterfaceScopes =
273
- state[ interfaceStoreName ]?.preferences?.features;
274
-
275
- persistence.set( interfaceStoreName, {
276
- ...otherInterfaceState,
277
- preferences: {
278
- features: {
279
- ...otherInterfaceScopes,
280
- [ sourceStoreName ]: undefined,
281
- },
282
- },
283
- } );
284
- }
285
-
286
- // Remove migrated feature preferences from the source.
287
- if ( sourceFeatures ) {
288
- const otherSourceState = state[ sourceStoreName ];
289
- const sourcePreferences = state[ sourceStoreName ]?.preferences;
290
-
291
- persistence.set( sourceStoreName, {
292
- ...otherSourceState,
293
- preferences: {
294
- ...sourcePreferences,
295
- features: undefined,
296
- },
297
- } );
298
- }
299
- }
300
- }
301
- }
302
-
303
- /**
304
- * Migrates an individual item inside the `preferences` object for a store.
305
- *
306
- * @param {Object} persistence The persistence interface.
307
- * @param {Object} migrate An options object that contains details of the migration.
308
- * @param {string} migrate.from The name of the store to migrate from.
309
- * @param {string} migrate.scope The scope in the preferences store to migrate to.
310
- * @param {string} key The key in the preferences object to migrate.
311
- * @param {?Function} convert A function that converts preferences from one format to another.
312
- */
313
- export function migrateIndividualPreferenceToPreferencesStore(
314
- persistence,
315
- { from: sourceStoreName, scope },
316
- key,
317
- convert = identity
318
- ) {
319
- const preferencesStoreName = 'core/preferences';
320
- const state = persistence.get();
321
- const sourcePreference = state[ sourceStoreName ]?.preferences?.[ key ];
322
-
323
- // There's nothing to migrate, exit early.
324
- if ( sourcePreference === undefined ) {
325
- return;
326
- }
327
-
328
- const targetPreference =
329
- state[ preferencesStoreName ]?.preferences?.[ scope ]?.[ key ];
330
-
331
- // There's existing data at the target, so don't overwrite it, exit early.
332
- if ( targetPreference ) {
333
- return;
334
- }
335
-
336
- const otherScopes = state[ preferencesStoreName ]?.preferences;
337
- const otherPreferences =
338
- state[ preferencesStoreName ]?.preferences?.[ scope ];
339
-
340
- // Pass an object with the key and value as this allows the convert
341
- // function to convert to a data structure that has different keys.
342
- const convertedPreferences = convert( { [ key ]: sourcePreference } );
343
-
344
- persistence.set( preferencesStoreName, {
345
- preferences: {
346
- ...otherScopes,
347
- [ scope ]: {
348
- ...otherPreferences,
349
- ...convertedPreferences,
350
- },
351
- },
352
- } );
353
-
354
- // Remove migrated feature preferences from the source.
355
- const otherSourceState = state[ sourceStoreName ];
356
- const allSourcePreferences = state[ sourceStoreName ]?.preferences;
357
- persistence.set( sourceStoreName, {
358
- ...otherSourceState,
359
- preferences: {
360
- ...allSourcePreferences,
361
- [ key ]: undefined,
362
- },
363
- } );
364
- }
365
-
366
- /**
367
- * Convert from:
368
- * ```
369
- * {
370
- * panels: {
371
- * tags: {
372
- * enabled: true,
373
- * opened: true,
374
- * },
375
- * permalinks: {
376
- * enabled: false,
377
- * opened: false,
378
- * },
379
- * },
380
- * }
381
- * ```
382
- *
383
- * to:
384
- * {
385
- * inactivePanels: [
386
- * 'permalinks',
387
- * ],
388
- * openPanels: [
389
- * 'tags',
390
- * ],
391
- * }
392
- *
393
- * @param {Object} preferences A preferences object.
394
- *
395
- * @return {Object} The converted data.
396
- */
397
- export function convertEditPostPanels( preferences ) {
398
- const panels = preferences?.panels ?? {};
399
- return Object.keys( panels ).reduce(
400
- ( convertedData, panelName ) => {
401
- const panel = panels[ panelName ];
402
-
403
- if ( panel?.enabled === false ) {
404
- convertedData.inactivePanels.push( panelName );
405
- }
406
-
407
- if ( panel?.opened === true ) {
408
- convertedData.openPanels.push( panelName );
409
- }
410
-
411
- return convertedData;
412
- },
413
- { inactivePanels: [], openPanels: [] }
414
- );
415
- }
416
-
417
- export function migrateThirdPartyFeaturePreferencesToPreferencesStore(
418
- persistence
419
- ) {
420
- const interfaceStoreName = 'core/interface';
421
- const preferencesStoreName = 'core/preferences';
422
-
423
- let state = persistence.get();
424
-
425
- const interfaceScopes = state[ interfaceStoreName ]?.preferences?.features;
426
-
427
- for ( const scope in interfaceScopes ) {
428
- // Don't migrate any core 'scopes'.
429
- if ( scope.startsWith( 'core' ) ) {
430
- continue;
431
- }
432
-
433
- // Skip this scope if there are no features to migrate.
434
- const featuresToMigrate = interfaceScopes[ scope ];
435
- if ( ! featuresToMigrate ) {
436
- continue;
437
- }
438
-
439
- const existingPreferences = state[ preferencesStoreName ]?.preferences;
440
-
441
- // Add the data to the preferences store structure.
442
- persistence.set( preferencesStoreName, {
443
- preferences: {
444
- ...existingPreferences,
445
- [ scope ]: featuresToMigrate,
446
- },
447
- } );
448
-
449
- // Remove the data from the interface store structure.
450
- // Call `persistence.get` again to make sure `state` is up-to-date with
451
- // any changes from the previous iteration of this loop.
452
- state = persistence.get();
453
- const otherInterfaceState = state[ interfaceStoreName ];
454
- const otherInterfaceScopes =
455
- state[ interfaceStoreName ]?.preferences?.features;
456
-
457
- persistence.set( interfaceStoreName, {
458
- ...otherInterfaceState,
459
- preferences: {
460
- features: {
461
- ...otherInterfaceScopes,
462
- [ scope ]: undefined,
463
- },
464
- },
465
- } );
466
- }
467
- }
468
-
469
- /**
470
- * Migrates interface 'enableItems' data to the preferences store.
471
- *
472
- * The interface package stores this data in this format:
473
- * ```js
474
- * {
475
- * enableItems: {
476
- * singleEnableItems: {
477
- * complementaryArea: {
478
- * 'core/edit-post': 'edit-post/document',
479
- * 'core/edit-site': 'edit-site/global-styles',
480
- * }
481
- * },
482
- * multipleEnableItems: {
483
- * pinnedItems: {
484
- * 'core/edit-post': {
485
- * 'plugin-1': true,
486
- * },
487
- * 'core/edit-site': {
488
- * 'plugin-2': true,
489
- * },
490
- * },
491
- * }
492
- * }
493
- * }
494
- * ```
495
- * and it should be migrated it to:
496
- * ```js
497
- * {
498
- * 'core/edit-post': {
499
- * complementaryArea: 'edit-post/document',
500
- * pinnedItems: {
501
- * 'plugin-1': true,
502
- * },
503
- * },
504
- * 'core/edit-site': {
505
- * complementaryArea: 'edit-site/global-styles',
506
- * pinnedItems: {
507
- * 'plugin-2': true,
508
- * },
509
- * },
510
- * }
511
- * ```
512
- *
513
- * @param {Object} persistence The persistence interface.
514
- */
515
- export function migrateInterfaceEnableItemsToPreferencesStore( persistence ) {
516
- const interfaceStoreName = 'core/interface';
517
- const preferencesStoreName = 'core/preferences';
518
- const state = persistence.get();
519
- const sourceEnableItems = state[ interfaceStoreName ]?.enableItems;
520
-
521
- // There's nothing to migrate, exit early.
522
- if ( ! sourceEnableItems ) {
523
- return;
524
- }
525
-
526
- const allPreferences = state[ preferencesStoreName ]?.preferences ?? {};
527
-
528
- // First convert complementaryAreas into the right format.
529
- // Use the existing preferences as the accumulator so that the data is
530
- // merged.
531
- const sourceComplementaryAreas =
532
- sourceEnableItems?.singleEnableItems?.complementaryArea ?? {};
533
-
534
- const convertedComplementaryAreas = Object.keys(
535
- sourceComplementaryAreas
536
- ).reduce( ( accumulator, scope ) => {
537
- const data = sourceComplementaryAreas[ scope ];
538
-
539
- // Don't overwrite any existing data in the preferences store.
540
- if ( accumulator[ scope ]?.complementaryArea ) {
541
- return accumulator;
542
- }
543
-
544
- return {
545
- ...accumulator,
546
- [ scope ]: {
547
- ...accumulator[ scope ],
548
- complementaryArea: data,
549
- },
550
- };
551
- }, allPreferences );
552
-
553
- // Next feed the converted complementary areas back into a reducer that
554
- // converts the pinned items, resulting in the fully migrated data.
555
- const sourcePinnedItems =
556
- sourceEnableItems?.multipleEnableItems?.pinnedItems ?? {};
557
- const allConvertedData = Object.keys( sourcePinnedItems ).reduce(
558
- ( accumulator, scope ) => {
559
- const data = sourcePinnedItems[ scope ];
560
- // Don't overwrite any existing data in the preferences store.
561
- if ( accumulator[ scope ]?.pinnedItems ) {
562
- return accumulator;
563
- }
564
-
565
- return {
566
- ...accumulator,
567
- [ scope ]: {
568
- ...accumulator[ scope ],
569
- pinnedItems: data,
570
- },
571
- };
572
- },
573
- convertedComplementaryAreas
574
- );
575
-
576
- persistence.set( preferencesStoreName, {
577
- preferences: allConvertedData,
578
- } );
579
-
580
- // Remove migrated preferences.
581
- const otherInterfaceItems = state[ interfaceStoreName ];
582
- persistence.set( interfaceStoreName, {
583
- ...otherInterfaceItems,
584
- enableItems: undefined,
585
- } );
586
- }
587
-
588
- persistencePlugin.__unstableMigrate = ( pluginOptions ) => {
589
- const persistence = createPersistenceInterface( pluginOptions );
590
-
591
- // Boolean feature preferences.
592
- migrateFeaturePreferencesToPreferencesStore(
593
- persistence,
594
- 'core/edit-widgets'
595
- );
596
- migrateFeaturePreferencesToPreferencesStore(
597
- persistence,
598
- 'core/customize-widgets'
599
- );
600
- migrateFeaturePreferencesToPreferencesStore(
601
- persistence,
602
- 'core/edit-post'
603
- );
604
- migrateFeaturePreferencesToPreferencesStore(
605
- persistence,
606
- 'core/edit-site'
607
- );
608
- migrateThirdPartyFeaturePreferencesToPreferencesStore( persistence );
609
-
610
- // Other ad-hoc preferences.
611
- migrateIndividualPreferenceToPreferencesStore(
612
- persistence,
613
- { from: 'core/edit-post', scope: 'core/edit-post' },
614
- 'hiddenBlockTypes'
615
- );
616
- migrateIndividualPreferenceToPreferencesStore(
617
- persistence,
618
- { from: 'core/edit-post', scope: 'core/edit-post' },
619
- 'editorMode'
620
- );
621
- migrateIndividualPreferenceToPreferencesStore(
622
- persistence,
623
- { from: 'core/edit-post', scope: 'core/edit-post' },
624
- 'preferredStyleVariations'
625
- );
626
- migrateIndividualPreferenceToPreferencesStore(
627
- persistence,
628
- { from: 'core/edit-post', scope: 'core/edit-post' },
629
- 'panels',
630
- convertEditPostPanels
631
- );
632
- migrateIndividualPreferenceToPreferencesStore(
633
- persistence,
634
- { from: 'core/editor', scope: 'core/edit-post' },
635
- 'isPublishSidebarEnabled'
636
- );
637
- migrateIndividualPreferenceToPreferencesStore(
638
- persistence,
639
- { from: 'core/edit-site', scope: 'core/edit-site' },
640
- 'editorMode'
641
- );
642
- migrateInterfaceEnableItemsToPreferencesStore( persistence );
643
- };
225
+ persistencePlugin.__unstableMigrate = () => {};
644
226
 
645
227
  export default persistencePlugin;