[ 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  /* wp:polyfill */
 359  /**
 360   * The interface package previously had a public API that could be used by
 361   * plugins to set persisted boolean 'feature' preferences.
 362   *
 363   * While usage was likely non-existent or very small, this function ensures
 364   * those are migrated to the preferences data structure. The interface
 365   * package's APIs have now been deprecated and use the preferences store.
 366   *
 367   * This will convert data that looks like this:
 368   * ```js
 369   * {
 370   *     'core/interface': {
 371   *         preferences: {
 372   *             features: {
 373   *                 'my-plugin': {
 374   *                     myPluginFeature: true
 375   *                 }
 376   *             }
 377   *         }
 378   *     }
 379   * }
 380   * ```
 381   *
 382   * To this:
 383   * ```js
 384   *  * {
 385   *     'core/preferences': {
 386   *         preferences: {
 387   *             'my-plugin': {
 388   *                 myPluginFeature: true
 389   *             }
 390   *         }
 391   *     }
 392   * }
 393   * ```
 394   *
 395   * @param {Object} state The local storage state
 396   *
 397   * @return {Object} The state with third party preferences moved to the
 398   *                  preferences data structure.
 399   */
 400  function moveThirdPartyFeaturePreferencesToPreferences(state) {
 401    const interfaceStoreName = 'core/interface';
 402    const preferencesStoreName = 'core/preferences';
 403    const interfaceScopes = state?.[interfaceStoreName]?.preferences?.features;
 404    const interfaceScopeKeys = interfaceScopes ? Object.keys(interfaceScopes) : [];
 405    if (!interfaceScopeKeys?.length) {
 406      return state;
 407    }
 408    return interfaceScopeKeys.reduce(function (convertedState, scope) {
 409      if (scope.startsWith('core')) {
 410        return convertedState;
 411      }
 412      const featuresToMigrate = interfaceScopes?.[scope];
 413      if (!featuresToMigrate) {
 414        return convertedState;
 415      }
 416      const existingMigratedData = convertedState?.[preferencesStoreName]?.preferences?.[scope];
 417      if (existingMigratedData) {
 418        return convertedState;
 419      }
 420      const otherPreferencesScopes = convertedState?.[preferencesStoreName]?.preferences;
 421      const otherInterfaceState = convertedState?.[interfaceStoreName];
 422      const otherInterfaceScopes = convertedState?.[interfaceStoreName]?.preferences?.features;
 423      return {
 424        ...convertedState,
 425        [preferencesStoreName]: {
 426          preferences: {
 427            ...otherPreferencesScopes,
 428            [scope]: featuresToMigrate
 429          }
 430        },
 431        [interfaceStoreName]: {
 432          ...otherInterfaceState,
 433          preferences: {
 434            features: {
 435              ...otherInterfaceScopes,
 436              [scope]: undefined
 437            }
 438          }
 439        }
 440      };
 441    }, state);
 442  }
 443  
 444  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-individual-preference.js
 445  const identity = arg => arg;
 446  
 447  /**
 448   * Migrates an individual item inside the `preferences` object for a package's store.
 449   *
 450   * Previously, some packages had individual 'preferences' of any data type, and many used
 451   * complex nested data structures. For example:
 452   * ```js
 453   * {
 454   *     'core/edit-post': {
 455   *         preferences: {
 456   *             panels: {
 457   *                 publish: {
 458   *                     opened: true,
 459   *                     enabled: true,
 460   *                 }
 461   *             },
 462   *             // ...other preferences.
 463   *         },
 464   *     },
 465   * }
 466   *
 467   * This function supports moving an individual preference like 'panels' above into the
 468   * preferences package data structure.
 469   *
 470   * It supports moving a preference to a particular scope in the preferences store and
 471   * optionally converting the data using a `convert` function.
 472   *
 473   * ```
 474   *
 475   * @param {Object}    state        The original state.
 476   * @param {Object}    migrate      An options object that contains details of the migration.
 477   * @param {string}    migrate.from The name of the store to migrate from.
 478   * @param {string}    migrate.to   The scope in the preferences store to migrate to.
 479   * @param {string}    key          The key in the preferences object to migrate.
 480   * @param {?Function} convert      A function that converts preferences from one format to another.
 481   */
 482  function moveIndividualPreferenceToPreferences(state, {
 483    from: sourceStoreName,
 484    to: scope
 485  }, key, convert = identity) {
 486    const preferencesStoreName = 'core/preferences';
 487    const sourcePreference = state?.[sourceStoreName]?.preferences?.[key];
 488  
 489    // There's nothing to migrate, exit early.
 490    if (sourcePreference === undefined) {
 491      return state;
 492    }
 493    const targetPreference = state?.[preferencesStoreName]?.preferences?.[scope]?.[key];
 494  
 495    // There's existing data at the target, so don't overwrite it, exit early.
 496    if (targetPreference) {
 497      return state;
 498    }
 499    const otherScopes = state?.[preferencesStoreName]?.preferences;
 500    const otherPreferences = state?.[preferencesStoreName]?.preferences?.[scope];
 501    const otherSourceState = state?.[sourceStoreName];
 502    const allSourcePreferences = state?.[sourceStoreName]?.preferences;
 503  
 504    // Pass an object with the key and value as this allows the convert
 505    // function to convert to a data structure that has different keys.
 506    const convertedPreferences = convert({
 507      [key]: sourcePreference
 508    });
 509    return {
 510      ...state,
 511      [preferencesStoreName]: {
 512        preferences: {
 513          ...otherScopes,
 514          [scope]: {
 515            ...otherPreferences,
 516            ...convertedPreferences
 517          }
 518        }
 519      },
 520      [sourceStoreName]: {
 521        ...otherSourceState,
 522        preferences: {
 523          ...allSourcePreferences,
 524          [key]: undefined
 525        }
 526      }
 527    };
 528  }
 529  
 530  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.js
 531  /* wp:polyfill */
 532  /**
 533   * Migrates interface 'enableItems' data to the preferences store.
 534   *
 535   * The interface package stores this data in this format:
 536   * ```js
 537   * {
 538   *     enableItems: {
 539   *         singleEnableItems: {
 540   *                complementaryArea: {
 541   *                 'core/edit-post': 'edit-post/document',
 542   *                 'core/edit-site': 'edit-site/global-styles',
 543   *             }
 544   *         },
 545   *         multipleEnableItems: {
 546   *             pinnedItems: {
 547   *                 'core/edit-post': {
 548   *                     'plugin-1': true,
 549   *                 },
 550   *                 'core/edit-site': {
 551   *                     'plugin-2': true,
 552   *                 },
 553   *             },
 554   *         }
 555   *     }
 556   * }
 557   * ```
 558   *
 559   * and it should be converted it to:
 560   * ```js
 561   * {
 562   *     'core/edit-post': {
 563   *         complementaryArea: 'edit-post/document',
 564   *         pinnedItems: {
 565   *             'plugin-1': true,
 566   *         },
 567   *     },
 568   *     'core/edit-site': {
 569   *         complementaryArea: 'edit-site/global-styles',
 570   *         pinnedItems: {
 571   *             'plugin-2': true,
 572   *         },
 573   *     },
 574   * }
 575   * ```
 576   *
 577   * @param {Object} state The local storage state.
 578   */
 579  function moveInterfaceEnableItems(state) {
 580    var _state$preferencesSto, _sourceEnableItems$si, _sourceEnableItems$mu;
 581    const interfaceStoreName = 'core/interface';
 582    const preferencesStoreName = 'core/preferences';
 583    const sourceEnableItems = state?.[interfaceStoreName]?.enableItems;
 584  
 585    // There's nothing to migrate, exit early.
 586    if (!sourceEnableItems) {
 587      return state;
 588    }
 589    const allPreferences = (_state$preferencesSto = state?.[preferencesStoreName]?.preferences) !== null && _state$preferencesSto !== void 0 ? _state$preferencesSto : {};
 590  
 591    // First convert complementaryAreas into the right format.
 592    // Use the existing preferences as the accumulator so that the data is
 593    // merged.
 594    const sourceComplementaryAreas = (_sourceEnableItems$si = sourceEnableItems?.singleEnableItems?.complementaryArea) !== null && _sourceEnableItems$si !== void 0 ? _sourceEnableItems$si : {};
 595    const preferencesWithConvertedComplementaryAreas = Object.keys(sourceComplementaryAreas).reduce((accumulator, scope) => {
 596      const data = sourceComplementaryAreas[scope];
 597  
 598      // Don't overwrite any existing data in the preferences store.
 599      if (accumulator?.[scope]?.complementaryArea) {
 600        return accumulator;
 601      }
 602      return {
 603        ...accumulator,
 604        [scope]: {
 605          ...accumulator[scope],
 606          complementaryArea: data
 607        }
 608      };
 609    }, allPreferences);
 610  
 611    // Next feed the converted complementary areas back into a reducer that
 612    // converts the pinned items, resulting in the fully migrated data.
 613    const sourcePinnedItems = (_sourceEnableItems$mu = sourceEnableItems?.multipleEnableItems?.pinnedItems) !== null && _sourceEnableItems$mu !== void 0 ? _sourceEnableItems$mu : {};
 614    const allConvertedData = Object.keys(sourcePinnedItems).reduce((accumulator, scope) => {
 615      const data = sourcePinnedItems[scope];
 616      // Don't overwrite any existing data in the preferences store.
 617      if (accumulator?.[scope]?.pinnedItems) {
 618        return accumulator;
 619      }
 620      return {
 621        ...accumulator,
 622        [scope]: {
 623          ...accumulator[scope],
 624          pinnedItems: data
 625        }
 626      };
 627    }, preferencesWithConvertedComplementaryAreas);
 628    const otherInterfaceItems = state[interfaceStoreName];
 629    return {
 630      ...state,
 631      [preferencesStoreName]: {
 632        preferences: allConvertedData
 633      },
 634      [interfaceStoreName]: {
 635        ...otherInterfaceItems,
 636        enableItems: undefined
 637      }
 638    };
 639  }
 640  
 641  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.js
 642  /* wp:polyfill */
 643  /**
 644   * Convert the post editor's panels state from:
 645   * ```
 646   * {
 647   *     panels: {
 648   *         tags: {
 649   *             enabled: true,
 650   *             opened: true,
 651   *         },
 652   *         permalinks: {
 653   *             enabled: false,
 654   *             opened: false,
 655   *         },
 656   *     },
 657   * }
 658   * ```
 659   *
 660   * to a new, more concise data structure:
 661   * {
 662   *     inactivePanels: [
 663   *         'permalinks',
 664   *     ],
 665   *     openPanels: [
 666   *         'tags',
 667   *     ],
 668   * }
 669   *
 670   * @param {Object} preferences A preferences object.
 671   *
 672   * @return {Object} The converted data.
 673   */
 674  function convertEditPostPanels(preferences) {
 675    var _preferences$panels;
 676    const panels = (_preferences$panels = preferences?.panels) !== null && _preferences$panels !== void 0 ? _preferences$panels : {};
 677    return Object.keys(panels).reduce((convertedData, panelName) => {
 678      const panel = panels[panelName];
 679      if (panel?.enabled === false) {
 680        convertedData.inactivePanels.push(panelName);
 681      }
 682      if (panel?.opened === true) {
 683        convertedData.openPanels.push(panelName);
 684      }
 685      return convertedData;
 686    }, {
 687      inactivePanels: [],
 688      openPanels: []
 689    });
 690  }
 691  
 692  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/legacy-local-storage-data/index.js
 693  /**
 694   * Internal dependencies
 695   */
 696  
 697  
 698  
 699  
 700  
 701  
 702  /**
 703   * Gets the legacy local storage data for a given user.
 704   *
 705   * @param {string | number} userId The user id.
 706   *
 707   * @return {Object | null} The local storage data.
 708   */
 709  function getLegacyData(userId) {
 710    const key = `WP_DATA_USER_$userId}`;
 711    const unparsedData = window.localStorage.getItem(key);
 712    return JSON.parse(unparsedData);
 713  }
 714  
 715  /**
 716   * Converts data from the old `@wordpress/data` package format.
 717   *
 718   * @param {Object | null | undefined} data The legacy data in its original format.
 719   *
 720   * @return {Object | undefined} The converted data or `undefined` if there was
 721   *                              nothing to convert.
 722   */
 723  function convertLegacyData(data) {
 724    if (!data) {
 725      return;
 726    }
 727  
 728    // Move boolean feature preferences from each editor into the
 729    // preferences store data structure.
 730    data = moveFeaturePreferences(data, 'core/edit-widgets');
 731    data = moveFeaturePreferences(data, 'core/customize-widgets');
 732    data = moveFeaturePreferences(data, 'core/edit-post');
 733    data = moveFeaturePreferences(data, 'core/edit-site');
 734  
 735    // Move third party boolean feature preferences from the interface package
 736    // to the preferences store data structure.
 737    data = moveThirdPartyFeaturePreferencesToPreferences(data);
 738  
 739    // Move and convert the interface store's `enableItems` data into the
 740    // preferences data structure.
 741    data = moveInterfaceEnableItems(data);
 742  
 743    // Move individual ad-hoc preferences from various packages into the
 744    // preferences store data structure.
 745    data = moveIndividualPreferenceToPreferences(data, {
 746      from: 'core/edit-post',
 747      to: 'core/edit-post'
 748    }, 'hiddenBlockTypes');
 749    data = moveIndividualPreferenceToPreferences(data, {
 750      from: 'core/edit-post',
 751      to: 'core/edit-post'
 752    }, 'editorMode');
 753    data = moveIndividualPreferenceToPreferences(data, {
 754      from: 'core/edit-post',
 755      to: 'core/edit-post'
 756    }, 'panels', convertEditPostPanels);
 757    data = moveIndividualPreferenceToPreferences(data, {
 758      from: 'core/editor',
 759      to: 'core'
 760    }, 'isPublishSidebarEnabled');
 761    data = moveIndividualPreferenceToPreferences(data, {
 762      from: 'core/edit-post',
 763      to: 'core'
 764    }, 'isPublishSidebarEnabled');
 765    data = moveIndividualPreferenceToPreferences(data, {
 766      from: 'core/edit-site',
 767      to: 'core/edit-site'
 768    }, 'editorMode');
 769  
 770    // The new system is only concerned with persisting
 771    // 'core/preferences' preferences reducer, so only return that.
 772    return data?.['core/preferences']?.preferences;
 773  }
 774  
 775  /**
 776   * Gets the legacy local storage data for the given user and returns the
 777   * data converted to the new format.
 778   *
 779   * @param {string | number} userId The user id.
 780   *
 781   * @return {Object | undefined} The converted data or undefined if no local
 782   *                              storage data could be found.
 783   */
 784  function convertLegacyLocalStorageData(userId) {
 785    const data = getLegacyData(userId);
 786    return convertLegacyData(data);
 787  }
 788  
 789  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/preferences-package-data/convert-complementary-areas.js
 790  /* wp:polyfill */
 791  function convertComplementaryAreas(state) {
 792    return Object.keys(state).reduce((stateAccumulator, scope) => {
 793      const scopeData = state[scope];
 794  
 795      // If a complementary area is truthy, convert it to the `isComplementaryAreaVisible` boolean.
 796      if (scopeData?.complementaryArea) {
 797        const updatedScopeData = {
 798          ...scopeData
 799        };
 800        delete updatedScopeData.complementaryArea;
 801        updatedScopeData.isComplementaryAreaVisible = true;
 802        stateAccumulator[scope] = updatedScopeData;
 803        return stateAccumulator;
 804      }
 805      return stateAccumulator;
 806    }, state);
 807  }
 808  
 809  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/preferences-package-data/convert-editor-settings.js
 810  /**
 811   * Internal dependencies
 812   */
 813  
 814  function convertEditorSettings(data) {
 815    var _newData$coreEditPo, _newData$coreEditSi;
 816    let newData = data;
 817    const settingsToMoveToCore = ['allowRightClickOverrides', 'distractionFree', 'editorMode', 'fixedToolbar', 'focusMode', 'hiddenBlockTypes', 'inactivePanels', 'keepCaretInsideBlock', 'mostUsedBlocks', 'openPanels', 'showBlockBreadcrumbs', 'showIconLabels', 'showListViewByDefault', 'isPublishSidebarEnabled', 'isComplementaryAreaVisible', 'pinnedItems'];
 818    settingsToMoveToCore.forEach(setting => {
 819      if (data?.['core/edit-post']?.[setting] !== undefined) {
 820        newData = {
 821          ...newData,
 822          core: {
 823            ...newData?.core,
 824            [setting]: data['core/edit-post'][setting]
 825          }
 826        };
 827        delete newData['core/edit-post'][setting];
 828      }
 829      if (data?.['core/edit-site']?.[setting] !== undefined) {
 830        delete newData['core/edit-site'][setting];
 831      }
 832    });
 833    if (Object.keys((_newData$coreEditPo = newData?.['core/edit-post']) !== null && _newData$coreEditPo !== void 0 ? _newData$coreEditPo : {})?.length === 0) {
 834      delete newData['core/edit-post'];
 835    }
 836    if (Object.keys((_newData$coreEditSi = newData?.['core/edit-site']) !== null && _newData$coreEditSi !== void 0 ? _newData$coreEditSi : {})?.length === 0) {
 837      delete newData['core/edit-site'];
 838    }
 839    return newData;
 840  }
 841  
 842  ;// ./node_modules/@wordpress/preferences-persistence/build-module/migrations/preferences-package-data/index.js
 843  /**
 844   * Internal dependencies
 845   */
 846  
 847  
 848  function convertPreferencesPackageData(data) {
 849    let newData = convertComplementaryAreas(data);
 850    newData = convertEditorSettings(newData);
 851    return newData;
 852  }
 853  
 854  ;// ./node_modules/@wordpress/preferences-persistence/build-module/index.js
 855  /**
 856   * Internal dependencies
 857   */
 858  
 859  
 860  
 861  
 862  
 863  /**
 864   * Creates the persistence layer with preloaded data.
 865   *
 866   * It prioritizes any data from the server, but falls back first to localStorage
 867   * restore data, and then to any legacy data.
 868   *
 869   * This function is used internally by WordPress in an inline script, so
 870   * prefixed with `__unstable`.
 871   *
 872   * @param {Object} serverData Preferences data preloaded from the server.
 873   * @param {string} userId     The user id.
 874   *
 875   * @return {Object} The persistence layer initialized with the preloaded data.
 876   */
 877  function __unstableCreatePersistenceLayer(serverData, userId) {
 878    const localStorageRestoreKey = `WP_PREFERENCES_USER_$userId}`;
 879    const localData = JSON.parse(window.localStorage.getItem(localStorageRestoreKey));
 880  
 881    // Date parse returns NaN for invalid input. Coerce anything invalid
 882    // into a conveniently comparable zero.
 883    const serverModified = Date.parse(serverData && serverData._modified) || 0;
 884    const localModified = Date.parse(localData && localData._modified) || 0;
 885    let preloadedData;
 886    if (serverData && serverModified >= localModified) {
 887      preloadedData = convertPreferencesPackageData(serverData);
 888    } else if (localData) {
 889      preloadedData = convertPreferencesPackageData(localData);
 890    } else {
 891      // Check if there is data in the legacy format from the old persistence system.
 892      preloadedData = convertLegacyLocalStorageData(userId);
 893    }
 894    return create({
 895      preloadedData,
 896      localStorageRestoreKey
 897    });
 898  }
 899  
 900  (window.wp = window.wp || {}).preferencesPersistence = __webpack_exports__;
 901  /******/ })()
 902  ;


Generated : Sat Feb 22 08:20:01 2025 Cross-referenced by PHPXref