[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/js/dist/ -> preferences-persistence.js (source)

   1  /******/ (() => { // webpackBootstrap
   2  /******/     "use strict";
   3  /******/     // The require scope
   4  /******/     var __webpack_require__ = {};
   5  /******/     
   6  /************************************************************************/
   7  /******/     /* webpack/runtime/compat get default export */
   8  /******/     (() => {
   9  /******/         // getDefaultExport function for compatibility with non-harmony modules
  10  /******/         __webpack_require__.n = (module) => {
  11  /******/             var getter = module && module.__esModule ?
  12  /******/                 () => (module['default']) :
  13  /******/                 () => (module);
  14  /******/             __webpack_require__.d(getter, { a: getter });
  15  /******/             return getter;
  16  /******/         };
  17  /******/     })();
  18  /******/     
  19  /******/     /* webpack/runtime/define property getters */
  20  /******/     (() => {
  21  /******/         // define getter functions for harmony exports
  22  /******/         __webpack_require__.d = (exports, definition) => {
  23  /******/             for(var key in definition) {
  24  /******/                 if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
  25  /******/                     Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
  26  /******/                 }
  27  /******/             }
  28  /******/         };
  29  /******/     })();
  30  /******/     
  31  /******/     /* webpack/runtime/hasOwnProperty shorthand */
  32  /******/     (() => {
  33  /******/         __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
  34  /******/     })();
  35  /******/     
  36  /******/     /* webpack/runtime/make namespace object */
  37  /******/     (() => {
  38  /******/         // define __esModule on exports
  39  /******/         __webpack_require__.r = (exports) => {
  40  /******/             if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  41  /******/                 Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  42  /******/             }
  43  /******/             Object.defineProperty(exports, '__esModule', { value: true });
  44  /******/         };
  45  /******/     })();
  46  /******/     
  47  /************************************************************************/
  48  var __webpack_exports__ = {};
  49  // ESM COMPAT FLAG
  50  __webpack_require__.r(__webpack_exports__);
  51  
  52  // EXPORTS
  53  __webpack_require__.d(__webpack_exports__, {
  54    __unstableCreatePersistenceLayer: () => (/* binding */ __unstableCreatePersistenceLayer),
  55    create: () => (/* reexport */ create)
  56  });
  57  
  58  ;// external ["wp","apiFetch"]
  59  const external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
  60  var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
  61  ;// ./node_modules/@wordpress/preferences-persistence/build-module/create/debounce-async.js
  62  /**
  63   * Performs a leading edge debounce of async functions.
  64   *
  65   * If three functions are throttled at the same time:
  66   * - The first happens immediately.
  67   * - The second is never called.
  68   * - The third happens `delayMS` milliseconds after the first has resolved.
  69   *
  70   * This is distinct from `{ debounce } from @wordpress/compose` in that it
  71   * waits for promise resolution.
  72   *
  73   * @param {Function} func    A function that returns a promise.
  74   * @param {number}   delayMS A delay in milliseconds.
  75   *
  76   * @return {Function} A function that debounce whatever function is passed
  77   *                    to it.
  78   */
  79  function debounceAsync(func, delayMS) {
  80    let timeoutId;
  81    let activePromise;
  82    return async function debounced(...args) {
  83      // This is a leading edge debounce. If there's no promise or timeout
  84      // in progress, call the debounced function immediately.
  85      if (!activePromise && !timeoutId) {
  86        return new Promise((resolve, reject) => {
  87          // Keep a reference to the promise.
  88          activePromise = func(...args).then((...thenArgs) => {
  89            resolve(...thenArgs);
  90          }).catch(error => {
  91            reject(error);
  92          }).finally(() => {
  93            // As soon this promise is complete, clear the way for the
  94            // next one to happen immediately.
  95            activePromise = null;
  96          });
  97        });
  98      }
  99      if (activePromise) {
 100        // Let any active promises finish before queuing the next request.
 101        await activePromise;
 102      }
 103  
 104      // Clear any active timeouts, abandoning any requests that have
 105      // been queued but not been made.
 106      if (timeoutId) {
 107        clearTimeout(timeoutId);
 108        timeoutId = null;
 109      }
 110  
 111      // Trigger any trailing edge calls to the function.
 112      return new Promise((resolve, reject) => {
 113        // Schedule the next request but with a delay.
 114        timeoutId = setTimeout(() => {
 115          activePromise = func(...args).then((...thenArgs) => {
 116            resolve(...thenArgs);
 117          }).catch(error => {
 118            reject(error);
 119          }).finally(() => {
 120            // As soon this promise is complete, clear the way for the
 121            // next one to happen immediately.
 122            activePromise = null;
 123            timeoutId = null;
 124          });
 125        }, delayMS);
 126      });
 127    };
 128  }
 129  
 130  ;// ./node_modules/@wordpress/preferences-persistence/build-module/create/index.js
 131  /**
 132   * WordPress dependencies
 133   */
 134  
 135  
 136  /**
 137   * Internal dependencies
 138   */
 139  
 140  const EMPTY_OBJECT = {};
 141  const localStorage = window.localStorage;
 142  
 143  /**
 144   * Creates a persistence layer that stores data in WordPress user meta via the
 145   * REST API.
 146   *
 147   * @param {Object}  options
 148   * @param {?Object} options.preloadedData          Any persisted preferences data that should be preloaded.
 149   *                                                 When set, the persistence layer will avoid fetching data
 150   *                                                 from the REST API.
 151   * @param {?string} options.localStorageRestoreKey The key to use for restoring the localStorage backup, used
 152   *                                                 when the persistence layer calls `localStorage.getItem` or
 153   *                                                 `localStorage.setItem`.
 154   * @param {?number} options.requestDebounceMS      Debounce requests to the API so that they only occur at
 155   *                                                 minimum every `requestDebounceMS` milliseconds, and don't
 156   *                                                 swamp the server. Defaults to 2500ms.
 157   *
 158   * @return {Object} A persistence layer for WordPress user meta.
 159   */
 160  function create({
 161    preloadedData,
 162    localStorageRestoreKey = 'WP_PREFERENCES_RESTORE_DATA',
 163    requestDebounceMS = 2500
 164  } = {}) {
 165    let cache = preloadedData;
 166    const debouncedApiFetch = debounceAsync((external_wp_apiFetch_default()), requestDebounceMS);
 167    async function get() {
 168      if (cache) {
 169        return cache;
 170      }
 171      const user = await external_wp_apiFetch_default()({
 172        path: '/wp/v2/users/me?context=edit'
 173      });
 174      const serverData = user?.meta?.persisted_preferences;
 175      const localData = JSON.parse(localStorage.getItem(localStorageRestoreKey));
 176  
 177      // Date parse returns NaN for invalid input. Coerce anything invalid
 178      // into a conveniently comparable zero.
 179      const serverTimestamp = Date.parse(serverData?._modified) || 0;
 180      const localTimestamp = Date.parse(localData?._modified) || 0;
 181  
 182      // Prefer server data if it exists and is more recent.
 183      // Otherwise fallback to localStorage data.
 184      if (serverData && serverTimestamp >= localTimestamp) {
 185        cache = serverData;
 186      } else if (localData) {
 187        cache = localData;
 188      } else {
 189        cache = EMPTY_OBJECT;
 190      }
 191      return cache;
 192    }
 193    function set(newData) {
 194      const dataWithTimestamp = {
 195        ...newData,
 196        _modified: new Date().toISOString()
 197      };
 198      cache = dataWithTimestamp;
 199  
 200      // Store data in local storage as a fallback. If for some reason the
 201      // api request does not complete or becomes unavailable, this data
 202      // can be used to restore preferences.
 203      localStorage.setItem(localStorageRestoreKey, JSON.stringify(dataWithTimestamp));
 204  
 205      // The user meta endpoint seems susceptible to errors when consecutive
 206      // requests are made in quick succession. Ensure there's a gap between
 207      // any consecutive requests.
 208      //
 209      // Catch and do nothing with errors from the REST API.
 210      debouncedApiFetch({
 211        path: '/wp/v2/users/me',
 212        method: 'PUT',
 213        // `keepalive` will still send the request in the background,
 214        // even when a browser unload event might interrupt it.
 215        // This should hopefully make things more resilient.
 216        // This does have a size limit of 64kb, but the data is usually
 217        // much less.
 218        keepalive: true,
 219        data: {
 220          meta: {
 221            persisted_preferences: dataWithTimestamp
 222          }
 223        }
 224      }).catch(() => {});
 225    }
 226    return {
 227      get,
 228      set
 229    };
 230  }
 231  
 232  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-feature-preferences.js
 233  /**
 234   * Move the 'features' object in local storage from the sourceStoreName to the
 235   * preferences store data structure.
 236   *
 237   * Previously, editors used a data structure like this for feature preferences:
 238   * ```js
 239   * {
 240   *     'core/edit-post': {
 241   *         preferences: {
 242   *             features; {
 243   *                 topToolbar: true,
 244   *                 // ... other boolean 'feature' preferences
 245   *             },
 246   *         },
 247   *     },
 248   * }
 249   * ```
 250   *
 251   * And for a while these feature preferences lived in the interface package:
 252   * ```js
 253   * {
 254   *     'core/interface': {
 255   *         preferences: {
 256   *             features: {
 257   *                 'core/edit-post': {
 258   *                     topToolbar: true
 259   *                 }
 260   *             }
 261   *         }
 262   *     }
 263   * }
 264   * ```
 265   *
 266   * In the preferences store, 'features' aren't considered special, they're
 267   * merged to the root level of the scope along with other preferences:
 268   * ```js
 269   * {
 270   *     'core/preferences': {
 271   *         preferences: {
 272   *             'core/edit-post': {
 273   *                 topToolbar: true,
 274   *                 // ... any other preferences.
 275   *             }
 276   *         }
 277   *     }
 278   * }
 279   * ```
 280   *
 281   * This function handles moving from either the source store or the interface
 282   * store to the preferences data structure.
 283   *
 284   * @param {Object} state           The state before migration.
 285   * @param {string} sourceStoreName The name of the store that has persisted
 286   *                                 preferences to migrate to the preferences
 287   *                                 package.
 288   * @return {Object} The migrated state
 289   */
 290  function moveFeaturePreferences(state, sourceStoreName) {
 291    const preferencesStoreName = 'core/preferences';
 292    const interfaceStoreName = 'core/interface';
 293  
 294    // Features most recently (and briefly) lived in the interface package.
 295    // If data exists there, prioritize using that for the migration. If not
 296    // also check the original package as the user may have updated from an
 297    // older block editor version.
 298    const interfaceFeatures = state?.[interfaceStoreName]?.preferences?.features?.[sourceStoreName];
 299    const sourceFeatures = state?.[sourceStoreName]?.preferences?.features;
 300    const featuresToMigrate = interfaceFeatures ? interfaceFeatures : sourceFeatures;
 301    if (!featuresToMigrate) {
 302      return state;
 303    }
 304    const existingPreferences = state?.[preferencesStoreName]?.preferences;
 305  
 306    // Avoid migrating features again if they've previously been migrated.
 307    if (existingPreferences?.[sourceStoreName]) {
 308      return state;
 309    }
 310    let updatedInterfaceState;
 311    if (interfaceFeatures) {
 312      const otherInterfaceState = state?.[interfaceStoreName];
 313      const otherInterfaceScopes = state?.[interfaceStoreName]?.preferences?.features;
 314      updatedInterfaceState = {
 315        [interfaceStoreName]: {
 316          ...otherInterfaceState,
 317          preferences: {
 318            features: {
 319              ...otherInterfaceScopes,
 320              [sourceStoreName]: undefined
 321            }
 322          }
 323        }
 324      };
 325    }
 326    let updatedSourceState;
 327    if (sourceFeatures) {
 328      const otherSourceState = state?.[sourceStoreName];
 329      const sourcePreferences = state?.[sourceStoreName]?.preferences;
 330      updatedSourceState = {
 331        [sourceStoreName]: {
 332          ...otherSourceState,
 333          preferences: {
 334            ...sourcePreferences,
 335            features: undefined
 336          }
 337        }
 338      };
 339    }
 340  
 341    // Set the feature values in the interface store, the features
 342    // object is keyed by 'scope', which matches the store name for
 343    // the source.
 344    return {
 345      ...state,
 346      [preferencesStoreName]: {
 347        preferences: {
 348          ...existingPreferences,
 349          [sourceStoreName]: featuresToMigrate
 350        }
 351      },
 352      ...updatedInterfaceState,
 353      ...updatedSourceState
 354    };
 355  }
 356  
 357  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.js
 358  /**
 359   * The interface package previously had a public API that could be used by
 360   * plugins to set persisted boolean 'feature' preferences.
 361   *
 362   * While usage was likely non-existent or very small, this function ensures
 363   * those are migrated to the preferences data structure. The interface
 364   * package's APIs have now been deprecated and use the preferences store.
 365   *
 366   * This will convert data that looks like this:
 367   * ```js
 368   * {
 369   *     'core/interface': {
 370   *         preferences: {
 371   *             features: {
 372   *                 'my-plugin': {
 373   *                     myPluginFeature: true
 374   *                 }
 375   *             }
 376   *         }
 377   *     }
 378   * }
 379   * ```
 380   *
 381   * To this:
 382   * ```js
 383   *  * {
 384   *     'core/preferences': {
 385   *         preferences: {
 386   *             'my-plugin': {
 387   *                 myPluginFeature: true
 388   *             }
 389   *         }
 390   *     }
 391   * }
 392   * ```
 393   *
 394   * @param {Object} state The local storage state
 395   *
 396   * @return {Object} The state with third party preferences moved to the
 397   *                  preferences data structure.
 398   */
 399  function moveThirdPartyFeaturePreferencesToPreferences(state) {
 400    const interfaceStoreName = 'core/interface';
 401    const preferencesStoreName = 'core/preferences';
 402    const interfaceScopes = state?.[interfaceStoreName]?.preferences?.features;
 403    const interfaceScopeKeys = interfaceScopes ? Object.keys(interfaceScopes) : [];
 404    if (!interfaceScopeKeys?.length) {
 405      return state;
 406    }
 407    return interfaceScopeKeys.reduce(function (convertedState, scope) {
 408      if (scope.startsWith('core')) {
 409        return convertedState;
 410      }
 411      const featuresToMigrate = interfaceScopes?.[scope];
 412      if (!featuresToMigrate) {
 413        return convertedState;
 414      }
 415      const existingMigratedData = convertedState?.[preferencesStoreName]?.preferences?.[scope];
 416      if (existingMigratedData) {
 417        return convertedState;
 418      }
 419      const otherPreferencesScopes = convertedState?.[preferencesStoreName]?.preferences;
 420      const otherInterfaceState = convertedState?.[interfaceStoreName];
 421      const otherInterfaceScopes = convertedState?.[interfaceStoreName]?.preferences?.features;
 422      return {
 423        ...convertedState,
 424        [preferencesStoreName]: {
 425          preferences: {
 426            ...otherPreferencesScopes,
 427            [scope]: featuresToMigrate
 428          }
 429        },
 430        [interfaceStoreName]: {
 431          ...otherInterfaceState,
 432          preferences: {
 433            features: {
 434              ...otherInterfaceScopes,
 435              [scope]: undefined
 436            }
 437          }
 438        }
 439      };
 440    }, state);
 441  }
 442  
 443  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-individual-preference.js
 444  const identity = arg => arg;
 445  
 446  /**
 447   * Migrates an individual item inside the `preferences` object for a package's store.
 448   *
 449   * Previously, some packages had individual 'preferences' of any data type, and many used
 450   * complex nested data structures. For example:
 451   * ```js
 452   * {
 453   *     'core/edit-post': {
 454   *         preferences: {
 455   *             panels: {
 456   *                 publish: {
 457   *                     opened: true,
 458   *                     enabled: true,
 459   *                 }
 460   *             },
 461   *             // ...other preferences.
 462   *         },
 463   *     },
 464   * }
 465   *
 466   * This function supports moving an individual preference like 'panels' above into the
 467   * preferences package data structure.
 468   *
 469   * It supports moving a preference to a particular scope in the preferences store and
 470   * optionally converting the data using a `convert` function.
 471   *
 472   * ```
 473   *
 474   * @param {Object}    state        The original state.
 475   * @param {Object}    migrate      An options object that contains details of the migration.
 476   * @param {string}    migrate.from The name of the store to migrate from.
 477   * @param {string}    migrate.to   The scope in the preferences store to migrate to.
 478   * @param {string}    key          The key in the preferences object to migrate.
 479   * @param {?Function} convert      A function that converts preferences from one format to another.
 480   */
 481  function moveIndividualPreferenceToPreferences(state, {
 482    from: sourceStoreName,
 483    to: scope
 484  }, key, convert = identity) {
 485    const preferencesStoreName = 'core/preferences';
 486    const sourcePreference = state?.[sourceStoreName]?.preferences?.[key];
 487  
 488    // There's nothing to migrate, exit early.
 489    if (sourcePreference === undefined) {
 490      return state;
 491    }
 492    const targetPreference = state?.[preferencesStoreName]?.preferences?.[scope]?.[key];
 493  
 494    // There's existing data at the target, so don't overwrite it, exit early.
 495    if (targetPreference) {
 496      return state;
 497    }
 498    const otherScopes = state?.[preferencesStoreName]?.preferences;
 499    const otherPreferences = state?.[preferencesStoreName]?.preferences?.[scope];
 500    const otherSourceState = state?.[sourceStoreName];
 501    const allSourcePreferences = state?.[sourceStoreName]?.preferences;
 502  
 503    // Pass an object with the key and value as this allows the convert
 504    // function to convert to a data structure that has different keys.
 505    const convertedPreferences = convert({
 506      [key]: sourcePreference
 507    });
 508    return {
 509      ...state,
 510      [preferencesStoreName]: {
 511        preferences: {
 512          ...otherScopes,
 513          [scope]: {
 514            ...otherPreferences,
 515            ...convertedPreferences
 516          }
 517        }
 518      },
 519      [sourceStoreName]: {
 520        ...otherSourceState,
 521        preferences: {
 522          ...allSourcePreferences,
 523          [key]: undefined
 524        }
 525      }
 526    };
 527  }
 528  
 529  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.js
 530  /**
 531   * Migrates interface 'enableItems' data to the preferences store.
 532   *
 533   * The interface package stores this data in this format:
 534   * ```js
 535   * {
 536   *     enableItems: {
 537   *         singleEnableItems: {
 538   *                complementaryArea: {
 539   *                 'core/edit-post': 'edit-post/document',
 540   *                 'core/edit-site': 'edit-site/global-styles',
 541   *             }
 542   *         },
 543   *         multipleEnableItems: {
 544   *             pinnedItems: {
 545   *                 'core/edit-post': {
 546   *                     'plugin-1': true,
 547   *                 },
 548   *                 'core/edit-site': {
 549   *                     'plugin-2': true,
 550   *                 },
 551   *             },
 552   *         }
 553   *     }
 554   * }
 555   * ```
 556   *
 557   * and it should be converted it to:
 558   * ```js
 559   * {
 560   *     'core/edit-post': {
 561   *         complementaryArea: 'edit-post/document',
 562   *         pinnedItems: {
 563   *             'plugin-1': true,
 564   *         },
 565   *     },
 566   *     'core/edit-site': {
 567   *         complementaryArea: 'edit-site/global-styles',
 568   *         pinnedItems: {
 569   *             'plugin-2': true,
 570   *         },
 571   *     },
 572   * }
 573   * ```
 574   *
 575   * @param {Object} state The local storage state.
 576   */
 577  function moveInterfaceEnableItems(state) {
 578    var _state$preferencesSto, _sourceEnableItems$si, _sourceEnableItems$mu;
 579    const interfaceStoreName = 'core/interface';
 580    const preferencesStoreName = 'core/preferences';
 581    const sourceEnableItems = state?.[interfaceStoreName]?.enableItems;
 582  
 583    // There's nothing to migrate, exit early.
 584    if (!sourceEnableItems) {
 585      return state;
 586    }
 587    const allPreferences = (_state$preferencesSto = state?.[preferencesStoreName]?.preferences) !== null && _state$preferencesSto !== void 0 ? _state$preferencesSto : {};
 588  
 589    // First convert complementaryAreas into the right format.
 590    // Use the existing preferences as the accumulator so that the data is
 591    // merged.
 592    const sourceComplementaryAreas = (_sourceEnableItems$si = sourceEnableItems?.singleEnableItems?.complementaryArea) !== null && _sourceEnableItems$si !== void 0 ? _sourceEnableItems$si : {};
 593    const preferencesWithConvertedComplementaryAreas = Object.keys(sourceComplementaryAreas).reduce((accumulator, scope) => {
 594      const data = sourceComplementaryAreas[scope];
 595  
 596      // Don't overwrite any existing data in the preferences store.
 597      if (accumulator?.[scope]?.complementaryArea) {
 598        return accumulator;
 599      }
 600      return {
 601        ...accumulator,
 602        [scope]: {
 603          ...accumulator[scope],
 604          complementaryArea: data
 605        }
 606      };
 607    }, allPreferences);
 608  
 609    // Next feed the converted complementary areas back into a reducer that
 610    // converts the pinned items, resulting in the fully migrated data.
 611    const sourcePinnedItems = (_sourceEnableItems$mu = sourceEnableItems?.multipleEnableItems?.pinnedItems) !== null && _sourceEnableItems$mu !== void 0 ? _sourceEnableItems$mu : {};
 612    const allConvertedData = Object.keys(sourcePinnedItems).reduce((accumulator, scope) => {
 613      const data = sourcePinnedItems[scope];
 614      // Don't overwrite any existing data in the preferences store.
 615      if (accumulator?.[scope]?.pinnedItems) {
 616        return accumulator;
 617      }
 618      return {
 619        ...accumulator,
 620        [scope]: {
 621          ...accumulator[scope],
 622          pinnedItems: data
 623        }
 624      };
 625    }, preferencesWithConvertedComplementaryAreas);
 626    const otherInterfaceItems = state[interfaceStoreName];
 627    return {
 628      ...state,
 629      [preferencesStoreName]: {
 630        preferences: allConvertedData
 631      },
 632      [interfaceStoreName]: {
 633        ...otherInterfaceItems,
 634        enableItems: undefined
 635      }
 636    };
 637  }
 638  
 639  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.js
 640  /**
 641   * Convert the post editor's panels state from:
 642   * ```
 643   * {
 644   *     panels: {
 645   *         tags: {
 646   *             enabled: true,
 647   *             opened: true,
 648   *         },
 649   *         permalinks: {
 650   *             enabled: false,
 651   *             opened: false,
 652   *         },
 653   *     },
 654   * }
 655   * ```
 656   *
 657   * to a new, more concise data structure:
 658   * {
 659   *     inactivePanels: [
 660   *         'permalinks',
 661   *     ],
 662   *     openPanels: [
 663   *         'tags',
 664   *     ],
 665   * }
 666   *
 667   * @param {Object} preferences A preferences object.
 668   *
 669   * @return {Object} The converted data.
 670   */
 671  function convertEditPostPanels(preferences) {
 672    var _preferences$panels;
 673    const panels = (_preferences$panels = preferences?.panels) !== null && _preferences$panels !== void 0 ? _preferences$panels : {};
 674    return Object.keys(panels).reduce((convertedData, panelName) => {
 675      const panel = panels[panelName];
 676      if (panel?.enabled === false) {
 677        convertedData.inactivePanels.push(panelName);
 678      }
 679      if (panel?.opened === true) {
 680        convertedData.openPanels.push(panelName);
 681      }
 682      return convertedData;
 683    }, {
 684      inactivePanels: [],
 685      openPanels: []
 686    });
 687  }
 688  
 689  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/index.js
 690  /**
 691   * Internal dependencies
 692   */
 693  
 694  
 695  
 696  
 697  
 698  
 699  /**
 700   * Gets the legacy local storage data for a given user.
 701   *
 702   * @param {string | number} userId The user id.
 703   *
 704   * @return {Object | null} The local storage data.
 705   */
 706  function getLegacyData(userId) {
 707    const key = `WP_DATA_USER_$userId}`;
 708    const unparsedData = window.localStorage.getItem(key);
 709    return JSON.parse(unparsedData);
 710  }
 711  
 712  /**
 713   * Converts data from the old `@wordpress/data` package format.
 714   *
 715   * @param {Object | null | undefined} data The legacy data in its original format.
 716   *
 717   * @return {Object | undefined} The converted data or `undefined` if there was
 718   *                              nothing to convert.
 719   */
 720  function convertLegacyData(data) {
 721    if (!data) {
 722      return;
 723    }
 724  
 725    // Move boolean feature preferences from each editor into the
 726    // preferences store data structure.
 727    data = moveFeaturePreferences(data, 'core/edit-widgets');
 728    data = moveFeaturePreferences(data, 'core/customize-widgets');
 729    data = moveFeaturePreferences(data, 'core/edit-post');
 730    data = moveFeaturePreferences(data, 'core/edit-site');
 731  
 732    // Move third party boolean feature preferences from the interface package
 733    // to the preferences store data structure.
 734    data = moveThirdPartyFeaturePreferencesToPreferences(data);
 735  
 736    // Move and convert the interface store's `enableItems` data into the
 737    // preferences data structure.
 738    data = moveInterfaceEnableItems(data);
 739  
 740    // Move individual ad-hoc preferences from various packages into the
 741    // preferences store data structure.
 742    data = moveIndividualPreferenceToPreferences(data, {
 743      from: 'core/edit-post',
 744      to: 'core/edit-post'
 745    }, 'hiddenBlockTypes');
 746    data = moveIndividualPreferenceToPreferences(data, {
 747      from: 'core/edit-post',
 748      to: 'core/edit-post'
 749    }, 'editorMode');
 750    data = moveIndividualPreferenceToPreferences(data, {
 751      from: 'core/edit-post',
 752      to: 'core/edit-post'
 753    }, 'panels', convertEditPostPanels);
 754    data = moveIndividualPreferenceToPreferences(data, {
 755      from: 'core/editor',
 756      to: 'core'
 757    }, 'isPublishSidebarEnabled');
 758    data = moveIndividualPreferenceToPreferences(data, {
 759      from: 'core/edit-post',
 760      to: 'core'
 761    }, 'isPublishSidebarEnabled');
 762    data = moveIndividualPreferenceToPreferences(data, {
 763      from: 'core/edit-site',
 764      to: 'core/edit-site'
 765    }, 'editorMode');
 766  
 767    // The new system is only concerned with persisting
 768    // 'core/preferences' preferences reducer, so only return that.
 769    return data?.['core/preferences']?.preferences;
 770  }
 771  
 772  /**
 773   * Gets the legacy local storage data for the given user and returns the
 774   * data converted to the new format.
 775   *
 776   * @param {string | number} userId The user id.
 777   *
 778   * @return {Object | undefined} The converted data or undefined if no local
 779   *                              storage data could be found.
 780   */
 781  function convertLegacyLocalStorageData(userId) {
 782    const data = getLegacyData(userId);
 783    return convertLegacyData(data);
 784  }
 785  
 786  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/preferences-package-data/convert-complementary-areas.js
 787  function convertComplementaryAreas(state) {
 788    return Object.keys(state).reduce((stateAccumulator, scope) => {
 789      const scopeData = state[scope];
 790  
 791      // If a complementary area is truthy, convert it to the `isComplementaryAreaVisible` boolean.
 792      if (scopeData?.complementaryArea) {
 793        const updatedScopeData = {
 794          ...scopeData
 795        };
 796        delete updatedScopeData.complementaryArea;
 797        updatedScopeData.isComplementaryAreaVisible = true;
 798        stateAccumulator[scope] = updatedScopeData;
 799        return stateAccumulator;
 800      }
 801      return stateAccumulator;
 802    }, state);
 803  }
 804  
 805  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/preferences-package-data/convert-editor-settings.js
 806  /**
 807   * Internal dependencies
 808   */
 809  
 810  function convertEditorSettings(data) {
 811    var _newData$coreEditPo, _newData$coreEditSi;
 812    let newData = data;
 813    const settingsToMoveToCore = ['allowRightClickOverrides', 'distractionFree', 'editorMode', 'fixedToolbar', 'focusMode', 'hiddenBlockTypes', 'inactivePanels', 'keepCaretInsideBlock', 'mostUsedBlocks', 'openPanels', 'showBlockBreadcrumbs', 'showIconLabels', 'showListViewByDefault', 'isPublishSidebarEnabled', 'isComplementaryAreaVisible', 'pinnedItems'];
 814    settingsToMoveToCore.forEach(setting => {
 815      if (data?.['core/edit-post']?.[setting] !== undefined) {
 816        newData = {
 817          ...newData,
 818          core: {
 819            ...newData?.core,
 820            [setting]: data['core/edit-post'][setting]
 821          }
 822        };
 823        delete newData['core/edit-post'][setting];
 824      }
 825      if (data?.['core/edit-site']?.[setting] !== undefined) {
 826        delete newData['core/edit-site'][setting];
 827      }
 828    });
 829    if (Object.keys((_newData$coreEditPo = newData?.['core/edit-post']) !== null && _newData$coreEditPo !== void 0 ? _newData$coreEditPo : {})?.length === 0) {
 830      delete newData['core/edit-post'];
 831    }
 832    if (Object.keys((_newData$coreEditSi = newData?.['core/edit-site']) !== null && _newData$coreEditSi !== void 0 ? _newData$coreEditSi : {})?.length === 0) {
 833      delete newData['core/edit-site'];
 834    }
 835    return newData;
 836  }
 837  
 838  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/preferences-package-data/index.js
 839  /**
 840   * Internal dependencies
 841   */
 842  
 843  
 844  function convertPreferencesPackageData(data) {
 845    let newData = convertComplementaryAreas(data);
 846    newData = convertEditorSettings(newData);
 847    return newData;
 848  }
 849  
 850  ;// ./node_modules/@wordpress/preferences-persistence/build-module/index.js
 851  /**
 852   * Internal dependencies
 853   */
 854  
 855  
 856  
 857  
 858  
 859  /**
 860   * Creates the persistence layer with preloaded data.
 861   *
 862   * It prioritizes any data from the server, but falls back first to localStorage
 863   * restore data, and then to any legacy data.
 864   *
 865   * This function is used internally by WordPress in an inline script, so
 866   * prefixed with `__unstable`.
 867   *
 868   * @param {Object} serverData Preferences data preloaded from the server.
 869   * @param {string} userId     The user id.
 870   *
 871   * @return {Object} The persistence layer initialized with the preloaded data.
 872   */
 873  function __unstableCreatePersistenceLayer(serverData, userId) {
 874    const localStorageRestoreKey = `WP_PREFERENCES_USER_$userId}`;
 875    const localData = JSON.parse(window.localStorage.getItem(localStorageRestoreKey));
 876  
 877    // Date parse returns NaN for invalid input. Coerce anything invalid
 878    // into a conveniently comparable zero.
 879    const serverModified = Date.parse(serverData && serverData._modified) || 0;
 880    const localModified = Date.parse(localData && localData._modified) || 0;
 881    let preloadedData;
 882    if (serverData && serverModified >= localModified) {
 883      preloadedData = convertPreferencesPackageData(serverData);
 884    } else if (localData) {
 885      preloadedData = convertPreferencesPackageData(localData);
 886    } else {
 887      // Check if there is data in the legacy format from the old persistence system.
 888      preloadedData = convertLegacyLocalStorageData(userId);
 889    }
 890    return create({
 891      preloadedData,
 892      localStorageRestoreKey
 893    });
 894  }
 895  
 896  (window.wp = window.wp || {}).preferencesPersistence = __webpack_exports__;
 897  /******/ })()
 898  ;


Generated : Sat Dec 21 08:20:01 2024 Cross-referenced by PHPXref