[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

   1  (function() {
   2  "use strict";
   3  var wp;
   4  (wp ||= {}).preferencesPersistence = (() => {
   5    var __create = Object.create;
   6    var __defProp = Object.defineProperty;
   7    var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
   8    var __getOwnPropNames = Object.getOwnPropertyNames;
   9    var __getProtoOf = Object.getPrototypeOf;
  10    var __hasOwnProp = Object.prototype.hasOwnProperty;
  11    var __commonJS = (cb, mod) => function __require() {
  12      return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  13    };
  14    var __export = (target, all) => {
  15      for (var name in all)
  16        __defProp(target, name, { get: all[name], enumerable: true });
  17    };
  18    var __copyProps = (to, from, except, desc) => {
  19      if (from && typeof from === "object" || typeof from === "function") {
  20        for (let key of __getOwnPropNames(from))
  21          if (!__hasOwnProp.call(to, key) && key !== except)
  22            __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  23      }
  24      return to;
  25    };
  26    var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  27      // If the importer is in node compatibility mode or this is not an ESM
  28      // file that has been converted to a CommonJS file using a Babel-
  29      // compatible transform (i.e. "__esModule" has not been set), then set
  30      // "default" to the CommonJS "module.exports" for node compatibility.
  31      isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  32      mod
  33    ));
  34    var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  35  
  36    // package-external:@wordpress/api-fetch
  37    var require_api_fetch = __commonJS({
  38      "package-external:@wordpress/api-fetch"(exports, module) {
  39        module.exports = window.wp.apiFetch;
  40      }
  41    });
  42  
  43    // packages/preferences-persistence/build-module/index.mjs
  44    var index_exports = {};
  45    __export(index_exports, {
  46      __unstableCreatePersistenceLayer: () => __unstableCreatePersistenceLayer,
  47      create: () => create
  48    });
  49  
  50    // packages/preferences-persistence/build-module/create/index.mjs
  51    var import_api_fetch = __toESM(require_api_fetch(), 1);
  52  
  53    // packages/preferences-persistence/build-module/create/debounce-async.mjs
  54    function debounceAsync(func, delayMS) {
  55      let timeoutId;
  56      let activePromise;
  57      return async function debounced(...args) {
  58        if (!activePromise && !timeoutId) {
  59          return new Promise((resolve, reject) => {
  60            activePromise = func(...args).then((...thenArgs) => {
  61              resolve(...thenArgs);
  62            }).catch((error) => {
  63              reject(error);
  64            }).finally(() => {
  65              activePromise = null;
  66            });
  67          });
  68        }
  69        if (activePromise) {
  70          await activePromise;
  71        }
  72        if (timeoutId) {
  73          clearTimeout(timeoutId);
  74          timeoutId = null;
  75        }
  76        return new Promise((resolve, reject) => {
  77          timeoutId = setTimeout(() => {
  78            activePromise = func(...args).then((...thenArgs) => {
  79              resolve(...thenArgs);
  80            }).catch((error) => {
  81              reject(error);
  82            }).finally(() => {
  83              activePromise = null;
  84              timeoutId = null;
  85            });
  86          }, delayMS);
  87        });
  88      };
  89    }
  90  
  91    // packages/preferences-persistence/build-module/is-preferences-data.mjs
  92    function isPreferencesData(data) {
  93      return !!data && typeof data === "object" && !Array.isArray(data);
  94    }
  95  
  96    // packages/preferences-persistence/build-module/local-storage.mjs
  97    function readStoredJSON(key) {
  98      try {
  99        const value = window.localStorage.getItem(key);
 100        return value === null ? null : JSON.parse(value);
 101      } catch {
 102        return null;
 103      }
 104    }
 105    function writeStoredJSON(key, value) {
 106      try {
 107        window.localStorage.setItem(key, JSON.stringify(value));
 108      } catch {
 109      }
 110    }
 111  
 112    // packages/preferences-persistence/build-module/migrations/preferences-package-data/convert-complementary-areas.mjs
 113    function convertComplementaryAreas(state) {
 114      return Object.keys(state).reduce(
 115        (stateAccumulator, scope) => {
 116          const scopeData = state[scope];
 117          if (scopeData?.complementaryArea) {
 118            const updatedScopeData = { ...scopeData };
 119            delete updatedScopeData.complementaryArea;
 120            updatedScopeData.isComplementaryAreaVisible = true;
 121            stateAccumulator[scope] = updatedScopeData;
 122            return stateAccumulator;
 123          }
 124          return stateAccumulator;
 125        },
 126        { ...state }
 127      );
 128    }
 129  
 130    // packages/preferences-persistence/build-module/migrations/preferences-package-data/convert-editor-settings.mjs
 131    var copyScope = (scope) => isPreferencesData(scope) ? { ...scope } : void 0;
 132    function convertEditorSettings(data) {
 133      const newData = { ...data };
 134      const editPost = copyScope(data["core/edit-post"]);
 135      const editSite = copyScope(data["core/edit-site"]);
 136      const settingsToMoveToCore = [
 137        "allowRightClickOverrides",
 138        "distractionFree",
 139        "editorMode",
 140        "fixedToolbar",
 141        "focusMode",
 142        "hiddenBlockTypes",
 143        "inactivePanels",
 144        "keepCaretInsideBlock",
 145        "mostUsedBlocks",
 146        "openPanels",
 147        "showBlockBreadcrumbs",
 148        "showIconLabels",
 149        "showListViewByDefault",
 150        "isPublishSidebarEnabled",
 151        "isComplementaryAreaVisible",
 152        "pinnedItems"
 153      ];
 154      settingsToMoveToCore.forEach((setting) => {
 155        if (editPost?.[setting] !== void 0) {
 156          newData.core = {
 157            ...copyScope(newData.core),
 158            [setting]: editPost[setting]
 159          };
 160          delete editPost[setting];
 161        }
 162        if (editSite?.[setting] !== void 0) {
 163          delete editSite[setting];
 164        }
 165      });
 166      if (editPost && Object.keys(editPost).length > 0) {
 167        newData["core/edit-post"] = editPost;
 168      } else {
 169        delete newData["core/edit-post"];
 170      }
 171      if (editSite && Object.keys(editSite).length > 0) {
 172        newData["core/edit-site"] = editSite;
 173      } else {
 174        delete newData["core/edit-site"];
 175      }
 176      return newData;
 177    }
 178  
 179    // packages/preferences-persistence/build-module/migrations/preferences-package-data/index.mjs
 180    function convertPreferencesPackageData(data) {
 181      let newData = convertComplementaryAreas(data);
 182      newData = convertEditorSettings(newData);
 183      return newData;
 184    }
 185  
 186    // packages/preferences-persistence/build-module/get-newest-data.mjs
 187    function pickNewestData(serverData, localStorageRestoreKey) {
 188      const storedData = readStoredJSON(localStorageRestoreKey);
 189      const localData = isPreferencesData(storedData) ? storedData : null;
 190      if (!isPreferencesData(serverData)) {
 191        return localData;
 192      }
 193      const serverModified = Date.parse(serverData._modified ?? "") || 0;
 194      const localModified = Date.parse(localData?._modified ?? "") || 0;
 195      return localData && localModified > serverModified ? localData : serverData;
 196    }
 197    function getNewestData(serverData, localStorageRestoreKey) {
 198      const newestData = pickNewestData(serverData, localStorageRestoreKey);
 199      return newestData ? convertPreferencesPackageData(newestData) : void 0;
 200    }
 201  
 202    // packages/preferences-persistence/build-module/create/index.mjs
 203    function create({
 204      preloadedData,
 205      localStorageRestoreKey = "WP_PREFERENCES_RESTORE_DATA",
 206      requestDebounceMS = 2500
 207    } = {}) {
 208      let cache = isPreferencesData(preloadedData) ? preloadedData : void 0;
 209      const debouncedApiFetch = debounceAsync(import_api_fetch.default, requestDebounceMS);
 210      async function get() {
 211        if (cache) {
 212          return cache;
 213        }
 214        const user = await (0, import_api_fetch.default)({
 215          path: "/wp/v2/users/me?context=edit"
 216        });
 217        cache = getNewestData(
 218          user?.meta?.persisted_preferences,
 219          localStorageRestoreKey
 220        ) ?? {};
 221        return cache;
 222      }
 223      function set(newData) {
 224        const dataWithTimestamp = {
 225          ...newData,
 226          _modified: (/* @__PURE__ */ new Date()).toISOString()
 227        };
 228        cache = dataWithTimestamp;
 229        writeStoredJSON(localStorageRestoreKey, dataWithTimestamp);
 230        debouncedApiFetch({
 231          path: "/wp/v2/users/me",
 232          method: "PUT",
 233          // `keepalive` will still send the request in the background,
 234          // even when a browser unload event might interrupt it.
 235          // This should hopefully make things more resilient.
 236          // This does have a size limit of 64kb, but the data is usually
 237          // much less.
 238          keepalive: true,
 239          data: {
 240            meta: {
 241              persisted_preferences: dataWithTimestamp
 242            }
 243          }
 244        }).catch(() => {
 245        });
 246      }
 247      return {
 248        get,
 249        set
 250      };
 251    }
 252  
 253    // packages/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-feature-preferences.mjs
 254    function moveFeaturePreferences(state, sourceStoreName) {
 255      const preferencesStoreName = "core/preferences";
 256      const interfaceStoreName = "core/interface";
 257      const interfaceFeatures = state?.[interfaceStoreName]?.preferences?.features?.[sourceStoreName];
 258      const sourceFeatures = state?.[sourceStoreName]?.preferences?.features;
 259      const featuresToMigrate = interfaceFeatures ? interfaceFeatures : sourceFeatures;
 260      if (!featuresToMigrate) {
 261        return state;
 262      }
 263      const existingPreferences = state?.[preferencesStoreName]?.preferences;
 264      if (existingPreferences?.[sourceStoreName]) {
 265        return state;
 266      }
 267      let updatedInterfaceState;
 268      if (interfaceFeatures) {
 269        const otherInterfaceState = state?.[interfaceStoreName];
 270        const otherInterfaceScopes = state?.[interfaceStoreName]?.preferences?.features;
 271        updatedInterfaceState = {
 272          [interfaceStoreName]: {
 273            ...otherInterfaceState,
 274            preferences: {
 275              features: {
 276                ...otherInterfaceScopes,
 277                [sourceStoreName]: void 0
 278              }
 279            }
 280          }
 281        };
 282      }
 283      let updatedSourceState;
 284      if (sourceFeatures) {
 285        const otherSourceState = state?.[sourceStoreName];
 286        const sourcePreferences = state?.[sourceStoreName]?.preferences;
 287        updatedSourceState = {
 288          [sourceStoreName]: {
 289            ...otherSourceState,
 290            preferences: {
 291              ...sourcePreferences,
 292              features: void 0
 293            }
 294          }
 295        };
 296      }
 297      return {
 298        ...state,
 299        [preferencesStoreName]: {
 300          preferences: {
 301            ...existingPreferences,
 302            [sourceStoreName]: featuresToMigrate
 303          }
 304        },
 305        ...updatedInterfaceState,
 306        ...updatedSourceState
 307      };
 308    }
 309  
 310    // packages/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-third-party-feature-preferences.mjs
 311    function moveThirdPartyFeaturePreferencesToPreferences(state) {
 312      const interfaceStoreName = "core/interface";
 313      const preferencesStoreName = "core/preferences";
 314      const interfaceScopes = state?.[interfaceStoreName]?.preferences?.features;
 315      const interfaceScopeKeys = interfaceScopes ? Object.keys(interfaceScopes) : [];
 316      if (!interfaceScopeKeys?.length) {
 317        return state;
 318      }
 319      return interfaceScopeKeys.reduce(function(convertedState, scope) {
 320        if (scope.startsWith("core")) {
 321          return convertedState;
 322        }
 323        const featuresToMigrate = interfaceScopes?.[scope];
 324        if (!featuresToMigrate) {
 325          return convertedState;
 326        }
 327        const existingMigratedData = convertedState?.[preferencesStoreName]?.preferences?.[scope];
 328        if (existingMigratedData) {
 329          return convertedState;
 330        }
 331        const otherPreferencesScopes = convertedState?.[preferencesStoreName]?.preferences;
 332        const otherInterfaceState = convertedState?.[interfaceStoreName];
 333        const otherInterfaceScopes = convertedState?.[interfaceStoreName]?.preferences?.features;
 334        return {
 335          ...convertedState,
 336          [preferencesStoreName]: {
 337            preferences: {
 338              ...otherPreferencesScopes,
 339              [scope]: featuresToMigrate
 340            }
 341          },
 342          [interfaceStoreName]: {
 343            ...otherInterfaceState,
 344            preferences: {
 345              features: {
 346                ...otherInterfaceScopes,
 347                [scope]: void 0
 348              }
 349            }
 350          }
 351        };
 352      }, state);
 353    }
 354  
 355    // packages/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-individual-preference.mjs
 356    var identity = (arg) => arg;
 357    function moveIndividualPreferenceToPreferences(state, { from: sourceStoreName, to: scope }, key, convert = identity) {
 358      const preferencesStoreName = "core/preferences";
 359      const sourcePreference = state?.[sourceStoreName]?.preferences?.[key];
 360      if (sourcePreference === void 0) {
 361        return state;
 362      }
 363      const targetPreference = state?.[preferencesStoreName]?.preferences?.[scope]?.[key];
 364      if (targetPreference) {
 365        return state;
 366      }
 367      const otherScopes = state?.[preferencesStoreName]?.preferences;
 368      const otherPreferences = state?.[preferencesStoreName]?.preferences?.[scope];
 369      const otherSourceState = state?.[sourceStoreName];
 370      const allSourcePreferences = state?.[sourceStoreName]?.preferences;
 371      const convertedPreferences = convert({ [key]: sourcePreference });
 372      return {
 373        ...state,
 374        [preferencesStoreName]: {
 375          preferences: {
 376            ...otherScopes,
 377            [scope]: {
 378              ...otherPreferences,
 379              ...convertedPreferences
 380            }
 381          }
 382        },
 383        [sourceStoreName]: {
 384          ...otherSourceState,
 385          preferences: {
 386            ...allSourcePreferences,
 387            [key]: void 0
 388          }
 389        }
 390      };
 391    }
 392  
 393    // packages/preferences-persistence/build-module/migrations/legacy-local-storage-data/move-interface-enable-items.mjs
 394    function moveInterfaceEnableItems(state) {
 395      const interfaceStoreName = "core/interface";
 396      const preferencesStoreName = "core/preferences";
 397      const sourceEnableItems = state?.[interfaceStoreName]?.enableItems;
 398      if (!sourceEnableItems) {
 399        return state;
 400      }
 401      const allPreferences = state?.[preferencesStoreName]?.preferences ?? {};
 402      const sourceComplementaryAreas = sourceEnableItems?.singleEnableItems?.complementaryArea ?? {};
 403      const preferencesWithConvertedComplementaryAreas = Object.keys(
 404        sourceComplementaryAreas
 405      ).reduce((accumulator, scope) => {
 406        const data = sourceComplementaryAreas[scope];
 407        if (accumulator?.[scope]?.complementaryArea) {
 408          return accumulator;
 409        }
 410        return {
 411          ...accumulator,
 412          [scope]: {
 413            ...accumulator[scope],
 414            complementaryArea: data
 415          }
 416        };
 417      }, allPreferences);
 418      const sourcePinnedItems = sourceEnableItems?.multipleEnableItems?.pinnedItems ?? {};
 419      const allConvertedData = Object.keys(sourcePinnedItems).reduce(
 420        (accumulator, scope) => {
 421          const data = sourcePinnedItems[scope];
 422          if (accumulator?.[scope]?.pinnedItems) {
 423            return accumulator;
 424          }
 425          return {
 426            ...accumulator,
 427            [scope]: {
 428              ...accumulator[scope],
 429              pinnedItems: data
 430            }
 431          };
 432        },
 433        preferencesWithConvertedComplementaryAreas
 434      );
 435      const otherInterfaceItems = state[interfaceStoreName];
 436      return {
 437        ...state,
 438        [preferencesStoreName]: {
 439          preferences: allConvertedData
 440        },
 441        [interfaceStoreName]: {
 442          ...otherInterfaceItems,
 443          enableItems: void 0
 444        }
 445      };
 446    }
 447  
 448    // packages/preferences-persistence/build-module/migrations/legacy-local-storage-data/convert-edit-post-panels.mjs
 449    function convertEditPostPanels(preferences) {
 450      const panels = preferences?.panels ?? {};
 451      return Object.keys(panels).reduce(
 452        (convertedData, panelName) => {
 453          const panel = panels[panelName];
 454          if (panel?.enabled === false) {
 455            convertedData.inactivePanels.push(panelName);
 456          }
 457          if (panel?.opened === true) {
 458            convertedData.openPanels.push(panelName);
 459          }
 460          return convertedData;
 461        },
 462        { inactivePanels: [], openPanels: [] }
 463      );
 464    }
 465  
 466    // packages/preferences-persistence/build-module/migrations/legacy-local-storage-data/index.mjs
 467    function getLegacyData(userId) {
 468      return readStoredJSON(`WP_DATA_USER_$userId}`);
 469    }
 470    function convertLegacyData(data) {
 471      if (!data) {
 472        return;
 473      }
 474      data = moveFeaturePreferences(data, "core/edit-widgets");
 475      data = moveFeaturePreferences(data, "core/customize-widgets");
 476      data = moveFeaturePreferences(data, "core/edit-post");
 477      data = moveFeaturePreferences(data, "core/edit-site");
 478      data = moveThirdPartyFeaturePreferencesToPreferences(data);
 479      data = moveInterfaceEnableItems(data);
 480      data = moveIndividualPreferenceToPreferences(
 481        data,
 482        { from: "core/edit-post", to: "core/edit-post" },
 483        "hiddenBlockTypes"
 484      );
 485      data = moveIndividualPreferenceToPreferences(
 486        data,
 487        { from: "core/edit-post", to: "core/edit-post" },
 488        "editorMode"
 489      );
 490      data = moveIndividualPreferenceToPreferences(
 491        data,
 492        { from: "core/edit-post", to: "core/edit-post" },
 493        "panels",
 494        convertEditPostPanels
 495      );
 496      data = moveIndividualPreferenceToPreferences(
 497        data,
 498        { from: "core/editor", to: "core" },
 499        "isPublishSidebarEnabled"
 500      );
 501      data = moveIndividualPreferenceToPreferences(
 502        data,
 503        { from: "core/edit-post", to: "core" },
 504        "isPublishSidebarEnabled"
 505      );
 506      data = moveIndividualPreferenceToPreferences(
 507        data,
 508        { from: "core/edit-site", to: "core/edit-site" },
 509        "editorMode"
 510      );
 511      const preferences = data?.["core/preferences"]?.preferences;
 512      return isPreferencesData(preferences) ? preferences : void 0;
 513    }
 514    function convertLegacyLocalStorageData(userId) {
 515      const data = getLegacyData(userId);
 516      return convertLegacyData(data);
 517    }
 518  
 519    // packages/preferences-persistence/build-module/index.mjs
 520    function __unstableCreatePersistenceLayer(serverData, userId) {
 521      const localStorageRestoreKey = `WP_PREFERENCES_USER_$userId}`;
 522      return create({
 523        /*
 524         * Fall back to data in the legacy format from the old persistence system.
 525         * The server data is already preloaded, so fetching it again is redundant.
 526         */
 527        preloadedData: getNewestData(serverData, localStorageRestoreKey) ?? convertLegacyLocalStorageData(userId) ?? {},
 528        localStorageRestoreKey
 529      });
 530    }
 531    return __toCommonJS(index_exports);
 532  })();
 533  (window.wp ||= {}).preferencesPersistence = wp.preferencesPersistence;
 534  })();


Generated : Tue Nov 3 08:20:36 2026 Cross-referenced by PHPXref