@wordpress/data 6.6.0 → 6.8.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 6.8.0 (2022-05-04)
6
+
7
+ ## 6.7.0 (2022-04-21)
8
+
5
9
  ## 6.6.0 (2022-04-08)
6
10
 
7
11
  ## 6.5.0 (2022-03-23)
@@ -124,19 +124,12 @@ function useSelect(mapSelect, deps) {
124
124
  const _mapSelect = hasMappingFunction ? callbackMapper : null;
125
125
 
126
126
  const registry = (0, _useRegistry.default)();
127
- const isAsync = (0, _useAsyncMode.default)(); // React can sometimes clear the `useMemo` cache.
128
- // We use the cache-stable `useMemoOne` to avoid
129
- // losing queues.
130
-
131
- const queueContext = (0, _useMemoOne.useMemoOne)(() => ({
132
- queue: true
133
- }), [registry]);
134
- const [, forceRender] = (0, _element.useReducer)(s => s + 1, 0);
127
+ const isAsync = (0, _useAsyncMode.default)();
128
+ const latestRegistry = (0, _element.useRef)(registry);
135
129
  const latestMapSelect = (0, _element.useRef)();
136
130
  const latestIsAsync = (0, _element.useRef)(isAsync);
137
131
  const latestMapOutput = (0, _element.useRef)();
138
- const latestMapOutputError = (0, _element.useRef)();
139
- const isMountedAndNotUnsubscribing = (0, _element.useRef)(); // Keep track of the stores being selected in the _mapSelect function,
132
+ const latestMapOutputError = (0, _element.useRef)(); // Keep track of the stores being selected in the _mapSelect function,
140
133
  // and only subscribe to those stores later.
141
134
 
142
135
  const listeningStores = (0, _element.useRef)([]);
@@ -149,10 +142,12 @@ function useSelect(mapSelect, deps) {
149
142
 
150
143
  if (_mapSelect) {
151
144
  mapOutput = latestMapOutput.current;
145
+ const hasReplacedRegistry = latestRegistry.current !== registry;
152
146
  const hasReplacedMapSelect = latestMapSelect.current !== _mapSelect;
147
+ const hasLeftAsyncMode = latestIsAsync.current && !isAsync;
153
148
  const lastMapSelectFailed = !!latestMapOutputError.current;
154
149
 
155
- if (hasReplacedMapSelect || lastMapSelectFailed) {
150
+ if (hasReplacedRegistry || hasReplacedMapSelect || hasLeftAsyncMode || lastMapSelectFailed) {
156
151
  try {
157
152
  mapOutput = wrapSelect(_mapSelect);
158
153
  } catch (error) {
@@ -175,43 +170,46 @@ function useSelect(mapSelect, deps) {
175
170
  return;
176
171
  }
177
172
 
173
+ latestRegistry.current = registry;
178
174
  latestMapSelect.current = _mapSelect;
175
+ latestIsAsync.current = isAsync;
179
176
  latestMapOutput.current = mapOutput;
180
177
  latestMapOutputError.current = undefined;
181
- isMountedAndNotUnsubscribing.current = true; // This has to run after the other ref updates
182
- // to avoid using stale values in the flushed
183
- // callbacks or potentially overwriting a
184
- // changed `latestMapOutput.current`.
185
-
186
- if (latestIsAsync.current !== isAsync) {
187
- latestIsAsync.current = isAsync;
188
- renderQueue.flush(queueContext);
189
- }
190
- });
178
+ }); // React can sometimes clear the `useMemo` cache.
179
+ // We use the cache-stable `useMemoOne` to avoid
180
+ // losing queues.
181
+
182
+ const queueContext = (0, _useMemoOne.useMemoOne)(() => ({
183
+ queue: true
184
+ }), [registry]);
185
+ const [, forceRender] = (0, _element.useReducer)(s => s + 1, 0);
186
+ const isMounted = (0, _element.useRef)(false);
191
187
  (0, _compose.useIsomorphicLayoutEffect)(() => {
192
188
  if (!hasMappingFunction) {
193
189
  return;
194
190
  }
195
191
 
196
192
  const onStoreChange = () => {
197
- if (isMountedAndNotUnsubscribing.current) {
198
- try {
199
- const newMapOutput = wrapSelect(latestMapSelect.current);
200
-
201
- if ((0, _isShallowEqual.default)(latestMapOutput.current, newMapOutput)) {
202
- return;
203
- }
193
+ try {
194
+ const newMapOutput = wrapSelect(latestMapSelect.current);
204
195
 
205
- latestMapOutput.current = newMapOutput;
206
- } catch (error) {
207
- latestMapOutputError.current = error;
196
+ if ((0, _isShallowEqual.default)(latestMapOutput.current, newMapOutput)) {
197
+ return;
208
198
  }
209
199
 
210
- forceRender();
200
+ latestMapOutput.current = newMapOutput;
201
+ } catch (error) {
202
+ latestMapOutputError.current = error;
211
203
  }
204
+
205
+ forceRender();
212
206
  };
213
207
 
214
208
  const onChange = () => {
209
+ if (!isMounted.current) {
210
+ return;
211
+ }
212
+
215
213
  if (latestIsAsync.current) {
216
214
  renderQueue.add(queueContext, onStoreChange);
217
215
  } else {
@@ -221,13 +219,14 @@ function useSelect(mapSelect, deps) {
221
219
  // could be set.
222
220
 
223
221
 
224
- onChange();
222
+ onStoreChange();
225
223
  const unsubscribers = listeningStores.current.map(storeName => registry.__unstableSubscribeStore(storeName, onChange));
224
+ isMounted.current = true;
226
225
  return () => {
227
- isMountedAndNotUnsubscribing.current = false; // The return value of the subscribe function could be undefined if the store is a custom generic store.
228
-
226
+ // The return value of the subscribe function could be undefined if the store is a custom generic store.
229
227
  unsubscribers.forEach(unsubscribe => unsubscribe === null || unsubscribe === void 0 ? void 0 : unsubscribe());
230
- renderQueue.flush(queueContext);
228
+ renderQueue.cancel(queueContext);
229
+ isMounted.current = false;
231
230
  }; // If you're tempted to eliminate the spread dependencies below don't do it!
232
231
  // We're passing these in from the calling function and want to make sure we're
233
232
  // examining every individual value inside the `deps` array.
@@ -1 +1 @@
1
- {"version":3,"sources":["@wordpress/data/src/components/use-select/index.js"],"names":["noop","renderQueue","useSelect","mapSelect","deps","hasMappingFunction","callbackMapper","_mapSelect","registry","isAsync","queueContext","queue","forceRender","s","latestMapSelect","latestIsAsync","latestMapOutput","latestMapOutputError","isMountedAndNotUnsubscribing","listeningStores","wrapSelect","callback","__unstableMarkListeningStores","select","depsChangedFlag","mapOutput","current","hasReplacedMapSelect","lastMapSelectFailed","error","errorMessage","message","stack","console","undefined","flush","onStoreChange","newMapOutput","onChange","add","unsubscribers","map","storeName","__unstableSubscribeStore","forEach","unsubscribe"],"mappings":";;;;;;;;;AAGA;;AAKA;;AACA;;AACA;;AACA;;AAKA;;AACA;;AAjBA;AACA;AACA;;AAGA;AACA;AACA;;AAMA;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AAtB;AAIA,WAAO,MAAM;AACZpB,MAAAA,4BAA4B,CAACQ,OAA7B,GAAuC,KAAvC,CADY,CAEZ;;AACAc,MAAAA,aAAa,CAACI,OAAd,CAAyBC,WAAF,IAAmBA,WAAnB,aAAmBA,WAAnB,uBAAmBA,WAAW,EAArD;AACA5C,MAAAA,WAAW,CAACkC,KAAZ,CAAmBzB,YAAnB;AACA,KALD,CAvCgC,CA6ChC;AACA;AACA;AACA,GAhDD,EAgDG,CAAEF,QAAF,EAAYY,UAAZ,EAAwBf,kBAAxB,EAA4CmB,eAA5C,CAhDH;AAkDA,SAAOnB,kBAAkB,GAAGoB,SAAH,GAAejB,QAAQ,CAACe,MAAT,CAAiBpB,SAAjB,CAAxC;AACA","sourcesContent":["/**\n * External dependencies\n */\nimport { useMemoOne } from 'use-memo-one';\n\n/**\n * WordPress dependencies\n */\nimport { createQueue } from '@wordpress/priority-queue';\nimport { useRef, useCallback, useMemo, useReducer } from '@wordpress/element';\nimport isShallowEqual from '@wordpress/is-shallow-equal';\nimport { useIsomorphicLayoutEffect } from '@wordpress/compose';\n\n/**\n * Internal dependencies\n */\nimport useRegistry from '../registry-provider/use-registry';\nimport useAsyncMode from '../async-mode-provider/use-async-mode';\n\nconst noop = () => {};\nconst renderQueue = createQueue();\n\n/** @typedef {import('../../types').StoreDescriptor} StoreDescriptor */\n\n/**\n * Custom react hook for retrieving props from registered selectors.\n *\n * In general, this custom React hook follows the\n * [rules of hooks](https://reactjs.org/docs/hooks-rules.html).\n *\n * @param {Function|StoreDescriptor|string} mapSelect Function called on every state change. The\n * returned value is exposed to the component\n * implementing this hook. The function receives\n * the `registry.select` method on the first\n * argument and the `registry` on the second\n * argument.\n * When a store key is passed, all selectors for\n * the store will be returned. This is only meant\n * for usage of these selectors in event\n * callbacks, not for data needed to create the\n * element tree.\n * @param {Array} deps If provided, this memoizes the mapSelect so the\n * same `mapSelect` is invoked on every state\n * change unless the dependencies change.\n *\n * @example\n * ```js\n * import { useSelect } from '@wordpress/data';\n *\n * function HammerPriceDisplay( { currency } ) {\n * const price = useSelect( ( select ) => {\n * return select( 'my-shop' ).getPrice( 'hammer', currency )\n * }, [ currency ] );\n * return new Intl.NumberFormat( 'en-US', {\n * style: 'currency',\n * currency,\n * } ).format( price );\n * }\n *\n * // Rendered in the application:\n * // <HammerPriceDisplay currency=\"USD\" />\n * ```\n *\n * In the above example, when `HammerPriceDisplay` is rendered into an\n * application, the price will be retrieved from the store state using the\n * `mapSelect` callback on `useSelect`. If the currency prop changes then\n * any price in the state for that currency is retrieved. If the currency prop\n * doesn't change and other props are passed in that do change, the price will\n * not change because the dependency is just the currency.\n *\n * When data is only used in an event callback, the data should not be retrieved\n * on render, so it may be useful to get the selectors function instead.\n *\n * **Don't use `useSelect` this way when calling the selectors in the render\n * function because your component won't re-render on a data change.**\n *\n * ```js\n * import { useSelect } from '@wordpress/data';\n *\n * function Paste( { children } ) {\n * const { getSettings } = useSelect( 'my-shop' );\n * function onPaste() {\n * // Do something with the settings.\n * const settings = getSettings();\n * }\n * return <div onPaste={ onPaste }>{ children }</div>;\n * }\n * ```\n *\n * @return {Function} A custom react hook.\n */\nexport default function useSelect( mapSelect, deps ) {\n\tconst hasMappingFunction = 'function' === typeof mapSelect;\n\n\t// If we're recalling a store by its name or by\n\t// its descriptor then we won't be caching the\n\t// calls to `mapSelect` because we won't be calling it.\n\tif ( ! hasMappingFunction ) {\n\t\tdeps = [];\n\t}\n\n\t// Because of the \"rule of hooks\" we have to call `useCallback`\n\t// on every invocation whether or not we have a real function\n\t// for `mapSelect`. we'll create this intermediate variable to\n\t// fulfill that need and then reference it with our \"real\"\n\t// `_mapSelect` if we can.\n\tconst callbackMapper = useCallback(\n\t\thasMappingFunction ? mapSelect : noop,\n\t\tdeps\n\t);\n\tconst _mapSelect = hasMappingFunction ? callbackMapper : null;\n\n\tconst registry = useRegistry();\n\tconst isAsync = useAsyncMode();\n\t// React can sometimes clear the `useMemo` cache.\n\t// We use the cache-stable `useMemoOne` to avoid\n\t// losing queues.\n\tconst queueContext = useMemoOne( () => ( { queue: true } ), [ registry ] );\n\tconst [ , forceRender ] = useReducer( ( s ) => s + 1, 0 );\n\n\tconst latestMapSelect = useRef();\n\tconst latestIsAsync = useRef( isAsync );\n\tconst latestMapOutput = useRef();\n\tconst latestMapOutputError = useRef();\n\tconst isMountedAndNotUnsubscribing = useRef();\n\n\t// Keep track of the stores being selected in the _mapSelect function,\n\t// and only subscribe to those stores later.\n\tconst listeningStores = useRef( [] );\n\tconst wrapSelect = useCallback(\n\t\t( callback ) =>\n\t\t\tregistry.__unstableMarkListeningStores(\n\t\t\t\t() => callback( registry.select, registry ),\n\t\t\t\tlisteningStores\n\t\t\t),\n\t\t[ registry ]\n\t);\n\n\t// Generate a \"flag\" for used in the effect dependency array.\n\t// It's different than just using `mapSelect` since deps could be undefined,\n\t// in that case, we would still want to memoize it.\n\tconst depsChangedFlag = useMemo( () => ( {} ), deps || [] );\n\n\tlet mapOutput;\n\n\tif ( _mapSelect ) {\n\t\tmapOutput = latestMapOutput.current;\n\t\tconst hasReplacedMapSelect = latestMapSelect.current !== _mapSelect;\n\t\tconst lastMapSelectFailed = !! latestMapOutputError.current;\n\n\t\tif ( hasReplacedMapSelect || lastMapSelectFailed ) {\n\t\t\ttry {\n\t\t\t\tmapOutput = wrapSelect( _mapSelect );\n\t\t\t} catch ( error ) {\n\t\t\t\tlet errorMessage = `An error occurred while running 'mapSelect': ${ error.message }`;\n\n\t\t\t\tif ( latestMapOutputError.current ) {\n\t\t\t\t\terrorMessage += `\\nThe error may be correlated with this previous error:\\n`;\n\t\t\t\t\terrorMessage += `${ latestMapOutputError.current.stack }\\n\\n`;\n\t\t\t\t\terrorMessage += 'Original stack trace:';\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.error( errorMessage );\n\t\t\t}\n\t\t}\n\t}\n\n\tuseIsomorphicLayoutEffect( () => {\n\t\tif ( ! hasMappingFunction ) {\n\t\t\treturn;\n\t\t}\n\n\t\tlatestMapSelect.current = _mapSelect;\n\t\tlatestMapOutput.current = mapOutput;\n\t\tlatestMapOutputError.current = undefined;\n\t\tisMountedAndNotUnsubscribing.current = true;\n\n\t\t// This has to run after the other ref updates\n\t\t// to avoid using stale values in the flushed\n\t\t// callbacks or potentially overwriting a\n\t\t// changed `latestMapOutput.current`.\n\t\tif ( latestIsAsync.current !== isAsync ) {\n\t\t\tlatestIsAsync.current = isAsync;\n\t\t\trenderQueue.flush( queueContext );\n\t\t}\n\t} );\n\n\tuseIsomorphicLayoutEffect( () => {\n\t\tif ( ! hasMappingFunction ) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst onStoreChange = () => {\n\t\t\tif ( isMountedAndNotUnsubscribing.current ) {\n\t\t\t\ttry {\n\t\t\t\t\tconst newMapOutput = wrapSelect( latestMapSelect.current );\n\n\t\t\t\t\tif (\n\t\t\t\t\t\tisShallowEqual( latestMapOutput.current, newMapOutput )\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlatestMapOutput.current = newMapOutput;\n\t\t\t\t} catch ( error ) {\n\t\t\t\t\tlatestMapOutputError.current = error;\n\t\t\t\t}\n\t\t\t\tforceRender();\n\t\t\t}\n\t\t};\n\n\t\tconst onChange = () => {\n\t\t\tif ( latestIsAsync.current ) {\n\t\t\t\trenderQueue.add( queueContext, onStoreChange );\n\t\t\t} else {\n\t\t\t\tonStoreChange();\n\t\t\t}\n\t\t};\n\n\t\t// Catch any possible state changes during mount before the subscription\n\t\t// could be set.\n\t\tonChange();\n\n\t\tconst unsubscribers = listeningStores.current.map( ( storeName ) =>\n\t\t\tregistry.__unstableSubscribeStore( storeName, onChange )\n\t\t);\n\n\t\treturn () => {\n\t\t\tisMountedAndNotUnsubscribing.current = false;\n\t\t\t// The return value of the subscribe function could be undefined if the store is a custom generic store.\n\t\t\tunsubscribers.forEach( ( unsubscribe ) => unsubscribe?.() );\n\t\t\trenderQueue.flush( queueContext );\n\t\t};\n\t\t// If you're tempted to eliminate the spread dependencies below don't do it!\n\t\t// We're passing these in from the calling function and want to make sure we're\n\t\t// examining every individual value inside the `deps` array.\n\t}, [ registry, wrapSelect, hasMappingFunction, depsChangedFlag ] );\n\n\treturn hasMappingFunction ? mapOutput : registry.select( mapSelect );\n}\n"]}
1
+ {"version":3,"sources":["@wordpress/data/src/components/use-select/index.js"],"names":["noop","renderQueue","useSelect","mapSelect","deps","hasMappingFunction","callbackMapper","_mapSelect","registry","isAsync","latestRegistry","latestMapSelect","latestIsAsync","latestMapOutput","latestMapOutputError","listeningStores","wrapSelect","callback","__unstableMarkListeningStores","select","depsChangedFlag","mapOutput","current","hasReplacedRegistry","hasReplacedMapSelect","hasLeftAsyncMode","lastMapSelectFailed","error","errorMessage","message","stack","console","undefined","queueContext","queue","forceRender","s","isMounted","onStoreChange","newMapOutput","onChange","add","unsubscribers","map","storeName","__unstableSubscribeStore","forEach","unsubscribe","cancel"],"mappings":";;;;;;;;;AAGA;;AAKA;;AACA;;AACA;;AACA;;AAKA;;AACA;;AAjBA;AACA;AACA;;AAGA;AACA;AACA;;AAMA;AACA;AACA;AAIA,MAAMA,IAAI,GAAG,MAAM,CAAE,CAArB;;AACA,MAAMC,WAAW,GAAG,iCAApB;AAEA;;AAEA;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;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACe,SAASC,SAAT,CAAoBC,SAApB,EAA+BC,IAA/B,EAAsC;AACpD,QAAMC,kBAAkB,GAAG,eAAe,OAAOF,SAAjD,CADoD,C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Q,CAACW,MAAT,CAAiBhB,SAAjB,CAAxC;AACA","sourcesContent":["/**\n * External dependencies\n */\nimport { useMemoOne } from 'use-memo-one';\n\n/**\n * WordPress dependencies\n */\nimport { createQueue } from '@wordpress/priority-queue';\nimport { useRef, useCallback, useMemo, useReducer } from '@wordpress/element';\nimport isShallowEqual from '@wordpress/is-shallow-equal';\nimport { useIsomorphicLayoutEffect } from '@wordpress/compose';\n\n/**\n * Internal dependencies\n */\nimport useRegistry from '../registry-provider/use-registry';\nimport useAsyncMode from '../async-mode-provider/use-async-mode';\n\nconst noop = () => {};\nconst renderQueue = createQueue();\n\n/** @typedef {import('../../types').StoreDescriptor} StoreDescriptor */\n\n/**\n * Custom react hook for retrieving props from registered selectors.\n *\n * In general, this custom React hook follows the\n * [rules of hooks](https://reactjs.org/docs/hooks-rules.html).\n *\n * @param {Function|StoreDescriptor|string} mapSelect Function called on every state change. The\n * returned value is exposed to the component\n * implementing this hook. The function receives\n * the `registry.select` method on the first\n * argument and the `registry` on the second\n * argument.\n * When a store key is passed, all selectors for\n * the store will be returned. This is only meant\n * for usage of these selectors in event\n * callbacks, not for data needed to create the\n * element tree.\n * @param {Array} deps If provided, this memoizes the mapSelect so the\n * same `mapSelect` is invoked on every state\n * change unless the dependencies change.\n *\n * @example\n * ```js\n * import { useSelect } from '@wordpress/data';\n *\n * function HammerPriceDisplay( { currency } ) {\n * const price = useSelect( ( select ) => {\n * return select( 'my-shop' ).getPrice( 'hammer', currency )\n * }, [ currency ] );\n * return new Intl.NumberFormat( 'en-US', {\n * style: 'currency',\n * currency,\n * } ).format( price );\n * }\n *\n * // Rendered in the application:\n * // <HammerPriceDisplay currency=\"USD\" />\n * ```\n *\n * In the above example, when `HammerPriceDisplay` is rendered into an\n * application, the price will be retrieved from the store state using the\n * `mapSelect` callback on `useSelect`. If the currency prop changes then\n * any price in the state for that currency is retrieved. If the currency prop\n * doesn't change and other props are passed in that do change, the price will\n * not change because the dependency is just the currency.\n *\n * When data is only used in an event callback, the data should not be retrieved\n * on render, so it may be useful to get the selectors function instead.\n *\n * **Don't use `useSelect` this way when calling the selectors in the render\n * function because your component won't re-render on a data change.**\n *\n * ```js\n * import { useSelect } from '@wordpress/data';\n *\n * function Paste( { children } ) {\n * const { getSettings } = useSelect( 'my-shop' );\n * function onPaste() {\n * // Do something with the settings.\n * const settings = getSettings();\n * }\n * return <div onPaste={ onPaste }>{ children }</div>;\n * }\n * ```\n *\n * @return {Function} A custom react hook.\n */\nexport default function useSelect( mapSelect, deps ) {\n\tconst hasMappingFunction = 'function' === typeof mapSelect;\n\n\t// If we're recalling a store by its name or by\n\t// its descriptor then we won't be caching the\n\t// calls to `mapSelect` because we won't be calling it.\n\tif ( ! hasMappingFunction ) {\n\t\tdeps = [];\n\t}\n\n\t// Because of the \"rule of hooks\" we have to call `useCallback`\n\t// on every invocation whether or not we have a real function\n\t// for `mapSelect`. we'll create this intermediate variable to\n\t// fulfill that need and then reference it with our \"real\"\n\t// `_mapSelect` if we can.\n\tconst callbackMapper = useCallback(\n\t\thasMappingFunction ? mapSelect : noop,\n\t\tdeps\n\t);\n\tconst _mapSelect = hasMappingFunction ? callbackMapper : null;\n\n\tconst registry = useRegistry();\n\tconst isAsync = useAsyncMode();\n\n\tconst latestRegistry = useRef( registry );\n\tconst latestMapSelect = useRef();\n\tconst latestIsAsync = useRef( isAsync );\n\tconst latestMapOutput = useRef();\n\tconst latestMapOutputError = useRef();\n\n\t// Keep track of the stores being selected in the _mapSelect function,\n\t// and only subscribe to those stores later.\n\tconst listeningStores = useRef( [] );\n\tconst wrapSelect = useCallback(\n\t\t( callback ) =>\n\t\t\tregistry.__unstableMarkListeningStores(\n\t\t\t\t() => callback( registry.select, registry ),\n\t\t\t\tlisteningStores\n\t\t\t),\n\t\t[ registry ]\n\t);\n\n\t// Generate a \"flag\" for used in the effect dependency array.\n\t// It's different than just using `mapSelect` since deps could be undefined,\n\t// in that case, we would still want to memoize it.\n\tconst depsChangedFlag = useMemo( () => ( {} ), deps || [] );\n\n\tlet mapOutput;\n\n\tif ( _mapSelect ) {\n\t\tmapOutput = latestMapOutput.current;\n\t\tconst hasReplacedRegistry = latestRegistry.current !== registry;\n\t\tconst hasReplacedMapSelect = latestMapSelect.current !== _mapSelect;\n\t\tconst hasLeftAsyncMode = latestIsAsync.current && ! isAsync;\n\t\tconst lastMapSelectFailed = !! latestMapOutputError.current;\n\n\t\tif (\n\t\t\thasReplacedRegistry ||\n\t\t\thasReplacedMapSelect ||\n\t\t\thasLeftAsyncMode ||\n\t\t\tlastMapSelectFailed\n\t\t) {\n\t\t\ttry {\n\t\t\t\tmapOutput = wrapSelect( _mapSelect );\n\t\t\t} catch ( error ) {\n\t\t\t\tlet errorMessage = `An error occurred while running 'mapSelect': ${ error.message }`;\n\n\t\t\t\tif ( latestMapOutputError.current ) {\n\t\t\t\t\terrorMessage += `\\nThe error may be correlated with this previous error:\\n`;\n\t\t\t\t\terrorMessage += `${ latestMapOutputError.current.stack }\\n\\n`;\n\t\t\t\t\terrorMessage += 'Original stack trace:';\n\t\t\t\t}\n\n\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\tconsole.error( errorMessage );\n\t\t\t}\n\t\t}\n\t}\n\n\tuseIsomorphicLayoutEffect( () => {\n\t\tif ( ! hasMappingFunction ) {\n\t\t\treturn;\n\t\t}\n\n\t\tlatestRegistry.current = registry;\n\t\tlatestMapSelect.current = _mapSelect;\n\t\tlatestIsAsync.current = isAsync;\n\t\tlatestMapOutput.current = mapOutput;\n\t\tlatestMapOutputError.current = undefined;\n\t} );\n\n\t// React can sometimes clear the `useMemo` cache.\n\t// We use the cache-stable `useMemoOne` to avoid\n\t// losing queues.\n\tconst queueContext = useMemoOne( () => ( { queue: true } ), [ registry ] );\n\tconst [ , forceRender ] = useReducer( ( s ) => s + 1, 0 );\n\tconst isMounted = useRef( false );\n\n\tuseIsomorphicLayoutEffect( () => {\n\t\tif ( ! hasMappingFunction ) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst onStoreChange = () => {\n\t\t\ttry {\n\t\t\t\tconst newMapOutput = wrapSelect( latestMapSelect.current );\n\n\t\t\t\tif ( isShallowEqual( latestMapOutput.current, newMapOutput ) ) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tlatestMapOutput.current = newMapOutput;\n\t\t\t} catch ( error ) {\n\t\t\t\tlatestMapOutputError.current = error;\n\t\t\t}\n\t\t\tforceRender();\n\t\t};\n\n\t\tconst onChange = () => {\n\t\t\tif ( ! isMounted.current ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif ( latestIsAsync.current ) {\n\t\t\t\trenderQueue.add( queueContext, onStoreChange );\n\t\t\t} else {\n\t\t\t\tonStoreChange();\n\t\t\t}\n\t\t};\n\n\t\t// Catch any possible state changes during mount before the subscription\n\t\t// could be set.\n\t\tonStoreChange();\n\n\t\tconst unsubscribers = listeningStores.current.map( ( storeName ) =>\n\t\t\tregistry.__unstableSubscribeStore( storeName, onChange )\n\t\t);\n\n\t\tisMounted.current = true;\n\n\t\treturn () => {\n\t\t\t// The return value of the subscribe function could be undefined if the store is a custom generic store.\n\t\t\tunsubscribers.forEach( ( unsubscribe ) => unsubscribe?.() );\n\t\t\trenderQueue.cancel( queueContext );\n\t\t\tisMounted.current = false;\n\t\t};\n\t\t// If you're tempted to eliminate the spread dependencies below don't do it!\n\t\t// We're passing these in from the calling function and want to make sure we're\n\t\t// examining every individual value inside the `deps` array.\n\t}, [ registry, wrapSelect, hasMappingFunction, depsChangedFlag ] );\n\n\treturn hasMappingFunction ? mapOutput : registry.select( mapSelect );\n}\n"]}
@@ -5,14 +5,8 @@ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefau
5
5
  Object.defineProperty(exports, "__esModule", {
6
6
  value: true
7
7
  });
8
- exports.convertEditPostPanels = convertEditPostPanels;
9
8
  exports.createPersistenceInterface = createPersistenceInterface;
10
- exports.default = void 0;
11
- exports.migrateFeaturePreferencesToPreferencesStore = migrateFeaturePreferencesToPreferencesStore;
12
- exports.migrateIndividualPreferenceToPreferencesStore = migrateIndividualPreferenceToPreferencesStore;
13
- exports.migrateInterfaceEnableItemsToPreferencesStore = migrateInterfaceEnableItemsToPreferencesStore;
14
- exports.migrateThirdPartyFeaturePreferencesToPreferencesStore = migrateThirdPartyFeaturePreferencesToPreferencesStore;
15
- exports.withLazySameState = void 0;
9
+ exports.withLazySameState = exports.default = void 0;
16
10
 
17
11
  var _lodash = require("lodash");
18
12
 
@@ -231,375 +225,8 @@ function persistencePlugin(registry, pluginOptions) {
231
225
 
232
226
  };
233
227
  }
234
- /**
235
- * Move the 'features' object in local storage from the sourceStoreName to the
236
- * preferences store.
237
- *
238
- * @param {Object} persistence The persistence interface.
239
- * @param {string} sourceStoreName The name of the store that has persisted
240
- * preferences to migrate to the preferences
241
- * package.
242
- */
243
-
244
-
245
- function migrateFeaturePreferencesToPreferencesStore(persistence, sourceStoreName) {
246
- var _state$interfaceStore, _state$interfaceStore2, _state$interfaceStore3, _state$sourceStoreNam, _state$sourceStoreNam2;
247
-
248
- const preferencesStoreName = 'core/preferences';
249
- const interfaceStoreName = 'core/interface';
250
- const state = persistence.get(); // Features most recently (and briefly) lived in the interface package.
251
- // If data exists there, prioritize using that for the migration. If not
252
- // also check the original package as the user may have updated from an
253
- // older block editor version.
254
-
255
- const interfaceFeatures = (_state$interfaceStore = state[interfaceStoreName]) === null || _state$interfaceStore === void 0 ? void 0 : (_state$interfaceStore2 = _state$interfaceStore.preferences) === null || _state$interfaceStore2 === void 0 ? void 0 : (_state$interfaceStore3 = _state$interfaceStore2.features) === null || _state$interfaceStore3 === void 0 ? void 0 : _state$interfaceStore3[sourceStoreName];
256
- const sourceFeatures = (_state$sourceStoreNam = state[sourceStoreName]) === null || _state$sourceStoreNam === void 0 ? void 0 : (_state$sourceStoreNam2 = _state$sourceStoreNam.preferences) === null || _state$sourceStoreNam2 === void 0 ? void 0 : _state$sourceStoreNam2.features;
257
- const featuresToMigrate = interfaceFeatures ? interfaceFeatures : sourceFeatures;
258
-
259
- if (featuresToMigrate) {
260
- var _state$preferencesSto;
261
-
262
- const existingPreferences = (_state$preferencesSto = state[preferencesStoreName]) === null || _state$preferencesSto === void 0 ? void 0 : _state$preferencesSto.preferences; // Avoid migrating features again if they've previously been migrated.
263
-
264
- if (!(existingPreferences !== null && existingPreferences !== void 0 && existingPreferences[sourceStoreName])) {
265
- // Set the feature values in the interface store, the features
266
- // object is keyed by 'scope', which matches the store name for
267
- // the source.
268
- persistence.set(preferencesStoreName, {
269
- preferences: { ...existingPreferences,
270
- [sourceStoreName]: featuresToMigrate
271
- }
272
- }); // Remove migrated feature preferences from `interface`.
273
-
274
- if (interfaceFeatures) {
275
- var _state$interfaceStore4, _state$interfaceStore5;
276
-
277
- const otherInterfaceState = state[interfaceStoreName];
278
- const otherInterfaceScopes = (_state$interfaceStore4 = state[interfaceStoreName]) === null || _state$interfaceStore4 === void 0 ? void 0 : (_state$interfaceStore5 = _state$interfaceStore4.preferences) === null || _state$interfaceStore5 === void 0 ? void 0 : _state$interfaceStore5.features;
279
- persistence.set(interfaceStoreName, { ...otherInterfaceState,
280
- preferences: {
281
- features: { ...otherInterfaceScopes,
282
- [sourceStoreName]: undefined
283
- }
284
- }
285
- });
286
- } // Remove migrated feature preferences from the source.
287
-
288
-
289
- if (sourceFeatures) {
290
- var _state$sourceStoreNam3;
291
-
292
- const otherSourceState = state[sourceStoreName];
293
- const sourcePreferences = (_state$sourceStoreNam3 = state[sourceStoreName]) === null || _state$sourceStoreNam3 === void 0 ? void 0 : _state$sourceStoreNam3.preferences;
294
- persistence.set(sourceStoreName, { ...otherSourceState,
295
- preferences: { ...sourcePreferences,
296
- features: undefined
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
-
314
-
315
- function migrateIndividualPreferenceToPreferencesStore(persistence, _ref, key) {
316
- var _state$sourceStoreNam4, _state$sourceStoreNam5, _state$preferencesSto2, _state$preferencesSto3, _state$preferencesSto4, _state$preferencesSto5, _state$preferencesSto6, _state$preferencesSto7, _state$sourceStoreNam6;
317
-
318
- let {
319
- from: sourceStoreName,
320
- scope
321
- } = _ref;
322
- let convert = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _lodash.identity;
323
- const preferencesStoreName = 'core/preferences';
324
- const state = persistence.get();
325
- const sourcePreference = (_state$sourceStoreNam4 = state[sourceStoreName]) === null || _state$sourceStoreNam4 === void 0 ? void 0 : (_state$sourceStoreNam5 = _state$sourceStoreNam4.preferences) === null || _state$sourceStoreNam5 === void 0 ? void 0 : _state$sourceStoreNam5[key]; // There's nothing to migrate, exit early.
326
-
327
- if (sourcePreference === undefined) {
328
- return;
329
- }
330
-
331
- const targetPreference = (_state$preferencesSto2 = state[preferencesStoreName]) === null || _state$preferencesSto2 === void 0 ? void 0 : (_state$preferencesSto3 = _state$preferencesSto2.preferences) === null || _state$preferencesSto3 === void 0 ? void 0 : (_state$preferencesSto4 = _state$preferencesSto3[scope]) === null || _state$preferencesSto4 === void 0 ? void 0 : _state$preferencesSto4[key]; // There's existing data at the target, so don't overwrite it, exit early.
332
-
333
- if (targetPreference) {
334
- return;
335
- }
336
-
337
- const otherScopes = (_state$preferencesSto5 = state[preferencesStoreName]) === null || _state$preferencesSto5 === void 0 ? void 0 : _state$preferencesSto5.preferences;
338
- const otherPreferences = (_state$preferencesSto6 = state[preferencesStoreName]) === null || _state$preferencesSto6 === void 0 ? void 0 : (_state$preferencesSto7 = _state$preferencesSto6.preferences) === null || _state$preferencesSto7 === void 0 ? void 0 : _state$preferencesSto7[scope]; // Pass an object with the key and value as this allows the convert
339
- // function to convert to a data structure that has different keys.
340
-
341
- const convertedPreferences = convert({
342
- [key]: sourcePreference
343
- });
344
- persistence.set(preferencesStoreName, {
345
- preferences: { ...otherScopes,
346
- [scope]: { ...otherPreferences,
347
- ...convertedPreferences
348
- }
349
- }
350
- }); // Remove migrated feature preferences from the source.
351
-
352
- const otherSourceState = state[sourceStoreName];
353
- const allSourcePreferences = (_state$sourceStoreNam6 = state[sourceStoreName]) === null || _state$sourceStoreNam6 === void 0 ? void 0 : _state$sourceStoreNam6.preferences;
354
- persistence.set(sourceStoreName, { ...otherSourceState,
355
- preferences: { ...allSourcePreferences,
356
- [key]: undefined
357
- }
358
- });
359
- }
360
- /**
361
- * Convert from:
362
- * ```
363
- * {
364
- * panels: {
365
- * tags: {
366
- * enabled: true,
367
- * opened: true,
368
- * },
369
- * permalinks: {
370
- * enabled: false,
371
- * opened: false,
372
- * },
373
- * },
374
- * }
375
- * ```
376
- *
377
- * to:
378
- * {
379
- * inactivePanels: [
380
- * 'permalinks',
381
- * ],
382
- * openPanels: [
383
- * 'tags',
384
- * ],
385
- * }
386
- *
387
- * @param {Object} preferences A preferences object.
388
- *
389
- * @return {Object} The converted data.
390
- */
391
-
392
-
393
- function convertEditPostPanels(preferences) {
394
- var _preferences$panels;
395
-
396
- const panels = (_preferences$panels = preferences === null || preferences === void 0 ? void 0 : preferences.panels) !== null && _preferences$panels !== void 0 ? _preferences$panels : {};
397
- return Object.keys(panels).reduce((convertedData, panelName) => {
398
- const panel = panels[panelName];
399
-
400
- if ((panel === null || panel === void 0 ? void 0 : panel.enabled) === false) {
401
- convertedData.inactivePanels.push(panelName);
402
- }
403
228
 
404
- if ((panel === null || panel === void 0 ? void 0 : panel.opened) === true) {
405
- convertedData.openPanels.push(panelName);
406
- }
407
-
408
- return convertedData;
409
- }, {
410
- inactivePanels: [],
411
- openPanels: []
412
- });
413
- }
414
-
415
- function migrateThirdPartyFeaturePreferencesToPreferencesStore(persistence) {
416
- var _state$interfaceStore6, _state$interfaceStore7;
417
-
418
- const interfaceStoreName = 'core/interface';
419
- const preferencesStoreName = 'core/preferences';
420
- let state = persistence.get();
421
- const interfaceScopes = (_state$interfaceStore6 = state[interfaceStoreName]) === null || _state$interfaceStore6 === void 0 ? void 0 : (_state$interfaceStore7 = _state$interfaceStore6.preferences) === null || _state$interfaceStore7 === void 0 ? void 0 : _state$interfaceStore7.features;
422
-
423
- for (const scope in interfaceScopes) {
424
- var _state$preferencesSto8, _state$interfaceStore8, _state$interfaceStore9;
425
-
426
- // Don't migrate any core 'scopes'.
427
- if (scope.startsWith('core')) {
428
- continue;
429
- } // Skip this scope if there are no features to migrate.
430
-
431
-
432
- const featuresToMigrate = interfaceScopes[scope];
433
-
434
- if (!featuresToMigrate) {
435
- continue;
436
- }
437
-
438
- const existingPreferences = (_state$preferencesSto8 = state[preferencesStoreName]) === null || _state$preferencesSto8 === void 0 ? void 0 : _state$preferencesSto8.preferences; // Add the data to the preferences store structure.
439
-
440
- persistence.set(preferencesStoreName, {
441
- preferences: { ...existingPreferences,
442
- [scope]: featuresToMigrate
443
- }
444
- }); // Remove the data from the interface store structure.
445
- // Call `persistence.get` again to make sure `state` is up-to-date with
446
- // any changes from the previous iteration of this loop.
447
-
448
- state = persistence.get();
449
- const otherInterfaceState = state[interfaceStoreName];
450
- const otherInterfaceScopes = (_state$interfaceStore8 = state[interfaceStoreName]) === null || _state$interfaceStore8 === void 0 ? void 0 : (_state$interfaceStore9 = _state$interfaceStore8.preferences) === null || _state$interfaceStore9 === void 0 ? void 0 : _state$interfaceStore9.features;
451
- persistence.set(interfaceStoreName, { ...otherInterfaceState,
452
- preferences: {
453
- features: { ...otherInterfaceScopes,
454
- [scope]: undefined
455
- }
456
- }
457
- });
458
- }
459
- }
460
- /**
461
- * Migrates interface 'enableItems' data to the preferences store.
462
- *
463
- * The interface package stores this data in this format:
464
- * ```js
465
- * {
466
- * enableItems: {
467
- * singleEnableItems: {
468
- * complementaryArea: {
469
- * 'core/edit-post': 'edit-post/document',
470
- * 'core/edit-site': 'edit-site/global-styles',
471
- * }
472
- * },
473
- * multipleEnableItems: {
474
- * pinnedItems: {
475
- * 'core/edit-post': {
476
- * 'plugin-1': true,
477
- * },
478
- * 'core/edit-site': {
479
- * 'plugin-2': true,
480
- * },
481
- * },
482
- * }
483
- * }
484
- * }
485
- * ```
486
- * and it should be migrated it to:
487
- * ```js
488
- * {
489
- * 'core/edit-post': {
490
- * complementaryArea: 'edit-post/document',
491
- * pinnedItems: {
492
- * 'plugin-1': true,
493
- * },
494
- * },
495
- * 'core/edit-site': {
496
- * complementaryArea: 'edit-site/global-styles',
497
- * pinnedItems: {
498
- * 'plugin-2': true,
499
- * },
500
- * },
501
- * }
502
- * ```
503
- *
504
- * @param {Object} persistence The persistence interface.
505
- */
506
-
507
-
508
- function migrateInterfaceEnableItemsToPreferencesStore(persistence) {
509
- var _state$interfaceStore10, _state$preferencesSto9, _state$preferencesSto10, _sourceEnableItems$si, _sourceEnableItems$si2, _sourceEnableItems$mu, _sourceEnableItems$mu2;
510
-
511
- const interfaceStoreName = 'core/interface';
512
- const preferencesStoreName = 'core/preferences';
513
- const state = persistence.get();
514
- const sourceEnableItems = (_state$interfaceStore10 = state[interfaceStoreName]) === null || _state$interfaceStore10 === void 0 ? void 0 : _state$interfaceStore10.enableItems; // There's nothing to migrate, exit early.
515
-
516
- if (!sourceEnableItems) {
517
- return;
518
- }
519
-
520
- const allPreferences = (_state$preferencesSto9 = (_state$preferencesSto10 = state[preferencesStoreName]) === null || _state$preferencesSto10 === void 0 ? void 0 : _state$preferencesSto10.preferences) !== null && _state$preferencesSto9 !== void 0 ? _state$preferencesSto9 : {}; // First convert complementaryAreas into the right format.
521
- // Use the existing preferences as the accumulator so that the data is
522
- // merged.
523
-
524
- 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 : {};
525
- const convertedComplementaryAreas = Object.keys(sourceComplementaryAreas).reduce((accumulator, scope) => {
526
- var _accumulator$scope;
527
-
528
- const data = sourceComplementaryAreas[scope]; // Don't overwrite any existing data in the preferences store.
529
-
530
- if ((_accumulator$scope = accumulator[scope]) !== null && _accumulator$scope !== void 0 && _accumulator$scope.complementaryArea) {
531
- return accumulator;
532
- }
533
-
534
- return { ...accumulator,
535
- [scope]: { ...accumulator[scope],
536
- complementaryArea: data
537
- }
538
- };
539
- }, allPreferences); // Next feed the converted complementary areas back into a reducer that
540
- // converts the pinned items, resulting in the fully migrated data.
541
-
542
- 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 : {};
543
- const allConvertedData = Object.keys(sourcePinnedItems).reduce((accumulator, scope) => {
544
- var _accumulator$scope2;
545
-
546
- const data = sourcePinnedItems[scope]; // Don't overwrite any existing data in the preferences store.
547
-
548
- if ((_accumulator$scope2 = accumulator[scope]) !== null && _accumulator$scope2 !== void 0 && _accumulator$scope2.pinnedItems) {
549
- return accumulator;
550
- }
551
-
552
- return { ...accumulator,
553
- [scope]: { ...accumulator[scope],
554
- pinnedItems: data
555
- }
556
- };
557
- }, convertedComplementaryAreas);
558
- persistence.set(preferencesStoreName, {
559
- preferences: allConvertedData
560
- }); // Remove migrated preferences.
561
-
562
- const otherInterfaceItems = state[interfaceStoreName];
563
- persistence.set(interfaceStoreName, { ...otherInterfaceItems,
564
- enableItems: undefined
565
- });
566
- }
567
-
568
- persistencePlugin.__unstableMigrate = pluginOptions => {
569
- const persistence = createPersistenceInterface(pluginOptions); // Boolean feature preferences.
570
-
571
- migrateFeaturePreferencesToPreferencesStore(persistence, 'core/edit-widgets');
572
- migrateFeaturePreferencesToPreferencesStore(persistence, 'core/customize-widgets');
573
- migrateFeaturePreferencesToPreferencesStore(persistence, 'core/edit-post');
574
- migrateFeaturePreferencesToPreferencesStore(persistence, 'core/edit-site');
575
- migrateThirdPartyFeaturePreferencesToPreferencesStore(persistence); // Other ad-hoc preferences.
576
-
577
- migrateIndividualPreferenceToPreferencesStore(persistence, {
578
- from: 'core/edit-post',
579
- scope: 'core/edit-post'
580
- }, 'hiddenBlockTypes');
581
- migrateIndividualPreferenceToPreferencesStore(persistence, {
582
- from: 'core/edit-post',
583
- scope: 'core/edit-post'
584
- }, 'editorMode');
585
- migrateIndividualPreferenceToPreferencesStore(persistence, {
586
- from: 'core/edit-post',
587
- scope: 'core/edit-post'
588
- }, 'preferredStyleVariations');
589
- migrateIndividualPreferenceToPreferencesStore(persistence, {
590
- from: 'core/edit-post',
591
- scope: 'core/edit-post'
592
- }, 'panels', convertEditPostPanels);
593
- migrateIndividualPreferenceToPreferencesStore(persistence, {
594
- from: 'core/editor',
595
- scope: 'core/edit-post'
596
- }, 'isPublishSidebarEnabled');
597
- migrateIndividualPreferenceToPreferencesStore(persistence, {
598
- from: 'core/edit-site',
599
- scope: 'core/edit-site'
600
- }, 'editorMode');
601
- migrateInterfaceEnableItemsToPreferencesStore(persistence);
602
- };
229
+ persistencePlugin.__unstableMigrate = () => {};
603
230
 
604
231
  var _default = persistencePlugin;
605
232
  exports.default = _default;