PluginProbe
Gutenberg / 23.6.0
Gutenberg v23.6.0
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / build / scripts / preferences-persistence / index.js

index.js in Gutenberg 23.6.0, at build/scripts/preferences-persistence/index.js

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