@wordpress/preferences-persistence 1.0.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE.md +788 -0
  3. package/README.md +59 -0
  4. package/build/create/debounce-async.js +80 -0
  5. package/build/create/debounce-async.js.map +1 -0
  6. package/build/create/index.js +115 -0
  7. package/build/create/index.js.map +1 -0
  8. package/build/index.js +61 -0
  9. package/build/index.js.map +1 -0
  10. package/build/migrations/legacy-local-storage-data/convert-edit-post-panels.js +60 -0
  11. package/build/migrations/legacy-local-storage-data/convert-edit-post-panels.js.map +1 -0
  12. package/build/migrations/legacy-local-storage-data/index.js +111 -0
  13. package/build/migrations/legacy-local-storage-data/index.js.map +1 -0
  14. package/build/migrations/legacy-local-storage-data/move-feature-preferences.js +135 -0
  15. package/build/migrations/legacy-local-storage-data/move-feature-preferences.js.map +1 -0
  16. package/build/migrations/legacy-local-storage-data/move-individual-preference.js +91 -0
  17. package/build/migrations/legacy-local-storage-data/move-individual-preference.js.map +1 -0
  18. package/build/migrations/legacy-local-storage-data/move-interface-enable-items.js +114 -0
  19. package/build/migrations/legacy-local-storage-data/move-interface-enable-items.js.map +1 -0
  20. package/build/migrations/legacy-local-storage-data/move-third-party-feature-preferences.js +99 -0
  21. package/build/migrations/legacy-local-storage-data/move-third-party-feature-preferences.js.map +1 -0
  22. package/build-module/create/debounce-async.js +73 -0
  23. package/build-module/create/debounce-async.js.map +1 -0
  24. package/build-module/create/index.js +104 -0
  25. package/build-module/create/index.js.map +1 -0
  26. package/build-module/index.js +45 -0
  27. package/build-module/index.js.map +1 -0
  28. package/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.js +53 -0
  29. package/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.js.map +1 -0
  30. package/build-module/migrations/legacy-local-storage-data/index.js +95 -0
  31. package/build-module/migrations/legacy-local-storage-data/index.js.map +1 -0
  32. package/build-module/migrations/legacy-local-storage-data/move-feature-preferences.js +128 -0
  33. package/build-module/migrations/legacy-local-storage-data/move-feature-preferences.js.map +1 -0
  34. package/build-module/migrations/legacy-local-storage-data/move-individual-preference.js +84 -0
  35. package/build-module/migrations/legacy-local-storage-data/move-individual-preference.js.map +1 -0
  36. package/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.js +107 -0
  37. package/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.js.map +1 -0
  38. package/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.js +92 -0
  39. package/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.js.map +1 -0
  40. package/package.json +37 -0
  41. package/src/create/debounce-async.js +75 -0
  42. package/src/create/index.js +112 -0
  43. package/src/create/test/debounce-async.js +129 -0
  44. package/src/create/test/index.js +178 -0
  45. package/src/index.js +49 -0
  46. package/src/migrations/legacy-local-storage-data/README.md +42 -0
  47. package/src/migrations/legacy-local-storage-data/convert-edit-post-panels.js +50 -0
  48. package/src/migrations/legacy-local-storage-data/index.js +102 -0
  49. package/src/migrations/legacy-local-storage-data/move-feature-preferences.js +135 -0
  50. package/src/migrations/legacy-local-storage-data/move-individual-preference.js +90 -0
  51. package/src/migrations/legacy-local-storage-data/move-interface-enable-items.js +120 -0
  52. package/src/migrations/legacy-local-storage-data/move-third-party-feature-preferences.js +98 -0
  53. package/src/migrations/legacy-local-storage-data/test/convert-edit-post-panels.js +47 -0
  54. package/src/migrations/legacy-local-storage-data/test/index.js +229 -0
  55. package/src/migrations/legacy-local-storage-data/test/move-feature-preferences.js +260 -0
  56. package/src/migrations/legacy-local-storage-data/test/move-individual-preference.js +188 -0
  57. package/src/migrations/legacy-local-storage-data/test/move-interface-enable-items.js +118 -0
  58. package/src/migrations/legacy-local-storage-data/test/move-third-party-feature-preferences.js +107 -0
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Migrates interface 'enableItems' data to the preferences store.
3
+ *
4
+ * The interface package stores this data in this format:
5
+ * ```js
6
+ * {
7
+ * enableItems: {
8
+ * singleEnableItems: {
9
+ * complementaryArea: {
10
+ * 'core/edit-post': 'edit-post/document',
11
+ * 'core/edit-site': 'edit-site/global-styles',
12
+ * }
13
+ * },
14
+ * multipleEnableItems: {
15
+ * pinnedItems: {
16
+ * 'core/edit-post': {
17
+ * 'plugin-1': true,
18
+ * },
19
+ * 'core/edit-site': {
20
+ * 'plugin-2': true,
21
+ * },
22
+ * },
23
+ * }
24
+ * }
25
+ * }
26
+ * ```
27
+ *
28
+ * and it should be converted it to:
29
+ * ```js
30
+ * {
31
+ * 'core/edit-post': {
32
+ * complementaryArea: 'edit-post/document',
33
+ * pinnedItems: {
34
+ * 'plugin-1': true,
35
+ * },
36
+ * },
37
+ * 'core/edit-site': {
38
+ * complementaryArea: 'edit-site/global-styles',
39
+ * pinnedItems: {
40
+ * 'plugin-2': true,
41
+ * },
42
+ * },
43
+ * }
44
+ * ```
45
+ *
46
+ * @param {Object} state The local storage state.
47
+ */
48
+ export default function moveInterfaceEnableItems(state) {
49
+ var _state$interfaceStore, _state$preferencesSto, _state$preferencesSto2, _sourceEnableItems$si, _sourceEnableItems$si2, _sourceEnableItems$mu, _sourceEnableItems$mu2;
50
+
51
+ const interfaceStoreName = 'core/interface';
52
+ const preferencesStoreName = 'core/preferences';
53
+ const sourceEnableItems = state === null || state === void 0 ? void 0 : (_state$interfaceStore = state[interfaceStoreName]) === null || _state$interfaceStore === void 0 ? void 0 : _state$interfaceStore.enableItems; // There's nothing to migrate, exit early.
54
+
55
+ if (!sourceEnableItems) {
56
+ return state;
57
+ }
58
+
59
+ const allPreferences = (_state$preferencesSto = state === null || state === void 0 ? void 0 : (_state$preferencesSto2 = state[preferencesStoreName]) === null || _state$preferencesSto2 === void 0 ? void 0 : _state$preferencesSto2.preferences) !== null && _state$preferencesSto !== void 0 ? _state$preferencesSto : {}; // First convert complementaryAreas into the right format.
60
+ // Use the existing preferences as the accumulator so that the data is
61
+ // merged.
62
+
63
+ const sourceComplementaryAreas = (_sourceEnableItems$si = sourceEnableItems === null || sourceEnableItems === void 0 ? void 0 : (_sourceEnableItems$si2 = sourceEnableItems.singleEnableItems) === null || _sourceEnableItems$si2 === void 0 ? void 0 : _sourceEnableItems$si2.complementaryArea) !== null && _sourceEnableItems$si !== void 0 ? _sourceEnableItems$si : {};
64
+ const preferencesWithConvertedComplementaryAreas = Object.keys(sourceComplementaryAreas).reduce((accumulator, scope) => {
65
+ var _accumulator$scope;
66
+
67
+ const data = sourceComplementaryAreas[scope]; // Don't overwrite any existing data in the preferences store.
68
+
69
+ if (accumulator !== null && accumulator !== void 0 && (_accumulator$scope = accumulator[scope]) !== null && _accumulator$scope !== void 0 && _accumulator$scope.complementaryArea) {
70
+ return accumulator;
71
+ }
72
+
73
+ return { ...accumulator,
74
+ [scope]: { ...accumulator[scope],
75
+ complementaryArea: data
76
+ }
77
+ };
78
+ }, allPreferences); // Next feed the converted complementary areas back into a reducer that
79
+ // converts the pinned items, resulting in the fully migrated data.
80
+
81
+ const sourcePinnedItems = (_sourceEnableItems$mu = sourceEnableItems === null || sourceEnableItems === void 0 ? void 0 : (_sourceEnableItems$mu2 = sourceEnableItems.multipleEnableItems) === null || _sourceEnableItems$mu2 === void 0 ? void 0 : _sourceEnableItems$mu2.pinnedItems) !== null && _sourceEnableItems$mu !== void 0 ? _sourceEnableItems$mu : {};
82
+ const allConvertedData = Object.keys(sourcePinnedItems).reduce((accumulator, scope) => {
83
+ var _accumulator$scope2;
84
+
85
+ const data = sourcePinnedItems[scope]; // Don't overwrite any existing data in the preferences store.
86
+
87
+ if (accumulator !== null && accumulator !== void 0 && (_accumulator$scope2 = accumulator[scope]) !== null && _accumulator$scope2 !== void 0 && _accumulator$scope2.pinnedItems) {
88
+ return accumulator;
89
+ }
90
+
91
+ return { ...accumulator,
92
+ [scope]: { ...accumulator[scope],
93
+ pinnedItems: data
94
+ }
95
+ };
96
+ }, preferencesWithConvertedComplementaryAreas);
97
+ const otherInterfaceItems = state[interfaceStoreName];
98
+ return { ...state,
99
+ [preferencesStoreName]: {
100
+ preferences: allConvertedData
101
+ },
102
+ [interfaceStoreName]: { ...otherInterfaceItems,
103
+ enableItems: undefined
104
+ }
105
+ };
106
+ }
107
+ //# sourceMappingURL=move-interface-enable-items.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["@wordpress/preferences-persistence/src/migrations/legacy-local-storage-data/move-interface-enable-items.js"],"names":["moveInterfaceEnableItems","state","interfaceStoreName","preferencesStoreName","sourceEnableItems","enableItems","allPreferences","preferences","sourceComplementaryAreas","singleEnableItems","complementaryArea","preferencesWithConvertedComplementaryAreas","Object","keys","reduce","accumulator","scope","data","sourcePinnedItems","multipleEnableItems","pinnedItems","allConvertedData","otherInterfaceItems","undefined"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASA,wBAAT,CAAmCC,KAAnC,EAA2C;AAAA;;AACzD,QAAMC,kBAAkB,GAAG,gBAA3B;AACA,QAAMC,oBAAoB,GAAG,kBAA7B;AACA,QAAMC,iBAAiB,GAAGH,KAAH,aAAGA,KAAH,gDAAGA,KAAK,CAAIC,kBAAJ,CAAR,0DAAG,sBAA+BG,WAAzD,CAHyD,CAKzD;;AACA,MAAK,CAAED,iBAAP,EAA2B;AAC1B,WAAOH,KAAP;AACA;;AAED,QAAMK,cAAc,4BAAGL,KAAH,aAAGA,KAAH,iDAAGA,KAAK,CAAIE,oBAAJ,CAAR,2DAAG,uBAAiCI,WAApC,yEAAmD,EAAvE,CAVyD,CAYzD;AACA;AACA;;AACA,QAAMC,wBAAwB,4BAC7BJ,iBAD6B,aAC7BA,iBAD6B,iDAC7BA,iBAAiB,C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AF,CAAjC;AAEA,SAAO,EACN,GAAGD,KADG;AAEN,KAAEE,oBAAF,GAA0B;AACzBI,MAAAA,WAAW,EAAEc;AADY,KAFpB;AAKN,KAAEnB,kBAAF,GAAwB,EACvB,GAAGoB,mBADoB;AAEvBjB,MAAAA,WAAW,EAAEkB;AAFU;AALlB,GAAP;AAUA","sourcesContent":["/**\n * Migrates interface 'enableItems' data to the preferences store.\n *\n * The interface package stores this data in this format:\n * ```js\n * {\n * enableItems: {\n * singleEnableItems: {\n * \t complementaryArea: {\n * 'core/edit-post': 'edit-post/document',\n * 'core/edit-site': 'edit-site/global-styles',\n * }\n * },\n * multipleEnableItems: {\n * pinnedItems: {\n * 'core/edit-post': {\n * 'plugin-1': true,\n * },\n * 'core/edit-site': {\n * 'plugin-2': true,\n * },\n * },\n * }\n * }\n * }\n * ```\n *\n * and it should be converted it to:\n * ```js\n * {\n * 'core/edit-post': {\n * complementaryArea: 'edit-post/document',\n * pinnedItems: {\n * 'plugin-1': true,\n * },\n * },\n * 'core/edit-site': {\n * complementaryArea: 'edit-site/global-styles',\n * pinnedItems: {\n * 'plugin-2': true,\n * },\n * },\n * }\n * ```\n *\n * @param {Object} state The local storage state.\n */\nexport default function moveInterfaceEnableItems( state ) {\n\tconst interfaceStoreName = 'core/interface';\n\tconst preferencesStoreName = 'core/preferences';\n\tconst sourceEnableItems = state?.[ interfaceStoreName ]?.enableItems;\n\n\t// There's nothing to migrate, exit early.\n\tif ( ! sourceEnableItems ) {\n\t\treturn state;\n\t}\n\n\tconst allPreferences = state?.[ preferencesStoreName ]?.preferences ?? {};\n\n\t// First convert complementaryAreas into the right format.\n\t// Use the existing preferences as the accumulator so that the data is\n\t// merged.\n\tconst sourceComplementaryAreas =\n\t\tsourceEnableItems?.singleEnableItems?.complementaryArea ?? {};\n\n\tconst preferencesWithConvertedComplementaryAreas = Object.keys(\n\t\tsourceComplementaryAreas\n\t).reduce( ( accumulator, scope ) => {\n\t\tconst data = sourceComplementaryAreas[ scope ];\n\n\t\t// Don't overwrite any existing data in the preferences store.\n\t\tif ( accumulator?.[ scope ]?.complementaryArea ) {\n\t\t\treturn accumulator;\n\t\t}\n\n\t\treturn {\n\t\t\t...accumulator,\n\t\t\t[ scope ]: {\n\t\t\t\t...accumulator[ scope ],\n\t\t\t\tcomplementaryArea: data,\n\t\t\t},\n\t\t};\n\t}, allPreferences );\n\n\t// Next feed the converted complementary areas back into a reducer that\n\t// converts the pinned items, resulting in the fully migrated data.\n\tconst sourcePinnedItems =\n\t\tsourceEnableItems?.multipleEnableItems?.pinnedItems ?? {};\n\tconst allConvertedData = Object.keys( sourcePinnedItems ).reduce(\n\t\t( accumulator, scope ) => {\n\t\t\tconst data = sourcePinnedItems[ scope ];\n\t\t\t// Don't overwrite any existing data in the preferences store.\n\t\t\tif ( accumulator?.[ scope ]?.pinnedItems ) {\n\t\t\t\treturn accumulator;\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\t...accumulator,\n\t\t\t\t[ scope ]: {\n\t\t\t\t\t...accumulator[ scope ],\n\t\t\t\t\tpinnedItems: data,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\tpreferencesWithConvertedComplementaryAreas\n\t);\n\n\tconst otherInterfaceItems = state[ interfaceStoreName ];\n\n\treturn {\n\t\t...state,\n\t\t[ preferencesStoreName ]: {\n\t\t\tpreferences: allConvertedData,\n\t\t},\n\t\t[ interfaceStoreName ]: {\n\t\t\t...otherInterfaceItems,\n\t\t\tenableItems: undefined,\n\t\t},\n\t};\n}\n"]}
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The interface package previously had a public API that could be used by
3
+ * plugins to set persisted boolean 'feature' preferences.
4
+ *
5
+ * While usage was likely non-existent or very small, this function ensures
6
+ * those are migrated to the preferences data structure. The interface
7
+ * package's APIs have now been deprecated and use the preferences store.
8
+ *
9
+ * This will convert data that looks like this:
10
+ * ```js
11
+ * {
12
+ * 'core/interface': {
13
+ * preferences: {
14
+ * features: {
15
+ * 'my-plugin': {
16
+ * myPluginFeature: true
17
+ * }
18
+ * }
19
+ * }
20
+ * }
21
+ * }
22
+ * ```
23
+ *
24
+ * To this:
25
+ * ```js
26
+ * * {
27
+ * 'core/preferences': {
28
+ * preferences: {
29
+ * 'my-plugin': {
30
+ * myPluginFeature: true
31
+ * }
32
+ * }
33
+ * }
34
+ * }
35
+ * ```
36
+ *
37
+ * @param {Object} state The local storage state
38
+ *
39
+ * @return {Object} The state with third party preferences moved to the
40
+ * preferences data structure.
41
+ */
42
+ export default function moveThirdPartyFeaturePreferencesToPreferences(state) {
43
+ var _state$interfaceStore, _state$interfaceStore2;
44
+
45
+ const interfaceStoreName = 'core/interface';
46
+ const preferencesStoreName = 'core/preferences';
47
+ const interfaceScopes = state === null || state === void 0 ? void 0 : (_state$interfaceStore = state[interfaceStoreName]) === null || _state$interfaceStore === void 0 ? void 0 : (_state$interfaceStore2 = _state$interfaceStore.preferences) === null || _state$interfaceStore2 === void 0 ? void 0 : _state$interfaceStore2.features;
48
+ const interfaceScopeKeys = interfaceScopes ? Object.keys(interfaceScopes) : [];
49
+
50
+ if (!(interfaceScopeKeys !== null && interfaceScopeKeys !== void 0 && interfaceScopeKeys.length)) {
51
+ return state;
52
+ }
53
+
54
+ return interfaceScopeKeys.reduce(function (convertedState, scope) {
55
+ var _convertedState$prefe, _convertedState$prefe2, _convertedState$prefe3, _convertedState$inter, _convertedState$inter2;
56
+
57
+ if (scope.startsWith('core')) {
58
+ return convertedState;
59
+ }
60
+
61
+ const featuresToMigrate = interfaceScopes === null || interfaceScopes === void 0 ? void 0 : interfaceScopes[scope];
62
+
63
+ if (!featuresToMigrate) {
64
+ return convertedState;
65
+ }
66
+
67
+ const existingMigratedData = convertedState === null || convertedState === void 0 ? void 0 : (_convertedState$prefe = convertedState[preferencesStoreName]) === null || _convertedState$prefe === void 0 ? void 0 : (_convertedState$prefe2 = _convertedState$prefe.preferences) === null || _convertedState$prefe2 === void 0 ? void 0 : _convertedState$prefe2[scope];
68
+
69
+ if (existingMigratedData) {
70
+ return convertedState;
71
+ }
72
+
73
+ const otherPreferencesScopes = convertedState === null || convertedState === void 0 ? void 0 : (_convertedState$prefe3 = convertedState[preferencesStoreName]) === null || _convertedState$prefe3 === void 0 ? void 0 : _convertedState$prefe3.preferences;
74
+ const otherInterfaceState = convertedState === null || convertedState === void 0 ? void 0 : convertedState[interfaceStoreName];
75
+ const otherInterfaceScopes = convertedState === null || convertedState === void 0 ? void 0 : (_convertedState$inter = convertedState[interfaceStoreName]) === null || _convertedState$inter === void 0 ? void 0 : (_convertedState$inter2 = _convertedState$inter.preferences) === null || _convertedState$inter2 === void 0 ? void 0 : _convertedState$inter2.features;
76
+ return { ...convertedState,
77
+ [preferencesStoreName]: {
78
+ preferences: { ...otherPreferencesScopes,
79
+ [scope]: featuresToMigrate
80
+ }
81
+ },
82
+ [interfaceStoreName]: { ...otherInterfaceState,
83
+ preferences: {
84
+ features: { ...otherInterfaceScopes,
85
+ [scope]: undefined
86
+ }
87
+ }
88
+ }
89
+ };
90
+ }, state);
91
+ }
92
+ //# sourceMappingURL=move-third-party-feature-preferences.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["@wordpress/preferences-persistence/src/migrations/legacy-local-storage-data/move-third-party-feature-preferences.js"],"names":["moveThirdPartyFeaturePreferencesToPreferences","state","interfaceStoreName","preferencesStoreName","interfaceScopes","preferences","features","interfaceScopeKeys","Object","keys","length","reduce","convertedState","scope","startsWith","featuresToMigrate","existingMigratedData","otherPreferencesScopes","otherInterfaceState","otherInterfaceScopes","undefined"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,eAAe,SAASA,6CAAT,CAAwDC,KAAxD,EAAgE;AAAA;;AAC9E,QAAMC,kBA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AAGM,cADG;AAEN,OAAET,oBAAF,GAA0B;AACzBE,QAAAA,WAAW,EAAE,EACZ,GAAGY,sBADS;AAEZ,WAAEJ,KAAF,GAAWE;AAFC;AADY,OAFpB;AAQN,OAAEb,kBAAF,GAAwB,EACvB,GAAGgB,mBADoB;AAEvBb,QAAAA,WAAW,EAAE;AACZC,UAAAA,QAAQ,EAAE,EACT,GAAGa,oBADM;AAET,aAAEN,KAAF,GAAWO;AAFF;AADE;AAFU;AARlB,KAAP;AAkBA,GAzCM,EAyCJnB,KAzCI,CAAP;AA0CA","sourcesContent":["/**\n * The interface package previously had a public API that could be used by\n * plugins to set persisted boolean 'feature' preferences.\n *\n * While usage was likely non-existent or very small, this function ensures\n * those are migrated to the preferences data structure. The interface\n * package's APIs have now been deprecated and use the preferences store.\n *\n * This will convert data that looks like this:\n * ```js\n * {\n * 'core/interface': {\n * preferences: {\n * features: {\n * 'my-plugin': {\n * myPluginFeature: true\n * }\n * }\n * }\n * }\n * }\n * ```\n *\n * To this:\n * ```js\n * * {\n * 'core/preferences': {\n * preferences: {\n * 'my-plugin': {\n * myPluginFeature: true\n * }\n * }\n * }\n * }\n * ```\n *\n * @param {Object} state The local storage state\n *\n * @return {Object} The state with third party preferences moved to the\n * preferences data structure.\n */\nexport default function moveThirdPartyFeaturePreferencesToPreferences( state ) {\n\tconst interfaceStoreName = 'core/interface';\n\tconst preferencesStoreName = 'core/preferences';\n\n\tconst interfaceScopes =\n\t\tstate?.[ interfaceStoreName ]?.preferences?.features;\n\tconst interfaceScopeKeys = interfaceScopes\n\t\t? Object.keys( interfaceScopes )\n\t\t: [];\n\n\tif ( ! interfaceScopeKeys?.length ) {\n\t\treturn state;\n\t}\n\n\treturn interfaceScopeKeys.reduce( function ( convertedState, scope ) {\n\t\tif ( scope.startsWith( 'core' ) ) {\n\t\t\treturn convertedState;\n\t\t}\n\n\t\tconst featuresToMigrate = interfaceScopes?.[ scope ];\n\t\tif ( ! featuresToMigrate ) {\n\t\t\treturn convertedState;\n\t\t}\n\n\t\tconst existingMigratedData =\n\t\t\tconvertedState?.[ preferencesStoreName ]?.preferences?.[ scope ];\n\n\t\tif ( existingMigratedData ) {\n\t\t\treturn convertedState;\n\t\t}\n\n\t\tconst otherPreferencesScopes =\n\t\t\tconvertedState?.[ preferencesStoreName ]?.preferences;\n\t\tconst otherInterfaceState = convertedState?.[ interfaceStoreName ];\n\t\tconst otherInterfaceScopes =\n\t\t\tconvertedState?.[ interfaceStoreName ]?.preferences?.features;\n\n\t\treturn {\n\t\t\t...convertedState,\n\t\t\t[ preferencesStoreName ]: {\n\t\t\t\tpreferences: {\n\t\t\t\t\t...otherPreferencesScopes,\n\t\t\t\t\t[ scope ]: featuresToMigrate,\n\t\t\t\t},\n\t\t\t},\n\t\t\t[ interfaceStoreName ]: {\n\t\t\t\t...otherInterfaceState,\n\t\t\t\tpreferences: {\n\t\t\t\t\tfeatures: {\n\t\t\t\t\t\t...otherInterfaceScopes,\n\t\t\t\t\t\t[ scope ]: undefined,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t};\n\t}, state );\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@wordpress/preferences-persistence",
3
+ "version": "1.0.0",
4
+ "description": "Persistence utilities for `wordpress/preferences`.",
5
+ "author": "The WordPress Contributors",
6
+ "license": "GPL-2.0-or-later",
7
+ "keywords": [
8
+ "wordpress",
9
+ "gutenberg",
10
+ "preferences",
11
+ "settings"
12
+ ],
13
+ "homepage": "https://github.com/WordPress/gutenberg/tree/HEAD/packages/preferences-persistence/README.md",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/WordPress/gutenberg.git",
17
+ "directory": "packages/preferences-persistence"
18
+ },
19
+ "bugs": {
20
+ "url": "https://github.com/WordPress/gutenberg/issues"
21
+ },
22
+ "engines": {
23
+ "node": ">=12"
24
+ },
25
+ "main": "build/index.js",
26
+ "module": "build-module/index.js",
27
+ "react-native": "src/index",
28
+ "sideEffects": false,
29
+ "dependencies": {
30
+ "@babel/runtime": "^7.16.0",
31
+ "@wordpress/api-fetch": "^6.5.0"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "gitHead": "4631d515033397fcfeda77e5755960253caef9bf"
37
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Performs a leading edge debounce of async functions.
3
+ *
4
+ * If three functions are throttled at the same time:
5
+ * - The first happens immediately.
6
+ * - The second is never called.
7
+ * - The third happens `delayMS` milliseconds after the first has resolved.
8
+ *
9
+ * This is distinct from `lodash.debounce` in that it waits for promise
10
+ * resolution.
11
+ *
12
+ * @param {Function} func A function that returns a promise.
13
+ * @param {number} delayMS A delay in milliseconds.
14
+ *
15
+ * @return {Function} A function that debounce whatever function is passed
16
+ * to it.
17
+ */
18
+ export default function debounceAsync( func, delayMS ) {
19
+ let timeoutId;
20
+ let activePromise;
21
+
22
+ return async function debounced( ...args ) {
23
+ // This is a leading edge debounce. If there's no promise or timeout
24
+ // in progress, call the debounced function immediately.
25
+ if ( ! activePromise && ! timeoutId ) {
26
+ return new Promise( ( resolve, reject ) => {
27
+ // Keep a reference to the promise.
28
+ activePromise = func( ...args )
29
+ .then( ( ...thenArgs ) => {
30
+ resolve( ...thenArgs );
31
+ } )
32
+ .catch( ( error ) => {
33
+ reject( error );
34
+ } )
35
+ .finally( () => {
36
+ // As soon this promise is complete, clear the way for the
37
+ // next one to happen immediately.
38
+ activePromise = null;
39
+ } );
40
+ } );
41
+ }
42
+
43
+ if ( activePromise ) {
44
+ // Let any active promises finish before queuing the next request.
45
+ await activePromise;
46
+ }
47
+
48
+ // Clear any active timeouts, abandoning any requests that have
49
+ // been queued but not been made.
50
+ if ( timeoutId ) {
51
+ clearTimeout( timeoutId );
52
+ timeoutId = null;
53
+ }
54
+
55
+ // Trigger any trailing edge calls to the function.
56
+ return new Promise( ( resolve, reject ) => {
57
+ // Schedule the next request but with a delay.
58
+ timeoutId = setTimeout( () => {
59
+ activePromise = func( ...args )
60
+ .then( ( ...thenArgs ) => {
61
+ resolve( ...thenArgs );
62
+ } )
63
+ .catch( ( error ) => {
64
+ reject( error );
65
+ } )
66
+ .finally( () => {
67
+ // As soon this promise is complete, clear the way for the
68
+ // next one to happen immediately.
69
+ activePromise = null;
70
+ timeoutId = null;
71
+ } );
72
+ }, delayMS );
73
+ } );
74
+ };
75
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * WordPress dependencies
3
+ */
4
+ import apiFetch from '@wordpress/api-fetch';
5
+
6
+ /**
7
+ * Internal dependencies
8
+ */
9
+ import debounceAsync from './debounce-async';
10
+
11
+ const EMPTY_OBJECT = {};
12
+ const localStorage = window.localStorage;
13
+
14
+ /**
15
+ * Creates a persistence layer that stores data in WordPress user meta via the
16
+ * REST API.
17
+ *
18
+ * @param {Object} options
19
+ * @param {?Object} options.preloadedData Any persisted preferences data that should be preloaded.
20
+ * When set, the persistence layer will avoid fetching data
21
+ * from the REST API.
22
+ * @param {?string} options.localStorageRestoreKey The key to use for restoring the localStorage backup, used
23
+ * when the persistence layer calls `localStorage.getItem` or
24
+ * `localStorage.setItem`.
25
+ * @param {?number} options.requestDebounceMS Debounce requests to the API so that they only occur at
26
+ * minimum every `requestDebounceMS` milliseconds, and don't
27
+ * swamp the server. Defaults to 2500ms.
28
+ *
29
+ * @return {Object} A persistence layer for WordPress user meta.
30
+ */
31
+ export default function create( {
32
+ preloadedData,
33
+ localStorageRestoreKey = 'WP_PREFERENCES_RESTORE_DATA',
34
+ requestDebounceMS = 2500,
35
+ } = {} ) {
36
+ let cache = preloadedData;
37
+ const debouncedApiFetch = debounceAsync( apiFetch, requestDebounceMS );
38
+
39
+ async function get() {
40
+ if ( cache ) {
41
+ return cache;
42
+ }
43
+
44
+ const user = await apiFetch( {
45
+ path: '/wp/v2/users/me?context=edit',
46
+ } );
47
+
48
+ const serverData = user?.meta?.persisted_preferences;
49
+ const localData = JSON.parse(
50
+ localStorage.getItem( localStorageRestoreKey )
51
+ );
52
+
53
+ // Date parse returns NaN for invalid input. Coerce anything invalid
54
+ // into a conveniently comparable zero.
55
+ const serverTimestamp = Date.parse( serverData?._modified ) || 0;
56
+ const localTimestamp = Date.parse( localData?._modified ) || 0;
57
+
58
+ // Prefer server data if it exists and is more recent.
59
+ // Otherwise fallback to localStorage data.
60
+ if ( serverData && serverTimestamp >= localTimestamp ) {
61
+ cache = serverData;
62
+ } else if ( localData ) {
63
+ cache = localData;
64
+ } else {
65
+ cache = EMPTY_OBJECT;
66
+ }
67
+
68
+ return cache;
69
+ }
70
+
71
+ function set( newData ) {
72
+ const dataWithTimestamp = {
73
+ ...newData,
74
+ _modified: new Date().toISOString(),
75
+ };
76
+ cache = dataWithTimestamp;
77
+
78
+ // Store data in local storage as a fallback. If for some reason the
79
+ // api request does not complete or becomes unavailable, this data
80
+ // can be used to restore preferences.
81
+ localStorage.setItem(
82
+ localStorageRestoreKey,
83
+ JSON.stringify( dataWithTimestamp )
84
+ );
85
+
86
+ // The user meta endpoint seems susceptible to errors when consecutive
87
+ // requests are made in quick succession. Ensure there's a gap between
88
+ // any consecutive requests.
89
+ //
90
+ // Catch and do nothing with errors from the REST API.
91
+ debouncedApiFetch( {
92
+ path: '/wp/v2/users/me',
93
+ method: 'PUT',
94
+ // `keepalive` will still send the request in the background,
95
+ // even when a browser unload event might interrupt it.
96
+ // This should hopefully make things more resilient.
97
+ // This does have a size limit of 64kb, but the data is usually
98
+ // much less.
99
+ keepalive: true,
100
+ data: {
101
+ meta: {
102
+ persisted_preferences: dataWithTimestamp,
103
+ },
104
+ },
105
+ } ).catch( () => {} );
106
+ }
107
+
108
+ return {
109
+ get,
110
+ set,
111
+ };
112
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Internal dependencies
3
+ */
4
+ import debounceAsync from '../debounce-async';
5
+
6
+ // See https://stackoverflow.com/questions/52177631/jest-timer-and-promise-dont-work-well-settimeout-and-async-function.
7
+ // Jest fake timers and async functions don't mix too well, since queued up
8
+ // promises can prevent jest from calling timeouts.
9
+ // This function flushes promises in the queue.
10
+ function flushPromises() {
11
+ return new Promise( jest.requireActual( 'timers' ).setImmediate );
12
+ }
13
+
14
+ // Promisify a timeout for use with jest.fn.
15
+ function timeout( milliseconds ) {
16
+ return new Promise( ( resolve ) => setTimeout( resolve, milliseconds ) );
17
+ }
18
+
19
+ describe( 'debounceAsync', () => {
20
+ it( 'uses a leading debounce, the first call happens immediately', () => {
21
+ const fn = jest.fn( async () => {} );
22
+ const debounced = debounceAsync( fn, 20 );
23
+ debounced();
24
+ expect( fn ).toHaveBeenCalledTimes( 1 );
25
+ } );
26
+
27
+ it( 'calls the function on the leading edge and then once on the trailing edge when there are multiple calls', async () => {
28
+ jest.useFakeTimers();
29
+ const fn = jest.fn( async () => {} );
30
+ const debounced = debounceAsync( fn, 20 );
31
+
32
+ debounced( 'A' );
33
+
34
+ expect( fn ).toHaveBeenCalledTimes( 1 );
35
+
36
+ debounced( 'B' );
37
+ debounced( 'C' );
38
+ debounced( 'D' );
39
+
40
+ await flushPromises();
41
+ jest.runAllTimers();
42
+
43
+ expect( fn ).toHaveBeenCalledTimes( 2 );
44
+ expect( fn ).toHaveBeenCalledWith( 'A' );
45
+ expect( fn ).toHaveBeenCalledWith( 'D' );
46
+
47
+ jest.runOnlyPendingTimers();
48
+ jest.useRealTimers();
49
+ } );
50
+
51
+ it( 'ensures the delay has elapsed between calls', async () => {
52
+ jest.useFakeTimers();
53
+ const fn = jest.fn( async () => timeout( 10 ) );
54
+ const debounced = debounceAsync( fn, 20 );
55
+
56
+ // The first call has been triggered, but will take 10ms to resolve.
57
+ debounced();
58
+ debounced();
59
+ debounced();
60
+ debounced();
61
+ expect( fn ).toHaveBeenCalledTimes( 1 );
62
+
63
+ // The first call has resolved. The delay period has started but has yet to finish.
64
+ await flushPromises();
65
+ jest.advanceTimersByTime( 11 );
66
+ expect( fn ).toHaveBeenCalledTimes( 1 );
67
+
68
+ // The second call is about to commence, but hasn't yet.
69
+ await flushPromises();
70
+ jest.advanceTimersByTime( 18 );
71
+ expect( fn ).toHaveBeenCalledTimes( 1 );
72
+
73
+ // The second call has now commenced.
74
+ await flushPromises();
75
+ jest.advanceTimersByTime( 2 );
76
+ expect( fn ).toHaveBeenCalledTimes( 2 );
77
+
78
+ // No more calls happen.
79
+ await flushPromises();
80
+ jest.runAllTimers();
81
+ expect( fn ).toHaveBeenCalledTimes( 2 );
82
+
83
+ jest.runOnlyPendingTimers();
84
+ jest.useRealTimers();
85
+ } );
86
+
87
+ it( 'is thenable, returning any data from promise resolution of the debounced function', async () => {
88
+ expect.assertions( 2 );
89
+ const fn = async () => 'test';
90
+ const debounced = debounceAsync( fn, 20 );
91
+
92
+ // Test the return value via awaiting.
93
+ const returnValue = await debounced();
94
+ expect( returnValue ).toBe( 'test' );
95
+
96
+ // Test then-ing.
97
+ await debounced().then( ( thenValue ) =>
98
+ expect( thenValue ).toBe( 'test' )
99
+ );
100
+ } );
101
+
102
+ it( 'is catchable', async () => {
103
+ expect.assertions( 2 );
104
+ const expectedError = new Error( 'test' );
105
+ const fn = async () => {
106
+ throw expectedError;
107
+ };
108
+
109
+ const debounced = debounceAsync( fn, 20 );
110
+
111
+ // Test traditional try/catch.
112
+ try {
113
+ await debounced();
114
+ } catch ( error ) {
115
+ // Disable reason - the test uses `expect.assertions` to ensure
116
+ // conditional assertions are called.
117
+ // eslint-disable-next-line jest/no-conditional-expect
118
+ expect( error ).toBe( expectedError );
119
+ }
120
+
121
+ // Test chained .catch().
122
+ await debounced().catch( ( error ) => {
123
+ // Disable reason - the test uses `expect.assertions` to ensure
124
+ // conditional assertions are called.
125
+ // eslint-disable-next-line jest/no-conditional-expect
126
+ expect( error ).toBe( expectedError );
127
+ } );
128
+ } );
129
+ } );