@wordpress/preferences-persistence 2.57.0 → 3.1.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 (136) hide show
  1. package/README.md +7 -7
  2. package/build/create/debounce-async.cjs +55 -58
  3. package/build/create/debounce-async.cjs.map +1 -7
  4. package/build/create/index.cjs +75 -91
  5. package/build/create/index.cjs.map +1 -7
  6. package/build/get-newest-data.cjs +64 -0
  7. package/build/get-newest-data.cjs.map +1 -0
  8. package/build/index.cjs +52 -53
  9. package/build/index.cjs.map +1 -7
  10. package/build/is-preferences-data.cjs +20 -0
  11. package/build/is-preferences-data.cjs.map +1 -0
  12. package/build/local-storage.cjs +39 -0
  13. package/build/local-storage.cjs.map +1 -0
  14. package/build/migrations/legacy-local-storage-data/convert-edit-post-panels.cjs +49 -38
  15. package/build/migrations/legacy-local-storage-data/convert-edit-post-panels.cjs.map +1 -7
  16. package/build/migrations/legacy-local-storage-data/index.cjs +95 -83
  17. package/build/migrations/legacy-local-storage-data/index.cjs.map +1 -7
  18. package/build/migrations/legacy-local-storage-data/move-feature-preferences.cjs +106 -77
  19. package/build/migrations/legacy-local-storage-data/move-feature-preferences.cjs.map +1 -7
  20. package/build/migrations/legacy-local-storage-data/move-individual-preference.cjs +70 -58
  21. package/build/migrations/legacy-local-storage-data/move-individual-preference.cjs.map +1 -7
  22. package/build/migrations/legacy-local-storage-data/move-interface-enable-items.cjs +93 -75
  23. package/build/migrations/legacy-local-storage-data/move-interface-enable-items.cjs.map +1 -7
  24. package/build/migrations/legacy-local-storage-data/move-third-party-feature-preferences.cjs +77 -65
  25. package/build/migrations/legacy-local-storage-data/move-third-party-feature-preferences.cjs.map +1 -7
  26. package/build/migrations/legacy-local-storage-data/types.cjs +5 -0
  27. package/build/migrations/preferences-package-data/convert-complementary-areas.cjs +19 -35
  28. package/build/migrations/preferences-package-data/convert-complementary-areas.cjs.map +1 -7
  29. package/build/migrations/preferences-package-data/convert-editor-settings.cjs +62 -60
  30. package/build/migrations/preferences-package-data/convert-editor-settings.cjs.map +1 -7
  31. package/build/migrations/preferences-package-data/index.cjs +29 -32
  32. package/build/migrations/preferences-package-data/index.cjs.map +1 -7
  33. package/build/types.cjs +5 -0
  34. package/build-module/create/debounce-async.mjs +51 -39
  35. package/build-module/create/debounce-async.mjs.map +1 -7
  36. package/build-module/create/index.mjs +51 -67
  37. package/build-module/create/index.mjs.map +1 -7
  38. package/build-module/get-newest-data.mjs +36 -0
  39. package/build-module/get-newest-data.mjs.map +1 -0
  40. package/build-module/index.mjs +24 -25
  41. package/build-module/index.mjs.map +1 -7
  42. package/build-module/is-preferences-data.mjs +15 -0
  43. package/build-module/is-preferences-data.mjs.map +1 -0
  44. package/build-module/local-storage.mjs +33 -0
  45. package/build-module/local-storage.mjs.map +1 -0
  46. package/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.mjs +45 -19
  47. package/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.mjs.map +1 -7
  48. package/build-module/migrations/legacy-local-storage-data/index.mjs +65 -52
  49. package/build-module/migrations/legacy-local-storage-data/index.mjs.map +1 -7
  50. package/build-module/migrations/legacy-local-storage-data/move-feature-preferences.mjs +102 -58
  51. package/build-module/migrations/legacy-local-storage-data/move-feature-preferences.mjs.map +1 -7
  52. package/build-module/migrations/legacy-local-storage-data/move-individual-preference.mjs +66 -39
  53. package/build-module/migrations/legacy-local-storage-data/move-individual-preference.mjs.map +1 -7
  54. package/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.mjs +89 -56
  55. package/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.mjs.map +1 -7
  56. package/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.mjs +73 -46
  57. package/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.mjs.map +1 -7
  58. package/build-module/migrations/legacy-local-storage-data/types.mjs +0 -0
  59. package/build-module/migrations/preferences-package-data/convert-complementary-areas.mjs +15 -16
  60. package/build-module/migrations/preferences-package-data/convert-complementary-areas.mjs.map +1 -7
  61. package/build-module/migrations/preferences-package-data/convert-editor-settings.mjs +41 -46
  62. package/build-module/migrations/preferences-package-data/convert-editor-settings.mjs.map +1 -7
  63. package/build-module/migrations/preferences-package-data/index.mjs +7 -8
  64. package/build-module/migrations/preferences-package-data/index.mjs.map +1 -7
  65. package/build-module/types.mjs +0 -0
  66. package/build-types/create/debounce-async.d.ts +19 -0
  67. package/build-types/create/debounce-async.d.ts.map +1 -0
  68. package/build-types/create/index.d.ts +20 -0
  69. package/build-types/create/index.d.ts.map +1 -0
  70. package/build-types/get-newest-data.d.ts +11 -0
  71. package/build-types/get-newest-data.d.ts.map +1 -0
  72. package/build-types/index.d.ts +20 -0
  73. package/build-types/index.d.ts.map +1 -0
  74. package/build-types/is-preferences-data.d.ts +11 -0
  75. package/build-types/is-preferences-data.d.ts.map +1 -0
  76. package/build-types/local-storage.d.ts +19 -0
  77. package/build-types/local-storage.d.ts.map +1 -0
  78. package/build-types/migrations/legacy-local-storage-data/convert-edit-post-panels.d.ts +35 -0
  79. package/build-types/migrations/legacy-local-storage-data/convert-edit-post-panels.d.ts.map +1 -0
  80. package/build-types/migrations/legacy-local-storage-data/index.d.ts +22 -0
  81. package/build-types/migrations/legacy-local-storage-data/index.d.ts.map +1 -0
  82. package/build-types/migrations/legacy-local-storage-data/move-feature-preferences.d.ts +60 -0
  83. package/build-types/migrations/legacy-local-storage-data/move-feature-preferences.d.ts.map +1 -0
  84. package/build-types/migrations/legacy-local-storage-data/move-individual-preference.d.ts +42 -0
  85. package/build-types/migrations/legacy-local-storage-data/move-individual-preference.d.ts.map +1 -0
  86. package/build-types/migrations/legacy-local-storage-data/move-interface-enable-items.d.ts +50 -0
  87. package/build-types/migrations/legacy-local-storage-data/move-interface-enable-items.d.ts.map +1 -0
  88. package/build-types/migrations/legacy-local-storage-data/move-third-party-feature-preferences.d.ts +44 -0
  89. package/build-types/migrations/legacy-local-storage-data/move-third-party-feature-preferences.d.ts.map +1 -0
  90. package/build-types/migrations/legacy-local-storage-data/types.d.ts +60 -0
  91. package/build-types/migrations/legacy-local-storage-data/types.d.ts.map +1 -0
  92. package/build-types/migrations/preferences-package-data/convert-complementary-areas.d.ts +5 -0
  93. package/build-types/migrations/preferences-package-data/convert-complementary-areas.d.ts.map +1 -0
  94. package/build-types/migrations/preferences-package-data/convert-editor-settings.d.ts +5 -0
  95. package/build-types/migrations/preferences-package-data/convert-editor-settings.d.ts.map +1 -0
  96. package/build-types/migrations/preferences-package-data/index.d.ts +5 -0
  97. package/build-types/migrations/preferences-package-data/index.d.ts.map +1 -0
  98. package/build-types/types.d.ts +40 -0
  99. package/build-types/types.d.ts.map +1 -0
  100. package/package.json +8 -7
  101. package/src/create/{debounce-async.js → debounce-async.ts} +13 -10
  102. package/src/create/index.ts +95 -0
  103. package/src/create/test/{debounce-async.js → debounce-async.ts} +7 -3
  104. package/src/create/test/{index.jsdom.test.js → index.jsdom.test.ts} +52 -4
  105. package/src/get-newest-data.ts +50 -0
  106. package/src/index.ts +40 -0
  107. package/src/is-preferences-data.ts +15 -0
  108. package/src/local-storage.ts +30 -0
  109. package/src/migrations/legacy-local-storage-data/{convert-edit-post-panels.js → convert-edit-post-panels.ts} +13 -5
  110. package/src/migrations/legacy-local-storage-data/{index.js → index.ts} +22 -15
  111. package/src/migrations/legacy-local-storage-data/{move-feature-preferences.js → move-feature-preferences.ts} +13 -7
  112. package/src/migrations/legacy-local-storage-data/{move-individual-preference.js → move-individual-preference.ts} +15 -12
  113. package/src/migrations/legacy-local-storage-data/{move-interface-enable-items.js → move-interface-enable-items.ts} +6 -2
  114. package/src/migrations/legacy-local-storage-data/{move-third-party-feature-preferences.js → move-third-party-feature-preferences.ts} +8 -4
  115. package/src/migrations/legacy-local-storage-data/test/{index.js → index.ts} +11 -0
  116. package/src/migrations/legacy-local-storage-data/types.ts +66 -0
  117. package/src/migrations/preferences-package-data/convert-complementary-areas.ts +21 -0
  118. package/src/migrations/preferences-package-data/convert-editor-settings.ts +58 -0
  119. package/src/migrations/preferences-package-data/{index.js → index.ts} +4 -1
  120. package/src/migrations/preferences-package-data/test/{convert-complementary-areas.js → convert-complementary-areas.ts} +10 -0
  121. package/src/migrations/preferences-package-data/test/convert-editor-settings.ts +58 -0
  122. package/src/test/index.jsdom.test.ts +97 -0
  123. package/src/test/local-storage.jsdom.test.ts +50 -0
  124. package/src/types.ts +43 -0
  125. package/CHANGELOG.md +0 -228
  126. package/src/create/index.js +0 -105
  127. package/src/index.js +0 -47
  128. package/src/migrations/preferences-package-data/convert-complementary-areas.js +0 -16
  129. package/src/migrations/preferences-package-data/convert-editor-settings.js +0 -48
  130. package/src/migrations/preferences-package-data/test/convert-editor-settings.js +0 -20
  131. /package/src/migrations/legacy-local-storage-data/test/{convert-edit-post-panels.js → convert-edit-post-panels.ts} +0 -0
  132. /package/src/migrations/legacy-local-storage-data/test/{move-feature-preferences.js → move-feature-preferences.ts} +0 -0
  133. /package/src/migrations/legacy-local-storage-data/test/{move-individual-preference.js → move-individual-preference.ts} +0 -0
  134. /package/src/migrations/legacy-local-storage-data/test/{move-interface-enable-items.js → move-interface-enable-items.ts} +0 -0
  135. /package/src/migrations/legacy-local-storage-data/test/{move-third-party-feature-preferences.js → move-third-party-feature-preferences.ts} +0 -0
  136. /package/src/migrations/preferences-package-data/test/{index.js → index.ts} +0 -0
@@ -0,0 +1,95 @@
1
+ import apiFetch from '@wordpress/api-fetch';
2
+ import debounceAsync from './debounce-async';
3
+ import getNewestData from '../get-newest-data';
4
+ import isPreferencesData from '../is-preferences-data';
5
+ import { writeStoredJSON } from '../local-storage';
6
+ import type {
7
+ CreateOptions,
8
+ PersistenceLayer,
9
+ PreferencesData,
10
+ } from '../types';
11
+
12
+ /**
13
+ * Creates a persistence layer that stores data in WordPress user meta via the
14
+ * REST API.
15
+ *
16
+ * @param {CreateOptions} [options]
17
+ * @param {PreferencesData|null} [options.preloadedData] Any persisted preferences data that should be preloaded.
18
+ * When set, the persistence layer will avoid fetching data
19
+ * from the REST API.
20
+ * @param {string} [options.localStorageRestoreKey] The key to use for restoring the localStorage backup, used
21
+ * when the persistence layer calls `localStorage.getItem` or
22
+ * `localStorage.setItem`.
23
+ * @param {number} [options.requestDebounceMS] Debounce requests to the API so that they only occur at
24
+ * minimum every `requestDebounceMS` milliseconds, and don't
25
+ * swamp the server. Defaults to 2500ms.
26
+ *
27
+ * @return A persistence layer for WordPress user meta.
28
+ */
29
+ export default function create( {
30
+ preloadedData,
31
+ localStorageRestoreKey = 'WP_PREFERENCES_RESTORE_DATA',
32
+ requestDebounceMS = 2500,
33
+ }: CreateOptions = {} ): PersistenceLayer {
34
+ let cache = isPreferencesData( preloadedData ) ? preloadedData : undefined;
35
+ const debouncedApiFetch = debounceAsync( apiFetch, requestDebounceMS );
36
+
37
+ async function get() {
38
+ if ( cache ) {
39
+ return cache;
40
+ }
41
+
42
+ const user = await apiFetch< {
43
+ meta?: { persisted_preferences?: unknown };
44
+ } >( {
45
+ path: '/wp/v2/users/me?context=edit',
46
+ } );
47
+
48
+ cache =
49
+ getNewestData(
50
+ user?.meta?.persisted_preferences,
51
+ localStorageRestoreKey
52
+ ) ?? {};
53
+
54
+ return cache;
55
+ }
56
+
57
+ function set( newData: PreferencesData ) {
58
+ const dataWithTimestamp = {
59
+ ...newData,
60
+ _modified: new Date().toISOString(),
61
+ };
62
+ cache = dataWithTimestamp;
63
+
64
+ // Store data in local storage as a fallback. If for some reason the
65
+ // api request does not complete or becomes unavailable, this data
66
+ // can be used to restore preferences.
67
+ writeStoredJSON( localStorageRestoreKey, dataWithTimestamp );
68
+
69
+ // The user meta endpoint seems susceptible to errors when consecutive
70
+ // requests are made in quick succession. Ensure there's a gap between
71
+ // any consecutive requests.
72
+ //
73
+ // Catch and do nothing with errors from the REST API.
74
+ debouncedApiFetch( {
75
+ path: '/wp/v2/users/me',
76
+ method: 'PUT',
77
+ // `keepalive` will still send the request in the background,
78
+ // even when a browser unload event might interrupt it.
79
+ // This should hopefully make things more resilient.
80
+ // This does have a size limit of 64kb, but the data is usually
81
+ // much less.
82
+ keepalive: true,
83
+ data: {
84
+ meta: {
85
+ persisted_preferences: dataWithTimestamp,
86
+ },
87
+ },
88
+ } ).catch( () => {} );
89
+ }
90
+
91
+ return {
92
+ get,
93
+ set,
94
+ };
95
+ }
@@ -8,8 +8,10 @@ function flushPromises() {
8
8
  }
9
9
 
10
10
  // Promisify a timeout for use with vi.fn.
11
- function timeout( milliseconds ) {
12
- return new Promise( ( resolve ) => setTimeout( resolve, milliseconds ) );
11
+ function timeout( milliseconds: number ) {
12
+ return new Promise< void >( ( resolve ) =>
13
+ setTimeout( resolve, milliseconds )
14
+ );
13
15
  }
14
16
 
15
17
  describe( 'debounceAsync', () => {
@@ -23,7 +25,9 @@ describe( 'debounceAsync', () => {
23
25
  it( 'calls the function on the leading edge and then once on the trailing edge when there are multiple calls', async () => {
24
26
  vi.useFakeTimers( { toFake: [ 'setTimeout', 'clearTimeout' ] } );
25
27
  try {
26
- const fn = vi.fn( async () => {} );
28
+ const fn = vi.fn< ( value: string ) => Promise< void > >(
29
+ async () => {}
30
+ );
27
31
  const debounced = debounceAsync( fn, 20 );
28
32
 
29
33
  debounced( 'A' );
@@ -2,16 +2,17 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
2
2
  import apiFetch from '@wordpress/api-fetch';
3
3
  import create from '..';
4
4
 
5
- vi.mock( import( '@wordpress/api-fetch' ), () => ( {
6
- default: vi.fn(),
7
- } ) );
5
+ vi.mock( import( '@wordpress/api-fetch' ) );
8
6
 
9
- const mockedApiFetch = vi.mocked( apiFetch );
7
+ const mockedApiFetch = vi.mocked(
8
+ apiFetch< { meta: { persisted_preferences: unknown } } | void >
9
+ );
10
10
 
11
11
  describe( 'create', () => {
12
12
  afterEach( () => {
13
13
  mockedApiFetch.mockReset();
14
14
  vi.restoreAllMocks();
15
+ window.localStorage.clear();
15
16
  } );
16
17
 
17
18
  describe( 'set', () => {
@@ -161,5 +162,52 @@ describe( 'create', () => {
161
162
  const { get } = create();
162
163
  expect( await get() ).toEqual( {} );
163
164
  } );
165
+
166
+ it( 'returns a new empty object for each persistence layer', async () => {
167
+ mockedApiFetch.mockResolvedValue( {
168
+ meta: { persisted_preferences: null },
169
+ } );
170
+
171
+ const first = await create().get();
172
+ first.core = { fixedToolbar: true };
173
+ expect( await create().get() ).toEqual( {} );
174
+ } );
175
+
176
+ it( 'fetches when the preloaded data is not an object', async () => {
177
+ mockedApiFetch.mockResolvedValueOnce( {
178
+ meta: {
179
+ persisted_preferences: { core: { fixedToolbar: true } },
180
+ },
181
+ } );
182
+
183
+ const { get } = create( {
184
+ // @ts-expect-error [] is not a PreferencesData object; invalid preloaded data triggers a fetch.
185
+ preloadedData: [],
186
+ } );
187
+ expect( await get() ).toEqual( { core: { fixedToolbar: true } } );
188
+ expect( mockedApiFetch ).toHaveBeenCalled();
189
+ } );
190
+
191
+ it( 'migrates data from the REST API', async () => {
192
+ mockedApiFetch.mockResolvedValueOnce( {
193
+ meta: {
194
+ persisted_preferences: {
195
+ 'core/edit-post': { fixedToolbar: true },
196
+ },
197
+ },
198
+ } );
199
+
200
+ const { get } = create();
201
+ expect( await get() ).toEqual( { core: { fixedToolbar: true } } );
202
+ } );
203
+
204
+ it( 'ignores an empty array from the REST API', async () => {
205
+ mockedApiFetch.mockResolvedValueOnce( {
206
+ meta: { persisted_preferences: [] },
207
+ } );
208
+
209
+ const { get } = create();
210
+ expect( await get() ).toEqual( {} );
211
+ } );
164
212
  } );
165
213
  } );
@@ -0,0 +1,50 @@
1
+ import isPreferencesData from './is-preferences-data';
2
+ import { readStoredJSON } from './local-storage';
3
+ import convertPreferencesPackageData from './migrations/preferences-package-data';
4
+ import type { PreferencesData, ScopedPreferences } from './types';
5
+
6
+ /**
7
+ * Picks the most recently modified preferences from the server data and the
8
+ * local storage backup, ignoring either when it is not a preferences object.
9
+ *
10
+ * @param serverData Preferences data from the server.
11
+ * @param localStorageRestoreKey The key of the local storage backup.
12
+ *
13
+ * @return The newest preferences data, or `null` when neither is valid.
14
+ */
15
+ function pickNewestData(
16
+ serverData: unknown,
17
+ localStorageRestoreKey: string
18
+ ): PreferencesData | null {
19
+ const storedData = readStoredJSON( localStorageRestoreKey );
20
+ const localData = isPreferencesData( storedData ) ? storedData : null;
21
+ if ( ! isPreferencesData( serverData ) ) {
22
+ return localData;
23
+ }
24
+
25
+ // Date parse returns NaN for invalid input. Coerce anything invalid
26
+ // into a conveniently comparable zero.
27
+ const serverModified = Date.parse( serverData._modified ?? '' ) || 0;
28
+ const localModified = Date.parse( localData?._modified ?? '' ) || 0;
29
+
30
+ // Prefer server data when it is at least as recent.
31
+ return localData && localModified > serverModified ? localData : serverData;
32
+ }
33
+
34
+ /**
35
+ * Gets the newest persisted preferences, migrated to the current format.
36
+ *
37
+ * @param serverData Preferences data from the server.
38
+ * @param localStorageRestoreKey The key of the local storage backup.
39
+ *
40
+ * @return The migrated preferences, or `undefined` when there are none.
41
+ */
42
+ export default function getNewestData(
43
+ serverData: unknown,
44
+ localStorageRestoreKey: string
45
+ ): ScopedPreferences | undefined {
46
+ const newestData = pickNewestData( serverData, localStorageRestoreKey );
47
+ return newestData
48
+ ? convertPreferencesPackageData( newestData as ScopedPreferences )
49
+ : undefined;
50
+ }
package/src/index.ts ADDED
@@ -0,0 +1,40 @@
1
+ import create from './create';
2
+ import convertLegacyLocalStorageData from './migrations/legacy-local-storage-data';
3
+ import getNewestData from './get-newest-data';
4
+ import type { PersistenceLayer } from './types';
5
+
6
+ export { create };
7
+
8
+ export type * from './types';
9
+
10
+ /**
11
+ * Creates the persistence layer with preloaded data.
12
+ *
13
+ * It prioritizes any data from the server, but falls back first to localStorage
14
+ * restore data, and then to any legacy data.
15
+ *
16
+ * This function is used internally by WordPress in an inline script, so
17
+ * prefixed with `__unstable`.
18
+ *
19
+ * @param serverData Preferences data preloaded from the server.
20
+ * @param userId The user id.
21
+ *
22
+ * @return The persistence layer initialized with the preloaded data.
23
+ */
24
+ export function __unstableCreatePersistenceLayer(
25
+ serverData: unknown,
26
+ userId: string | number
27
+ ): PersistenceLayer {
28
+ const localStorageRestoreKey = `WP_PREFERENCES_USER_${ userId }`;
29
+ return create( {
30
+ /*
31
+ * Fall back to data in the legacy format from the old persistence system.
32
+ * The server data is already preloaded, so fetching it again is redundant.
33
+ */
34
+ preloadedData:
35
+ getNewestData( serverData, localStorageRestoreKey ) ??
36
+ convertLegacyLocalStorageData( userId ) ??
37
+ {},
38
+ localStorageRestoreKey,
39
+ } );
40
+ }
@@ -0,0 +1,15 @@
1
+ import type { PreferencesData } from './types';
2
+
3
+ /**
4
+ * Checks whether persisted data is a preferences object. Empty user meta
5
+ * reaches the client as `[]` or `''`, which must not be used as preferences.
6
+ *
7
+ * @param data The persisted data.
8
+ *
9
+ * @return Whether the data is a preferences object.
10
+ */
11
+ export default function isPreferencesData(
12
+ data: unknown
13
+ ): data is PreferencesData {
14
+ return !! data && typeof data === 'object' && ! Array.isArray( data );
15
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Reads and parses a JSON value from local storage.
3
+ *
4
+ * @param key The local storage key.
5
+ *
6
+ * @return The parsed value, or `null` when the value is missing or invalid,
7
+ * or local storage is unavailable.
8
+ */
9
+ export function readStoredJSON( key: string ): unknown {
10
+ try {
11
+ const value = window.localStorage.getItem( key );
12
+ return value === null ? null : JSON.parse( value );
13
+ } catch {
14
+ return null;
15
+ }
16
+ }
17
+
18
+ /**
19
+ * Stores a value in local storage as JSON.
20
+ *
21
+ * Failures, such as blocked storage or an exceeded quota, are ignored.
22
+ *
23
+ * @param key The local storage key.
24
+ * @param value The value to store.
25
+ */
26
+ export function writeStoredJSON( key: string, value: unknown ) {
27
+ try {
28
+ window.localStorage.setItem( key, JSON.stringify( value ) );
29
+ } catch {}
30
+ }
@@ -1,3 +1,6 @@
1
+ import type { ScopePreferences } from '../../types';
2
+ import type { EditPostPanels, LegacyEditPostPanel } from './types';
3
+
1
4
  /**
2
5
  * Convert the post editor's panels state from:
3
6
  * ```
@@ -25,13 +28,18 @@
25
28
  * ],
26
29
  * }
27
30
  *
28
- * @param {Object} preferences A preferences object.
31
+ * @param preferences A preferences object.
29
32
  *
30
- * @return {Object} The converted data.
33
+ * @return The converted data.
31
34
  */
32
- export default function convertEditPostPanels( preferences ) {
33
- const panels = preferences?.panels ?? {};
34
- return Object.keys( panels ).reduce(
35
+ export default function convertEditPostPanels(
36
+ preferences: ScopePreferences
37
+ ): EditPostPanels {
38
+ const panels = ( preferences?.panels ?? {} ) as Record<
39
+ string,
40
+ LegacyEditPostPanel | undefined
41
+ >;
42
+ return Object.keys( panels ).reduce< EditPostPanels >(
35
43
  ( convertedData, panelName ) => {
36
44
  const panel = panels[ panelName ];
37
45
 
@@ -3,29 +3,33 @@ import moveThirdPartyFeaturePreferences from './move-third-party-feature-prefere
3
3
  import moveIndividualPreference from './move-individual-preference';
4
4
  import moveInterfaceEnableItems from './move-interface-enable-items';
5
5
  import convertEditPostPanels from './convert-edit-post-panels';
6
+ import isPreferencesData from '../../is-preferences-data';
7
+ import { readStoredJSON } from '../../local-storage';
8
+ import type { ScopedPreferences } from '../../types';
9
+ import type { LegacyData } from './types';
6
10
 
7
11
  /**
8
12
  * Gets the legacy local storage data for a given user.
9
13
  *
10
- * @param {string | number} userId The user id.
14
+ * @param userId The user id.
11
15
  *
12
- * @return {Object | null} The local storage data.
16
+ * @return The local storage data.
13
17
  */
14
- function getLegacyData( userId ) {
15
- const key = `WP_DATA_USER_${ userId }`;
16
- const unparsedData = window.localStorage.getItem( key );
17
- return JSON.parse( unparsedData );
18
+ function getLegacyData( userId: string | number ): LegacyData | null {
19
+ return readStoredJSON( `WP_DATA_USER_${ userId }` ) as LegacyData | null;
18
20
  }
19
21
 
20
22
  /**
21
23
  * Converts data from the old `@wordpress/data` package format.
22
24
  *
23
- * @param {Object | null | undefined} data The legacy data in its original format.
25
+ * @param data The legacy data in its original format.
24
26
  *
25
- * @return {Object | undefined} The converted data or `undefined` if there was
26
- * nothing to convert.
27
+ * @return The converted data or `undefined` if there was
28
+ * nothing to convert.
27
29
  */
28
- export function convertLegacyData( data ) {
30
+ export function convertLegacyData(
31
+ data: LegacyData | null | undefined
32
+ ): ScopedPreferences | undefined {
29
33
  if ( ! data ) {
30
34
  return;
31
35
  }
@@ -81,19 +85,22 @@ export function convertLegacyData( data ) {
81
85
 
82
86
  // The new system is only concerned with persisting
83
87
  // 'core/preferences' preferences reducer, so only return that.
84
- return data?.[ 'core/preferences' ]?.preferences;
88
+ const preferences = data?.[ 'core/preferences' ]?.preferences;
89
+ return isPreferencesData( preferences ) ? preferences : undefined;
85
90
  }
86
91
 
87
92
  /**
88
93
  * Gets the legacy local storage data for the given user and returns the
89
94
  * data converted to the new format.
90
95
  *
91
- * @param {string | number} userId The user id.
96
+ * @param userId The user id.
92
97
  *
93
- * @return {Object | undefined} The converted data or undefined if no local
94
- * storage data could be found.
98
+ * @return The converted data or undefined if no local
99
+ * storage data could be found.
95
100
  */
96
- export default function convertLegacyLocalStorageData( userId ) {
101
+ export default function convertLegacyLocalStorageData(
102
+ userId: string | number
103
+ ): ScopedPreferences | undefined {
97
104
  const data = getLegacyData( userId );
98
105
  return convertLegacyData( data );
99
106
  }
@@ -1,3 +1,5 @@
1
+ import type { FeaturePreferences, LegacyData } from './types';
2
+
1
3
  /**
2
4
  * Move the 'features' object in local storage from the sourceStoreName to the
3
5
  * preferences store data structure.
@@ -49,13 +51,16 @@
49
51
  * This function handles moving from either the source store or the interface
50
52
  * store to the preferences data structure.
51
53
  *
52
- * @param {Object} state The state before migration.
53
- * @param {string} sourceStoreName The name of the store that has persisted
54
- * preferences to migrate to the preferences
55
- * package.
56
- * @return {Object} The migrated state
54
+ * @param state The state before migration.
55
+ * @param sourceStoreName The name of the store that has persisted
56
+ * preferences to migrate to the preferences
57
+ * package.
58
+ * @return The migrated state
57
59
  */
58
- export default function moveFeaturePreferences( state, sourceStoreName ) {
60
+ export default function moveFeaturePreferences(
61
+ state: LegacyData,
62
+ sourceStoreName: string
63
+ ): LegacyData {
59
64
  const preferencesStoreName = 'core/preferences';
60
65
  const interfaceStoreName = 'core/interface';
61
66
 
@@ -67,7 +72,8 @@ export default function moveFeaturePreferences( state, sourceStoreName ) {
67
72
  state?.[ interfaceStoreName ]?.preferences?.features?.[
68
73
  sourceStoreName
69
74
  ];
70
- const sourceFeatures = state?.[ sourceStoreName ]?.preferences?.features;
75
+ const sourceFeatures = state?.[ sourceStoreName ]?.preferences?.features as
76
+ FeaturePreferences | undefined;
71
77
  const featuresToMigrate = interfaceFeatures
72
78
  ? interfaceFeatures
73
79
  : sourceFeatures;
@@ -1,4 +1,7 @@
1
- const identity = ( arg ) => arg;
1
+ import type { ScopePreferences } from '../../types';
2
+ import type { LegacyData } from './types';
3
+
4
+ const identity = < T >( arg: T ) => arg;
2
5
 
3
6
  /**
4
7
  * Migrates an individual item inside the `preferences` object for a package's store.
@@ -28,19 +31,19 @@ const identity = ( arg ) => arg;
28
31
  *
29
32
  * ```
30
33
  *
31
- * @param {Object} state The original state.
32
- * @param {Object} migrate An options object that contains details of the migration.
33
- * @param {string} migrate.from The name of the store to migrate from.
34
- * @param {string} migrate.to The scope in the preferences store to migrate to.
35
- * @param {string} key The key in the preferences object to migrate.
36
- * @param {?Function} convert A function that converts preferences from one format to another.
34
+ * @param state The original state.
35
+ * @param migrate An options object that contains details of the migration.
36
+ * @param migrate.from The name of the store to migrate from.
37
+ * @param migrate.to The scope in the preferences store to migrate to.
38
+ * @param key The key in the preferences object to migrate.
39
+ * @param convert A function that converts preferences from one format to another.
37
40
  */
38
41
  export default function moveIndividualPreferenceToPreferences(
39
- state,
40
- { from: sourceStoreName, to: scope },
41
- key,
42
- convert = identity
43
- ) {
42
+ state: LegacyData,
43
+ { from: sourceStoreName, to: scope }: { from: string; to: string },
44
+ key: string,
45
+ convert: ( preferences: ScopePreferences ) => object = identity
46
+ ): LegacyData {
44
47
  const preferencesStoreName = 'core/preferences';
45
48
  const sourcePreference = state?.[ sourceStoreName ]?.preferences?.[ key ];
46
49
 
@@ -1,3 +1,5 @@
1
+ import type { LegacyData } from './types';
2
+
1
3
  /**
2
4
  * Migrates interface 'enableItems' data to the preferences store.
3
5
  *
@@ -43,9 +45,11 @@
43
45
  * }
44
46
  * ```
45
47
  *
46
- * @param {Object} state The local storage state.
48
+ * @param state The local storage state.
47
49
  */
48
- export default function moveInterfaceEnableItems( state ) {
50
+ export default function moveInterfaceEnableItems(
51
+ state: LegacyData
52
+ ): LegacyData {
49
53
  const interfaceStoreName = 'core/interface';
50
54
  const preferencesStoreName = 'core/preferences';
51
55
  const sourceEnableItems = state?.[ interfaceStoreName ]?.enableItems;
@@ -1,3 +1,5 @@
1
+ import type { LegacyData } from './types';
2
+
1
3
  /**
2
4
  * The interface package previously had a public API that could be used by
3
5
  * plugins to set persisted boolean 'feature' preferences.
@@ -34,12 +36,14 @@
34
36
  * }
35
37
  * ```
36
38
  *
37
- * @param {Object} state The local storage state
39
+ * @param state The local storage state
38
40
  *
39
- * @return {Object} The state with third party preferences moved to the
40
- * preferences data structure.
41
+ * @return The state with third party preferences moved to the
42
+ * preferences data structure.
41
43
  */
42
- export default function moveThirdPartyFeaturePreferencesToPreferences( state ) {
44
+ export default function moveThirdPartyFeaturePreferencesToPreferences(
45
+ state: LegacyData
46
+ ): LegacyData {
43
47
  const interfaceStoreName = 'core/interface';
44
48
  const preferencesStoreName = 'core/preferences';
45
49
 
@@ -214,4 +214,15 @@ describe( 'convertLegacyData', () => {
214
214
  }
215
215
  ` );
216
216
  } );
217
+
218
+ it( 'ignores legacy preferences that are not an object', () => {
219
+ expect(
220
+ convertLegacyData( {
221
+ 'core/preferences': {
222
+ // @ts-expect-error [] is not a preferences object; non-object legacy data is ignored.
223
+ preferences: [],
224
+ },
225
+ } )
226
+ ).toBeUndefined();
227
+ } );
217
228
  } );
@@ -0,0 +1,66 @@
1
+ import type { ScopedPreferences } from '../../types';
2
+
3
+ /**
4
+ * Boolean 'feature' preferences, keyed by feature name.
5
+ */
6
+ export type FeaturePreferences = Record< string, boolean | undefined >;
7
+
8
+ /**
9
+ * Persisted state of a package's store, such as `core/edit-post`.
10
+ */
11
+ export interface LegacyStoreState {
12
+ preferences?: Record< string, unknown >;
13
+ [ key: string ]: unknown;
14
+ }
15
+
16
+ /**
17
+ * Persisted state of the `core/interface` store.
18
+ */
19
+ export interface LegacyInterfaceStoreState {
20
+ preferences?: {
21
+ features?: Record< string, FeaturePreferences | undefined >;
22
+ [ key: string ]: unknown;
23
+ };
24
+ enableItems?: {
25
+ singleEnableItems?: {
26
+ complementaryArea?: Record< string, string >;
27
+ };
28
+ multipleEnableItems?: {
29
+ pinnedItems?: Record< string, Record< string, boolean > >;
30
+ };
31
+ };
32
+ [ key: string ]: unknown;
33
+ }
34
+
35
+ /**
36
+ * Persisted state of the `core/preferences` store.
37
+ */
38
+ export interface LegacyPreferencesStoreState {
39
+ preferences?: ScopedPreferences;
40
+ [ key: string ]: unknown;
41
+ }
42
+
43
+ /**
44
+ * Local storage data in the legacy `@wordpress/data` format, keyed by store name.
45
+ */
46
+ export interface LegacyData {
47
+ 'core/interface'?: LegacyInterfaceStoreState;
48
+ 'core/preferences'?: LegacyPreferencesStoreState;
49
+ [ storeName: string ]: LegacyStoreState | undefined;
50
+ }
51
+
52
+ /**
53
+ * The post editor's panels state in the legacy format.
54
+ */
55
+ export interface LegacyEditPostPanel {
56
+ enabled?: boolean;
57
+ opened?: boolean;
58
+ }
59
+
60
+ /**
61
+ * The post editor's panels state in the preferences format.
62
+ */
63
+ export interface EditPostPanels {
64
+ inactivePanels: string[];
65
+ openPanels: string[];
66
+ }
@@ -0,0 +1,21 @@
1
+ import type { ScopedPreferences } from '../../types';
2
+
3
+ export default function convertComplementaryAreas( state: ScopedPreferences ) {
4
+ return Object.keys( state ).reduce(
5
+ ( stateAccumulator, scope ) => {
6
+ const scopeData = state[ scope ];
7
+
8
+ // If a complementary area is truthy, convert it to the `isComplementaryAreaVisible` boolean.
9
+ if ( scopeData?.complementaryArea ) {
10
+ const updatedScopeData = { ...scopeData };
11
+ delete updatedScopeData.complementaryArea;
12
+ updatedScopeData.isComplementaryAreaVisible = true;
13
+ stateAccumulator[ scope ] = updatedScopeData;
14
+ return stateAccumulator;
15
+ }
16
+
17
+ return stateAccumulator;
18
+ },
19
+ { ...state }
20
+ );
21
+ }