PluginProbe
Gutenberg / 24.1.0
Gutenberg v24.1.0
24.1.0 24.0.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 All 404 releases
← All changes | build/scripts/core-data/index.js +1863 -733 23.3.2 → 24.1.0 View file →
@@ -1,4 +1,5 @@
1 +(function() {
1 2 "use strict";
2 3 var wp;
3 4 (wp ||= {}).coreData = (() => {
4 5 var __create = Object.create;
@@ -108,8 +109,29 @@
108 109 module.exports = window.wp.undoManager;
109 110 }
110 111 });
111 112
113 + // package-external:@wordpress/api-fetch
114 + var require_api_fetch = __commonJS({
115 + "package-external:@wordpress/api-fetch"(exports, module) {
116 + module.exports = window.wp.apiFetch;
117 + }
118 + });
119 +
120 + // package-external:@wordpress/sync
121 + var require_sync = __commonJS({
122 + "package-external:@wordpress/sync"(exports, module) {
123 + module.exports = window.wp.sync;
124 + }
125 + });
126 +
127 + // package-external:@wordpress/private-apis
128 + var require_private_apis = __commonJS({
129 + "package-external:@wordpress/private-apis"(exports, module) {
130 + module.exports = window.wp.privateApis;
131 + }
132 + });
133 +
112 134 // node_modules/equivalent-key-map/equivalent-key-map.js
113 135 var require_equivalent_key_map = __commonJS({
114 136 "node_modules/equivalent-key-map/equivalent-key-map.js"(exports, module) {
115 137 "use strict";
@@ -328,15 +350,8 @@
328 350 module.exports = window.wp.url;
329 351 }
330 352 });
331 353
332 - // package-external:@wordpress/api-fetch
333 - var require_api_fetch = __commonJS({
334 - "package-external:@wordpress/api-fetch"(exports, module) {
335 - module.exports = window.wp.apiFetch;
336 - }
337 - });
338 -
339 354 // package-external:@wordpress/blocks
340 355 var require_blocks = __commonJS({
341 356 "package-external:@wordpress/blocks"(exports, module) {
342 357 module.exports = window.wp.blocks;
@@ -349,15 +364,8 @@
349 364 module.exports = window.wp.i18n;
350 365 }
351 366 });
352 367
353 - // package-external:@wordpress/sync
354 - var require_sync = __commonJS({
355 - "package-external:@wordpress/sync"(exports, module) {
356 - module.exports = window.wp.sync;
357 - }
358 - });
359 -
360 368 // package-external:@wordpress/block-editor
361 369 var require_block_editor = __commonJS({
362 370 "package-external:@wordpress/block-editor"(exports, module) {
363 371 module.exports = window.wp.blockEditor;
@@ -370,15 +378,8 @@
370 378 module.exports = window.wp.richText;
371 379 }
372 380 });
373 381
374 - // package-external:@wordpress/private-apis
375 - var require_private_apis = __commonJS({
376 - "package-external:@wordpress/private-apis"(exports, module) {
377 - module.exports = window.wp.privateApis;
378 - }
379 - });
380 -
381 382 // package-external:@wordpress/deprecated
382 383 var require_deprecated = __commonJS({
383 384 "package-external:@wordpress/deprecated"(exports, module) {
384 385 module.exports = window.wp.deprecated;
@@ -384,8 +385,15 @@
384 385 module.exports = window.wp.deprecated;
385 386 }
386 387 });
387 388
389 + // package-external:@wordpress/notices
390 + var require_notices = __commonJS({
391 + "package-external:@wordpress/notices"(exports, module) {
392 + module.exports = window.wp.notices;
393 + }
394 + });
395 +
388 396 // package-external:@wordpress/html-entities
389 397 var require_html_entities = __commonJS({
390 398 "package-external:@wordpress/html-entities"(exports, module) {
391 399 module.exports = window.wp.htmlEntities;
@@ -412,8 +420,22 @@
412 420 module.exports = window.wp.warning;
413 421 }
414 422 });
415 423
424 + // package-external:@wordpress/primitives
425 + var require_primitives = __commonJS({
426 + "package-external:@wordpress/primitives"(exports, module) {
427 + module.exports = window.wp.primitives;
428 + }
429 + });
430 +
431 + // package-external:@wordpress/components
432 + var require_components = __commonJS({
433 + "package-external:@wordpress/components"(exports, module) {
434 + module.exports = window.wp.components;
435 + }
436 + });
437 +
416 438 // packages/core-data/build-module/index.mjs
417 439 var index_exports = {};
418 440 __export(index_exports, {
419 441 EntityProvider: () => EntityProvider,
@@ -431,18 +453,35 @@
431 453 useEntityRecord: () => useEntityRecord,
432 454 useEntityRecords: () => useEntityRecords,
433 455 useResourcePermissions: () => use_resource_permissions_default
434 456 });
435 - var import_data15 = __toESM(require_data(), 1);
457 + var import_data20 = __toESM(require_data(), 1);
436 458
437 459 // packages/core-data/build-module/reducer.mjs
438 - var import_es64 = __toESM(require_es6(), 1);
460 + var import_es65 = __toESM(require_es6(), 1);
439 461 var import_compose2 = __toESM(require_compose(), 1);
440 462 var import_data7 = __toESM(require_data(), 1);
441 463 var import_undo_manager = __toESM(require_undo_manager(), 1);
442 464
465 + // packages/core-data/build-module/utils/clear-unchanged-edits.mjs
466 + var import_es6 = __toESM(require_es6(), 1);
467 + function clearUnchangedEdits(edits, persistedRecord) {
468 + if (!persistedRecord) {
469 + return edits;
470 + }
471 + return Object.fromEntries(
472 + Object.entries(edits).map(([key, value]) => {
473 + const persisted = persistedRecord[key]?.raw ?? persistedRecord[key];
474 + return [
475 + key,
476 + (0, import_es6.default)(value, persisted) ? void 0 : value
477 + ];
478 + })
479 + );
480 + }
481 +
443 482 // packages/core-data/build-module/utils/conservative-map-item.mjs
444 - var import_es6 = __toESM(require_es6(), 1);
483 + var import_es62 = __toESM(require_es6(), 1);
445 484 function conservativeMapItem(item, nextItem) {
446 485 if (!item) {
447 486 return nextItem;
448 487 }
@@ -448,9 +487,9 @@
448 487 }
449 488 let hasChanges = false;
450 489 const result = {};
451 490 for (const key in nextItem) {
452 - if ((0, import_es6.default)(item[key], nextItem[key])) {
491 + if ((0, import_es62.default)(item[key], nextItem[key])) {
453 492 result[key] = item[key];
454 493 } else {
455 494 hasChanges = true;
456 495 result[key] = nextItem[key];
@@ -477,8 +516,58 @@
477 516 return null;
478 517 }
479 518 var get_normalized_comma_separable_default = getNormalizedCommaSeparable;
480 519
520 + // packages/core-data/build-module/utils/set-nested-value.mjs
521 + function setNestedValue(object, path, value) {
522 + if (!object || typeof object !== "object") {
523 + return object;
524 + }
525 + const normalizedPath = Array.isArray(path) ? path : path.split(".");
526 + normalizedPath.reduce((acc, key, idx) => {
527 + if (acc[key] === void 0) {
528 + if (Number.isInteger(normalizedPath[idx + 1])) {
529 + acc[key] = [];
530 + } else {
531 + acc[key] = {};
532 + }
533 + }
534 + if (idx === normalizedPath.length - 1) {
535 + acc[key] = value;
536 + }
537 + return acc[key];
538 + }, object);
539 + return object;
540 + }
541 +
542 + // packages/core-data/build-module/utils/get-filtered-item.mjs
543 + var filteredItemCache = /* @__PURE__ */ new WeakMap();
544 + function getFilteredItem(item, _fields) {
545 + const fields = get_normalized_comma_separable_default(_fields) ?? [];
546 + const fieldsKey = fields.join(",");
547 + let itemCache = filteredItemCache.get(item);
548 + if (itemCache) {
549 + const filtered = itemCache.get(fieldsKey);
550 + if (filtered !== void 0) {
551 + return filtered;
552 + }
553 + } else if (item !== null && typeof item === "object") {
554 + itemCache = /* @__PURE__ */ new Map();
555 + filteredItemCache.set(item, itemCache);
556 + }
557 + const filteredItem = {};
558 + for (let f = 0; f < fields.length; f++) {
559 + const field = fields[f].split(".");
560 + let value = item;
561 + field.forEach((fieldName) => {
562 + value = value?.[fieldName];
563 + });
564 + setNestedValue(filteredItem, field, value);
565 + }
566 + itemCache?.set(fieldsKey, filteredItem);
567 + return filteredItem;
568 + }
569 +
481 570 // packages/core-data/build-module/utils/if-matching-action.mjs
482 571 var ifMatchingAction = (isMatch) => (reducer) => (state, action) => {
483 572 if (state === void 0 || isMatch(action)) {
484 573 return reducer(state, action);
@@ -516,30 +605,8 @@
516 605 };
517 606 }
518 607 var with_weak_map_cache_default = withWeakMapCache;
519 608
520 - // packages/core-data/build-module/utils/set-nested-value.mjs
521 - function setNestedValue(object, path, value) {
522 - if (!object || typeof object !== "object") {
523 - return object;
524 - }
525 - const normalizedPath = Array.isArray(path) ? path : path.split(".");
526 - normalizedPath.reduce((acc, key, idx) => {
527 - if (acc[key] === void 0) {
528 - if (Number.isInteger(normalizedPath[idx + 1])) {
529 - acc[key] = [];
530 - } else {
531 - acc[key] = {};
532 - }
533 - }
534 - if (idx === normalizedPath.length - 1) {
535 - acc[key] = value;
536 - }
537 - return acc[key];
538 - }, object);
539 - return object;
540 - }
541 -
542 609 // packages/core-data/build-module/utils/get-nested-value.mjs
543 610 function getNestedValue(object, path, defaultValue) {
544 611 if (!object || typeof object !== "object" || typeof path !== "string" && !Array.isArray(path)) {
545 612 return object;
@@ -597,8 +664,112 @@
597 664 );
598 665 return entries.length > 0 ? Object.fromEntries(entries) : void 0;
599 666 }
600 667
668 + // packages/core-data/build-module/utils/save-crdt-doc.mjs
669 + var import_api_fetch = __toESM(require_api_fetch(), 1);
670 +
671 + // packages/core-data/build-module/sync.mjs
672 + var import_sync = __toESM(require_sync(), 1);
673 +
674 + // packages/core-data/build-module/lock-unlock.mjs
675 + var import_private_apis = __toESM(require_private_apis(), 1);
676 + var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
677 + "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
678 + "@wordpress/core-data"
679 + );
680 +
681 + // packages/core-data/build-module/sync.mjs
682 + var {
683 + ConnectionErrorCode,
684 + createSyncManager,
685 + Delta,
686 + CRDT_DOC_META_PERSISTENCE_KEY,
687 + CRDT_RECORD_MAP_KEY,
688 + LOCAL_EDITOR_ORIGIN,
689 + LOCAL_UNDO_IGNORED_ORIGIN,
690 + retrySyncConnection
691 + } = unlock(import_sync.privateApis);
692 + var CRDT_AUTOSAVE_SNAPSHOT_KEY = "crdt_snapshot";
693 + var syncManager;
694 + function getSyncManager() {
695 + if (syncManager) {
696 + return syncManager;
697 + }
698 + if (!globalThis.window?.__experimentalEnableRealTimeCollaboration) {
699 + return void 0;
700 + }
701 + syncManager = createSyncManager();
702 + return syncManager;
703 + }
704 + function hasSyncManager() {
705 + return Boolean(syncManager);
706 + }
707 + function getEntitySnapshot(kind, name, recordId) {
708 + if (!hasSyncManager()) {
709 + return void 0;
710 + }
711 + return getSyncManager()?.getEntitySnapshot(
712 + `${kind}/${name}`,
713 + `${recordId}`
714 + );
715 + }
716 + function entityContainsSnapshot(kind, name, recordId, encodedSnapshot) {
717 + if (!hasSyncManager()) {
718 + return false;
719 + }
720 + return getSyncManager()?.entityContainsSnapshot(
721 + `${kind}/${name}`,
722 + `${recordId}`,
723 + encodedSnapshot
724 + ) ?? false;
725 + }
726 +
727 + // packages/core-data/build-module/utils/save-crdt-doc.mjs
728 + var SYNC_SAVE_API_PATH = "/wp-sync/v1/save";
729 + var saveCRDTDocQueues = /* @__PURE__ */ new Map();
730 + async function serializeAndSaveCRDTDoc(objectType, objectId, room) {
731 + const serializedDoc = await getSyncManager()?.createPersistedCRDTDoc(
732 + objectType,
733 + objectId
734 + );
735 + if (!serializedDoc) {
736 + return;
737 + }
738 + await (0, import_api_fetch.default)({
739 + path: SYNC_SAVE_API_PATH,
740 + method: "POST",
741 + data: {
742 + room,
743 + doc: serializedDoc
744 + }
745 + });
746 + }
747 + async function saveCRDTDoc(objectType, objectId) {
748 + const room = `${objectType}:${objectId}`;
749 + const previousSave = saveCRDTDocQueues.get(room) || Promise.resolve();
750 + const currentSave = previousSave.catch(() => {
751 + }).then(() => serializeAndSaveCRDTDoc(objectType, objectId, room));
752 + saveCRDTDocQueues.set(room, currentSave);
753 + try {
754 + await currentSave;
755 + } finally {
756 + if (saveCRDTDocQueues.get(room) === currentSave) {
757 + saveCRDTDocQueues.delete(room);
758 + }
759 + }
760 + }
761 +
762 + // packages/core-data/build-module/utils/get-pagination-meta.mjs
763 + function getPaginationMeta(headers) {
764 + const totalItems = parseInt(headers.get("X-WP-Total") ?? "");
765 + const totalPages = parseInt(headers.get("X-WP-TotalPages") ?? "");
766 + return {
767 + totalItems: Number.isFinite(totalItems) ? totalItems : null,
768 + totalPages: Number.isFinite(totalPages) ? totalPages : null
769 + };
770 + }
771 +
601 772 // packages/core-data/build-module/queried-data/actions.mjs
602 773 function receiveItems(items2, edits, meta) {
603 774 return {
604 775 type: "RECEIVE_ITEMS",
@@ -853,15 +1024,15 @@
853 1024 return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options));
854 1025 }
855 1026
856 1027 // packages/core-data/build-module/entities.mjs
857 - var import_api_fetch = __toESM(require_api_fetch(), 1);
1028 + var import_api_fetch2 = __toESM(require_api_fetch(), 1);
858 1029 var import_blocks4 = __toESM(require_blocks(), 1);
859 1030 var import_i18n = __toESM(require_i18n(), 1);
860 1031
861 1032 // packages/core-data/build-module/awareness/post-editor-awareness.mjs
862 1033 var import_data4 = __toESM(require_data(), 1);
863 - var import_sync8 = __toESM(require_sync(), 1);
1034 + var import_sync9 = __toESM(require_sync(), 1);
864 1035 var import_block_editor3 = __toESM(require_block_editor(), 1);
865 1036
866 1037 // packages/core-data/build-module/awareness/base-awareness.mjs
867 1038 var import_data = __toESM(require_data(), 1);
@@ -871,9 +1042,9 @@
871 1042 var LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS = 5;
872 1043 var REMOVAL_DELAY_IN_MS = 5e3;
873 1044
874 1045 // packages/core-data/build-module/awareness/typed-awareness.mjs
875 - var import_sync = __toESM(require_sync(), 1);
1046 + var import_sync3 = __toESM(require_sync(), 1);
876 1047
877 1048 // packages/core-data/build-module/awareness/utils.mjs
878 1049 function getBrowserName() {
879 1050 const userAgent = window.navigator.userAgent;
@@ -917,18 +1088,49 @@
917 1088 return Object.entries(collaboratorInfo1).every(([key, value]) => {
918 1089 return value === collaboratorInfo2[key];
919 1090 });
920 1091 }
921 - function generateCollaboratorInfo(currentCollaborator) {
922 - const { avatar_urls, id, name, slug } = currentCollaborator;
1092 + function hasValidAvatarUrls(value) {
1093 + if ("object" !== typeof value || null === value || Array.isArray(value)) {
1094 + return false;
1095 + }
1096 + return ["24", "48", "96"].every(
1097 + (size) => !(size in value) || "string" === typeof value[size]
1098 + );
1099 + }
1100 + function isCollaboratorInfo(value) {
1101 + if ("object" !== typeof value || null === value) {
1102 + return false;
1103 + }
1104 + return "id" in value && "name" in value && "slug" in value && "browserType" in value && "enteredAt" in value && (null === value.id || "number" === typeof value.id && Number.isInteger(value.id) && value.id > 0) && "string" === typeof value.name && "" !== value.name.trim() && "string" === typeof value.slug && (!("avatar_urls" in value) || hasValidAvatarUrls(value.avatar_urls)) && "string" === typeof value.browserType && "number" === typeof value.enteredAt && Number.isFinite(value.enteredAt);
1105 + }
1106 + function generateCollaboratorInfo(currentCollaborator, clientId) {
1107 + const presentationInfo = {
1108 + browserType: getBrowserName(),
1109 + enteredAt: Date.now()
1110 + };
1111 + if ("object" === typeof currentCollaborator && currentCollaborator) {
1112 + const user = currentCollaborator;
1113 + if ("id" in user && "name" in user) {
1114 + const collaboratorInfo = {
1115 + ...presentationInfo,
1116 + ..."avatar_urls" in user && hasValidAvatarUrls(user.avatar_urls) ? { avatar_urls: user.avatar_urls } : {},
1117 + id: user.id,
1118 + name: user.name,
1119 + slug: "slug" in user && "string" === typeof user.slug ? user.slug : ""
1120 + };
1121 + if (isCollaboratorInfo(collaboratorInfo) && null !== collaboratorInfo.id) {
1122 + return collaboratorInfo;
1123 + }
1124 + }
1125 + }
923 1126 return {
924 - avatar_urls,
925 - // eslint-disable-line camelcase
926 - browserType: getBrowserName(),
927 - enteredAt: Date.now(),
928 - id,
929 - name,
930 - slug
1127 + ...presentationInfo,
1128 + id: null,
1129 + // Keep shared awareness data language-neutral. The editor localizes this
1130 + // fallback name for the viewer when it is displayed.
1131 + name: "Anonymous User",
1132 + slug: `anonymous-${clientId}`
931 1133 };
932 1134 }
933 1135 function getRecordValue(obj, key) {
934 1136 if ("object" === typeof obj && null !== obj && key in obj) {
@@ -940,9 +1142,9 @@
940 1142 return Object.keys(obj);
941 1143 }
942 1144
943 1145 // packages/core-data/build-module/awareness/typed-awareness.mjs
944 - var TypedAwareness = class extends import_sync.Awareness {
1146 + var TypedAwareness = class extends import_sync3.Awareness {
945 1147 /**
946 1148 * Get the states from an awareness document.
947 1149 */
948 1150 getStates() {
@@ -1213,11 +1415,17 @@
1213 1415 /**
1214 1416 * Set the current collaborator info in the local state.
1215 1417 */
1216 1418 async setCurrentCollaboratorInfo() {
1217 - const currentUser2 = await (0, import_data.resolveSelect)(STORE_NAME).getCurrentUser();
1218 - const collaboratorInfo = generateCollaboratorInfo(currentUser2);
1219 - this.setLocalStateField("collaboratorInfo", collaboratorInfo);
1419 + let currentUser2;
1420 + try {
1421 + currentUser2 = await (0, import_data.resolveSelect)(STORE_NAME).getCurrentUser();
1422 + } catch {
1423 + }
1424 + this.setLocalStateField(
1425 + "collaboratorInfo",
1426 + generateCollaboratorInfo(currentUser2, this.clientID)
1427 + );
1220 1428 }
1221 1429 };
1222 1430 var baseEqualityFieldChecks = {
1223 1431 collaboratorInfo: areCollaboratorInfosEqual
@@ -1227,18 +1435,18 @@
1227 1435 };
1228 1436
1229 1437 // packages/core-data/build-module/awareness/block-lookup.mjs
1230 1438 var import_data2 = __toESM(require_data(), 1);
1231 - var import_sync2 = __toESM(require_sync(), 1);
1439 + var import_sync4 = __toESM(require_sync(), 1);
1232 1440 var import_block_editor = __toESM(require_block_editor(), 1);
1233 1441 function getContainingBlockYMap(yType) {
1234 1442 let current = yType;
1235 1443 while (current) {
1236 1444 const parent = current.parent;
1237 - if (parent instanceof import_sync2.Y.Map && parent.parent instanceof import_sync2.Y.Array && parent.get("clientId") !== void 0 && parent.get("innerBlocks") instanceof import_sync2.Y.Array) {
1445 + if (parent instanceof import_sync4.Y.Map && parent.parent instanceof import_sync4.Y.Array && parent.get("clientId") !== void 0 && parent.get("innerBlocks") instanceof import_sync4.Y.Array) {
1238 1446 return parent;
1239 1447 }
1240 - current = parent instanceof import_sync2.Y.AbstractType ? parent : null;
1448 + current = parent instanceof import_sync4.Y.AbstractType ? parent : null;
1241 1449 }
1242 1450 return null;
1243 1451 }
1244 1452 function getBlockPathInYdoc(yType) {
@@ -1245,9 +1453,9 @@
1245 1453 const path = [];
1246 1454 let current = yType;
1247 1455 while (current) {
1248 1456 const parentArray = current.parent;
1249 - if (!parentArray || !(parentArray instanceof import_sync2.Y.Array)) {
1457 + if (!parentArray || !(parentArray instanceof import_sync4.Y.Array)) {
1250 1458 return null;
1251 1459 }
1252 1460 let index = -1;
1253 1461 for (let i = 0; i < parentArray.length; i++) {
@@ -1260,9 +1468,9 @@
1260 1468 return null;
1261 1469 }
1262 1470 path.unshift(index);
1263 1471 const grandparent = parentArray.parent;
1264 - if (grandparent instanceof import_sync2.Y.Map && grandparent.get("clientId") !== void 0) {
1472 + if (grandparent instanceof import_sync4.Y.Map && grandparent.get("clientId") !== void 0) {
1265 1473 current = grandparent;
1266 1474 } else {
1267 1475 break;
1268 1476 }
@@ -1268,15 +1476,12 @@
1268 1476 }
1269 1477 }
1270 1478 return path;
1271 1479 }
1272 - function resolveBlockClientIdByPath(path) {
1480 + function resolveBlockClientIdByPath(path, blocks) {
1273 1481 if (path.length === 0) {
1274 1482 return null;
1275 1483 }
1276 - const { getBlocks } = (0, import_data2.select)(import_block_editor.store);
1277 - const postContentBlocks = getPostContentBlocks(getBlocks(), getBlocks);
1278 - let blocks = postContentBlocks;
1279 1484 for (let i = 0; i < path.length; i++) {
1280 1485 const block = blocks[path[i]];
1281 1486 if (!block) {
1282 1487 return null;
@@ -1287,76 +1492,29 @@
1287 1492 blocks = block.innerBlocks;
1288 1493 }
1289 1494 return null;
1290 1495 }
1291 - function getPostContentBlocks(rootBlocks, getBlocks) {
1292 - const postContentBlock = findBlockByName(rootBlocks, "core/post-content");
1293 - if (postContentBlock) {
1294 - return getBlocks(postContentBlock.clientId);
1295 - }
1296 - return rootBlocks;
1496 + function usePostContentBlocks() {
1497 + return (0, import_data2.useSelect)((select5) => {
1498 + const { getBlocksByName, getClientIdsTree } = unlock(
1499 + select5(import_block_editor.store)
1500 + );
1501 + const [postContentClientId] = getBlocksByName("core/post-content");
1502 + return getClientIdsTree(postContentClientId ?? "");
1503 + }, []);
1297 1504 }
1298 - function findBlockByName(blocks, name) {
1299 - for (const block of blocks) {
1300 - if (block.name === name) {
1301 - return block;
1302 - }
1303 - if (block.innerBlocks?.length) {
1304 - const found = findBlockByName(block.innerBlocks, name);
1305 - if (found) {
1306 - return found;
1307 - }
1308 - }
1309 - }
1310 - return null;
1311 - }
1312 1505
1313 1506 // packages/core-data/build-module/utils/crdt-utils.mjs
1314 - var import_sync4 = __toESM(require_sync(), 1);
1507 + var import_sync5 = __toESM(require_sync(), 1);
1315 1508 var import_rich_text = __toESM(require_rich_text(), 1);
1316 -
1317 - // packages/core-data/build-module/sync.mjs
1318 - var import_sync3 = __toESM(require_sync(), 1);
1319 -
1320 - // packages/core-data/build-module/lock-unlock.mjs
1321 - var import_private_apis = __toESM(require_private_apis(), 1);
1322 - var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
1323 - "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
1324 - "@wordpress/core-data"
1325 - );
1326 -
1327 - // packages/core-data/build-module/sync.mjs
1328 - var {
1329 - ConnectionErrorCode,
1330 - createSyncManager,
1331 - Delta,
1332 - CRDT_DOC_META_PERSISTENCE_KEY,
1333 - CRDT_RECORD_MAP_KEY,
1334 - LOCAL_EDITOR_ORIGIN,
1335 - LOCAL_UNDO_IGNORED_ORIGIN,
1336 - retrySyncConnection
1337 - } = unlock(import_sync3.privateApis);
1338 - var syncManager;
1339 - function getSyncManager() {
1340 - if (syncManager) {
1341 - return syncManager;
1342 - }
1343 - syncManager = createSyncManager();
1344 - return syncManager;
1345 - }
1346 - function hasSyncManager() {
1347 - return Boolean(syncManager);
1348 - }
1349 -
1350 - // packages/core-data/build-module/utils/crdt-utils.mjs
1351 1509 function getRootMap(doc, key) {
1352 1510 return doc.getMap(key);
1353 1511 }
1354 1512 function createYMap(partial = {}) {
1355 - return new import_sync4.Y.Map(Object.entries(partial));
1513 + return new import_sync5.Y.Map(Object.entries(partial));
1356 1514 }
1357 1515 function isYMap(value) {
1358 - return value instanceof import_sync4.Y.Map;
1516 + return value instanceof import_sync5.Y.Map;
1359 1517 }
1360 1518 function asRichTextOffset(offset) {
1361 1519 return offset;
1362 1520 }
@@ -1364,16 +1522,16 @@
1364 1522 return index;
1365 1523 }
1366 1524 function getYTextByAttributeKey(attributes, attributeKey) {
1367 1525 const directValue = attributes.get(attributeKey);
1368 - if (directValue instanceof import_sync4.Y.Text) {
1526 + if (directValue instanceof import_sync5.Y.Text) {
1369 1527 return directValue;
1370 1528 }
1371 1529 let value = attributes;
1372 1530 for (const pathPart of attributeKey.split(".")) {
1373 - if (value instanceof import_sync4.Y.Map) {
1531 + if (value instanceof import_sync5.Y.Map) {
1374 1532 value = value.get(pathPart);
1375 - } else if (value instanceof import_sync4.Y.Array) {
1533 + } else if (value instanceof import_sync5.Y.Array) {
1376 1534 const index = Number.parseInt(pathPart, 10);
1377 1535 if (!Number.isSafeInteger(index) || index < 0 || index.toString() !== pathPart) {
1378 1536 return null;
1379 1537 }
@@ -1381,14 +1539,14 @@
1381 1539 } else {
1382 1540 return null;
1383 1541 }
1384 1542 }
1385 - return value instanceof import_sync4.Y.Text ? value : null;
1543 + return value instanceof import_sync5.Y.Text ? value : null;
1386 1544 }
1387 1545 function findBlockByClientIdInDoc(blockId, ydoc) {
1388 1546 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY);
1389 1547 const blocks = ymap.get("blocks");
1390 - if (!(blocks instanceof import_sync4.Y.Array)) {
1548 + if (!(blocks instanceof import_sync5.Y.Array)) {
1391 1549 return null;
1392 1550 }
1393 1551 return findBlockByClientIdInBlocks(blockId, blocks);
1394 1552 }
@@ -1461,9 +1619,9 @@
1461 1619 }
1462 1620
1463 1621 // packages/core-data/build-module/utils/crdt-user-selections.mjs
1464 1622 var import_data3 = __toESM(require_data(), 1);
1465 - var import_sync6 = __toESM(require_sync(), 1);
1623 + var import_sync7 = __toESM(require_sync(), 1);
1466 1624 var import_block_editor2 = __toESM(require_block_editor(), 1);
1467 1625 var SelectionType = /* @__PURE__ */ ((SelectionType2) => {
1468 1626 SelectionType2["None"] = "none";
1469 1627 SelectionType2["Cursor"] = "cursor";
@@ -1511,32 +1669,32 @@
1511 1669 type: "cursor",
1512 1670 cursorPosition
1513 1671 };
1514 1672 } else if (isSelectionInOneBlock) {
1515 - const cursorStartPosition2 = getCursorPosition(
1673 + const cursorStartPosition = getCursorPosition(
1516 1674 selectionStart,
1517 1675 yBlocks
1518 1676 );
1519 - const cursorEndPosition2 = getCursorPosition(selectionEnd, yBlocks);
1520 - if (!cursorStartPosition2 || !cursorEndPosition2) {
1677 + const cursorEndPosition = getCursorPosition(selectionEnd, yBlocks);
1678 + if (!cursorStartPosition || !cursorEndPosition) {
1521 1679 return noSelection;
1522 1680 }
1523 1681 return {
1524 1682 type: "selection-in-one-block",
1525 - cursorStartPosition: cursorStartPosition2,
1526 - cursorEndPosition: cursorEndPosition2,
1683 + cursorStartPosition,
1684 + cursorEndPosition,
1527 1685 selectionDirection
1528 1686 };
1529 1687 }
1530 - const cursorStartPosition = getCursorPosition(selectionStart, yBlocks);
1531 - const cursorEndPosition = getCursorPosition(selectionEnd, yBlocks);
1532 - if (!cursorStartPosition || !cursorEndPosition) {
1688 + const startEndpoint = getSelectionEndpoint(selectionStart, yBlocks);
1689 + const endEndpoint = getSelectionEndpoint(selectionEnd, yBlocks);
1690 + if (!startEndpoint || !endEndpoint) {
1533 1691 return noSelection;
1534 1692 }
1535 1693 return {
1536 1694 type: "selection-in-multiple-blocks",
1537 - cursorStartPosition,
1538 - cursorEndPosition,
1695 + startEndpoint,
1696 + endEndpoint,
1539 1697 selectionDirection
1540 1698 };
1541 1699 }
1542 1700 function getCursorPosition(selection, blocks) {
@@ -1546,12 +1704,12 @@
1546 1704 return null;
1547 1705 }
1548 1706 const attributes = block.get("attributes");
1549 1707 const currentYText = attributes ? getYTextByAttributeKey(attributes, selection.attributeKey) : null;
1550 - if (!(currentYText instanceof import_sync6.Y.Text)) {
1708 + if (!(currentYText instanceof import_sync7.Y.Text)) {
1551 1709 return null;
1552 1710 }
1553 - const relativePosition = import_sync6.Y.createRelativePositionFromTypeIndex(
1711 + const relativePosition = import_sync7.Y.createRelativePositionFromTypeIndex(
1554 1712 currentYText,
1555 1713 richTextOffsetToHtmlIndex(
1556 1714 currentYText.toString(),
1557 1715 asRichTextOffset(selection.offset)
@@ -1562,8 +1720,20 @@
1562 1720 absoluteOffset: selection.offset,
1563 1721 attributeKey: selection.attributeKey
1564 1722 };
1565 1723 }
1724 + function getSelectionEndpoint(selection, blocks) {
1725 + const cursorPosition = getCursorPosition(selection, blocks);
1726 + if (cursorPosition) {
1727 + return { type: "cursor", cursorPosition };
1728 + }
1729 + const path = getBlockPathForLocalClientId(selection.clientId);
1730 + const blockPosition = path ? createRelativePositionForBlockPath(path, blocks) : null;
1731 + if (blockPosition) {
1732 + return { type: "whole-block", blockPosition };
1733 + }
1734 + return null;
1735 + }
1566 1736 function getBlockPathForLocalClientId(clientId) {
1567 1737 const { getBlockIndex, getBlockRootClientId, getBlockName } = (0, import_data3.select)(import_block_editor2.store);
1568 1738 const path = [];
1569 1739 let current = clientId;
@@ -1597,9 +1767,9 @@
1597 1767 }
1598 1768 if (i === path.length - 1) {
1599 1769 return block;
1600 1770 }
1601 - currentBlocks = block.get("innerBlocks") ?? new import_sync6.Y.Array();
1771 + currentBlocks = block.get("innerBlocks") ?? new import_sync7.Y.Array();
1602 1772 }
1603 1773 return null;
1604 1774 }
1605 1775 function createRelativePositionForBlockPath(path, blocks) {
@@ -1608,15 +1778,15 @@
1608 1778 if (path[i] >= currentBlocks.length) {
1609 1779 return null;
1610 1780 }
1611 1781 if (i === path.length - 1) {
1612 - return import_sync6.Y.createRelativePositionFromTypeIndex(
1782 + return import_sync7.Y.createRelativePositionFromTypeIndex(
1613 1783 currentBlocks,
1614 1784 path[i]
1615 1785 );
1616 1786 }
1617 1787 const block = currentBlocks.get(path[i]);
1618 - currentBlocks = block?.get("innerBlocks") ?? new import_sync6.Y.Array();
1788 + currentBlocks = block?.get("innerBlocks") ?? new import_sync7.Y.Array();
1619 1789 }
1620 1790 return null;
1621 1791 }
1622 1792 function areSelectionsStatesEqual(selection1, selection2) {
@@ -1639,17 +1809,17 @@
1639 1809 selection1.cursorEndPosition,
1640 1810 selection2.cursorEndPosition
1641 1811 ) && selection1.selectionDirection === selection2.selectionDirection;
1642 1812 case "selection-in-multiple-blocks":
1643 - return areCursorPositionsEqual(
1644 - selection1.cursorStartPosition,
1645 - selection2.cursorStartPosition
1646 - ) && areCursorPositionsEqual(
1647 - selection1.cursorEndPosition,
1648 - selection2.cursorEndPosition
1813 + return areEndpointsEqual(
1814 + selection1.startEndpoint,
1815 + selection2.startEndpoint
1816 + ) && areEndpointsEqual(
1817 + selection1.endEndpoint,
1818 + selection2.endEndpoint
1649 1819 ) && selection1.selectionDirection === selection2.selectionDirection;
1650 1820 case "whole-block":
1651 - return import_sync6.Y.compareRelativePositions(
1821 + return import_sync7.Y.compareRelativePositions(
1652 1822 selection1.blockPosition,
1653 1823 selection2.blockPosition
1654 1824 );
1655 1825 default:
@@ -1655,10 +1825,25 @@
1655 1825 default:
1656 1826 return false;
1657 1827 }
1658 1828 }
1829 + function areEndpointsEqual(ep1, ep2) {
1830 + if (ep1.type !== ep2.type) {
1831 + return false;
1832 + }
1833 + if (ep1.type === "cursor" && ep2.type === "cursor") {
1834 + return areCursorPositionsEqual(
1835 + ep1.cursorPosition,
1836 + ep2.cursorPosition
1837 + );
1838 + }
1839 + return import_sync7.Y.compareRelativePositions(
1840 + ep1.blockPosition,
1841 + ep2.blockPosition
1842 + );
1843 + }
1659 1844 function areCursorPositionsEqual(cursorPosition1, cursorPosition2) {
1660 - const isRelativePositionEqual = import_sync6.Y.compareRelativePositions(
1845 + const isRelativePositionEqual = import_sync7.Y.compareRelativePositions(
1661 1846 cursorPosition1.relativePosition,
1662 1847 cursorPosition2.relativePosition
1663 1848 );
1664 1849 const isAbsoluteOffsetEqual = cursorPosition1.absoluteOffset === cursorPosition2.absoluteOffset;
@@ -1793,11 +1978,12 @@
1793 1978 * from the Yjs block because the local block-editor store may use different
1794 1979 * clientIds (e.g. in "Show Template" mode where blocks are cloned).
1795 1980 *
1796 1981 * @param selection - The selection state.
1982 + * @param blocks - The tree of block-editor store post content blocks.
1797 1983 * @return The rich-text offset and block client ID, or nulls if not resolvable.
1798 1984 */
1799 - convertSelectionStateToAbsolute(selection) {
1985 + convertSelectionStateToAbsolute(selection, blocks) {
1800 1986 if (selection.type === SelectionType.None) {
1801 1987 return {
1802 1988 richTextOffset: null,
1803 1989 localClientId: null,
@@ -1804,19 +1990,19 @@
1804 1990 attributeKey: null
1805 1991 };
1806 1992 }
1807 1993 if (selection.type === SelectionType.WholeBlock) {
1808 - const absolutePos = import_sync8.Y.createAbsolutePositionFromRelativePosition(
1994 + const absolutePos = import_sync9.Y.createAbsolutePositionFromRelativePosition(
1809 1995 selection.blockPosition,
1810 1996 this.doc
1811 1997 );
1812 1998 let localClientId2 = null;
1813 - if (absolutePos && absolutePos.type instanceof import_sync8.Y.Array) {
1999 + if (absolutePos && absolutePos.type instanceof import_sync9.Y.Array) {
1814 2000 const parentArray = absolutePos.type;
1815 2001 const block = parentArray.get(absolutePos.index);
1816 - if (block instanceof import_sync8.Y.Map) {
2002 + if (block instanceof import_sync9.Y.Map) {
1817 2003 const path2 = getBlockPathInYdoc(block);
1818 - localClientId2 = path2 ? resolveBlockClientIdByPath(path2) : null;
2004 + localClientId2 = path2 ? resolveBlockClientIdByPath(path2, blocks) : null;
1819 2005 }
1820 2006 }
1821 2007 return {
1822 2008 richTextOffset: null,
@@ -1823,10 +2009,17 @@
1823 2009 localClientId: localClientId2,
1824 2010 attributeKey: null
1825 2011 };
1826 2012 }
2013 + if (selection.type === SelectionType.SelectionInMultipleBlocks) {
2014 + return {
2015 + richTextOffset: null,
2016 + localClientId: null,
2017 + attributeKey: null
2018 + };
2019 + }
1827 2020 const cursorPos = "cursorPosition" in selection ? selection.cursorPosition : selection.cursorStartPosition;
1828 - const absolutePosition = import_sync8.Y.createAbsolutePositionFromRelativePosition(
2021 + const absolutePosition = import_sync9.Y.createAbsolutePositionFromRelativePosition(
1829 2022 cursorPos.relativePosition,
1830 2023 this.doc
1831 2024 );
1832 2025 if (!absolutePosition) {
@@ -1837,9 +2030,9 @@
1837 2030 };
1838 2031 }
1839 2032 const yType = getContainingBlockYMap(absolutePosition.type);
1840 2033 const path = yType ? getBlockPathInYdoc(yType) : null;
1841 - const localClientId = path ? resolveBlockClientIdByPath(path) : null;
2034 + const localClientId = path ? resolveBlockClientIdByPath(path, blocks) : null;
1842 2035 return {
1843 2036 richTextOffset: htmlIndexToRichTextOffset(
1844 2037 absolutePosition.type.toString(),
1845 2038 asHtmlStringIndex(absolutePosition.index)
@@ -1869,17 +2062,17 @@
1869 2062 value.toJSON()
1870 2063 ])
1871 2064 );
1872 2065 const collaboratorMapData = new Map(
1873 - Array.from(this.getSeenStates().entries()).map(
1874 - ([clientId, collaboratorState]) => [
1875 - String(clientId),
1876 - {
1877 - name: collaboratorState.collaboratorInfo.name,
1878 - wpUserId: collaboratorState.collaboratorInfo.id
1879 - }
1880 - ]
1881 - )
2066 + Array.from(this.getSeenStates().entries()).filter(
2067 + ([, collaboratorState]) => isCollaboratorInfo(collaboratorState.collaboratorInfo)
2068 + ).map(([clientId, collaboratorState]) => [
2069 + String(clientId),
2070 + {
2071 + name: collaboratorState.collaboratorInfo.name,
2072 + wpUserId: collaboratorState.collaboratorInfo.id
2073 + }
2074 + ])
1882 2075 );
1883 2076 const serializableClientItems = {};
1884 2077 ydoc.store.clients.forEach((structs, clientId) => {
1885 2078 const items2 = structs.filter(this.isYItem);
@@ -1921,11 +2114,11 @@
1921 2114 return a.clientId === b.clientId && a.attributeKey === b.attributeKey && a.offset === b.offset;
1922 2115 }
1923 2116
1924 2117 // packages/core-data/build-module/utils/crdt.mjs
1925 - var import_es63 = __toESM(require_es6(), 1);
2118 + var import_es64 = __toESM(require_es6(), 1);
1926 2119 var import_blocks3 = __toESM(require_blocks(), 1);
1927 - var import_sync13 = __toESM(require_sync(), 1);
2120 + var import_sync14 = __toESM(require_sync(), 1);
1928 2121
1929 2122 // node_modules/uuid/dist/stringify.js
1930 2123 var byteToHex = [];
1931 2124 for (let i = 0; i < 256; ++i) {
@@ -1970,12 +2163,12 @@
1970 2163 }
1971 2164 var v4_default = v4;
1972 2165
1973 2166 // packages/core-data/build-module/utils/crdt-blocks.mjs
1974 - var import_es62 = __toESM(require_es6(), 1);
2167 + var import_es63 = __toESM(require_es6(), 1);
1975 2168 var import_blocks = __toESM(require_blocks(), 1);
1976 2169 var import_rich_text3 = __toESM(require_rich_text(), 1);
1977 - var import_sync9 = __toESM(require_sync(), 1);
2170 + var import_sync10 = __toESM(require_sync(), 1);
1978 2171
1979 2172 // packages/core-data/build-module/utils/crdt-text.mjs
1980 2173 var import_rich_text2 = __toESM(require_rich_text(), 1);
1981 2174 var RICH_TEXT_CACHE_MAX_SIZE = 500;
@@ -2099,9 +2292,9 @@
2099 2292 const overwrites = {
2100 2293 innerBlocks: null,
2101 2294 clientId: null
2102 2295 };
2103 - const res = (0, import_es62.default)(
2296 + const res = (0, import_es63.default)(
2104 2297 Object.assign({}, gblock, overwrites),
2105 2298 Object.assign({}, yblockAsJson, overwrites)
2106 2299 );
2107 2300 const inners = gblock.innerBlocks || [];
@@ -2110,9 +2303,9 @@
2110 2303 (block, i) => areBlocksEqual(block, yinners.get(i))
2111 2304 );
2112 2305 }
2113 2306 function createNewYAttributeMap(blockName, attributes) {
2114 - return new import_sync9.Y.Map(
2307 + return new import_sync10.Y.Map(
2115 2308 Object.entries(attributes).map(
2116 2309 ([attributeName, attributeValue]) => {
2117 2310 return [
2118 2311 attributeName,
@@ -2134,13 +2327,13 @@
2134 2327 if (!schema) {
2135 2328 return value;
2136 2329 }
2137 2330 if (schema.type === "rich-text") {
2138 - return new import_sync9.Y.Text(value?.toString() ?? "");
2331 + return new import_sync10.Y.Text(value?.toString() ?? "");
2139 2332 }
2140 2333 if (schema.type === "array" && schema.query && Array.isArray(value)) {
2141 2334 const query = schema.query;
2142 - const yArray = new import_sync9.Y.Array();
2335 + const yArray = new import_sync10.Y.Array();
2143 2336 yArray.insert(
2144 2337 0,
2145 2338 value.map((item) => createYMapFromQuery(query, item))
2146 2339 );
@@ -2155,9 +2348,9 @@
2155 2348 return !!value && typeof value === "object" && !Array.isArray(value);
2156 2349 }
2157 2350 function createYMapFromQuery(query, obj) {
2158 2351 if (!isRecord(obj)) {
2159 - return new import_sync9.Y.Map();
2352 + return new import_sync10.Y.Map();
2160 2353 }
2161 2354 const entries = Object.entries(obj).map(
2162 2355 ([key, val]) => {
2163 2356 const subSchema = query[key];
@@ -2163,9 +2356,9 @@
2163 2356 const subSchema = query[key];
2164 2357 return [key, createYValueFromSchema(subSchema, val)];
2165 2358 }
2166 2359 );
2167 - return new import_sync9.Y.Map(entries);
2360 + return new import_sync10.Y.Map(entries);
2168 2361 }
2169 2362 function createNewYBlock(block) {
2170 2363 return createYMap(
2171 2364 Object.fromEntries(
@@ -2177,9 +2370,9 @@
2177 2370 createNewYAttributeMap(block.name, value)
2178 2371 ];
2179 2372 }
2180 2373 case "innerBlocks": {
2181 - const innerBlocks = new import_sync9.Y.Array();
2374 + const innerBlocks = new import_sync10.Y.Array();
2182 2375 if (!Array.isArray(value)) {
2183 2376 return [key, innerBlocks];
2184 2377 }
2185 2378 innerBlocks.insert(
@@ -2196,9 +2389,9 @@
2196 2389 })
2197 2390 )
2198 2391 );
2199 2392 }
2200 - function mergeCrdtBlocks(yblocks, incomingBlocks, attributeCursor) {
2393 + function mergeCrdtBlocks(yblocks, incomingBlocks, attributeCursor, options = {}) {
2201 2394 if (!serializableBlocksCache.has(incomingBlocks)) {
2202 2395 serializableBlocksCache.set(
2203 2396 incomingBlocks,
2204 2397 makeBlocksSerializable(incomingBlocks)
@@ -2260,10 +2453,10 @@
2260 2453 incomingYBlock.name,
2261 2454 incomingAttributeName,
2262 2455 currentAttribute
2263 2456 );
2264 - const isYType = currentAttribute instanceof import_sync9.Y.AbstractType;
2265 - const isAttributeChanged = !isExpectedType || isYType || !(0, import_es62.default)(
2457 + const isYType = currentAttribute instanceof import_sync10.Y.AbstractType;
2458 + const isAttributeChanged = !isExpectedType || isYType || !(0, import_es63.default)(
2266 2459 currentAttribute,
2267 2460 incomingAttributeValue
2268 2461 );
2269 2462 if (isAttributeChanged) {
@@ -2292,10 +2485,10 @@
2292 2485 case "innerBlocks": {
2293 2486 let yInnerBlocks = localYBlock.get(
2294 2487 incomingBlockProperty
2295 2488 );
2296 - if (!(yInnerBlocks instanceof import_sync9.Y.Array)) {
2297 - yInnerBlocks = new import_sync9.Y.Array();
2489 + if (!(yInnerBlocks instanceof import_sync10.Y.Array)) {
2490 + yInnerBlocks = new import_sync10.Y.Array();
2298 2491 localYBlock.set(
2299 2492 incomingBlockProperty,
2300 2493 yInnerBlocks
2301 2494 );
@@ -2302,17 +2495,27 @@
2302 2495 }
2303 2496 mergeCrdtBlocks(
2304 2497 yInnerBlocks,
2305 2498 incomingBlockPropertyValue ?? [],
2306 - attributeCursor
2499 + attributeCursor,
2500 + options
2307 2501 );
2308 2502 break;
2309 2503 }
2310 2504 case "clientId": {
2505 + if (options.preserveClientIds) {
2506 + break;
2507 + }
2508 + if (incomingBlockPropertyValue !== localYBlock.get(incomingBlockProperty)) {
2509 + localYBlock.set(
2510 + incomingBlockProperty,
2511 + incomingBlockPropertyValue
2512 + );
2513 + }
2311 2514 break;
2312 2515 }
2313 2516 default:
2314 - if (!(0, import_es62.default)(
2517 + if (!(0, import_es63.default)(
2315 2518 incomingYBlock[incomingBlockProperty],
2316 2519 localYBlock.get(incomingBlockProperty)
2317 2520 )) {
2318 2521 localYBlock.set(
@@ -2348,12 +2551,12 @@
2348 2551 knownClientIds.add(clientId);
2349 2552 }
2350 2553 }
2351 2554 function areArrayElementsEqual(newElement, yElement) {
2352 - if (yElement instanceof import_sync9.Y.Map && isRecord(newElement)) {
2353 - return (0, import_es62.default)(newElement, yElement.toJSON());
2555 + if (yElement instanceof import_sync10.Y.Map && isRecord(newElement)) {
2556 + return (0, import_es63.default)(newElement, yElement.toJSON());
2354 2557 }
2355 - return (0, import_es62.default)(newElement, yElement);
2558 + return (0, import_es63.default)(newElement, yElement);
2356 2559 }
2357 2560 function mergeYArray(yArray, newValue, schema, cursorPosition, cursorScope) {
2358 2561 if (!schema.query) {
2359 2562 return;
@@ -2372,9 +2575,9 @@
2372 2575 const numOfUpdatesNeeded = numOfCommonEntries - left - right;
2373 2576 for (let i = 0; i < numOfUpdatesNeeded; i++) {
2374 2577 const currentElement = yArray.get(left + i);
2375 2578 const newElement = newValue[left + i];
2376 - if (currentElement instanceof import_sync9.Y.Map && isRecord(newElement)) {
2579 + if (currentElement instanceof import_sync10.Y.Map && isRecord(newElement)) {
2377 2580 mergeYMapValues(
2378 2581 currentElement,
2379 2582 newElement,
2380 2583 query,
@@ -2413,17 +2616,17 @@
2413 2616 }
2414 2617 }
2415 2618 function mergeYValue(schema, newVal, yMap, key, cursorPosition, cursorScope) {
2416 2619 const currentVal = yMap.get(key);
2417 - if (schema?.type === "rich-text" && typeof newVal === "string" && currentVal instanceof import_sync9.Y.Text) {
2620 + if (schema?.type === "rich-text" && typeof newVal === "string" && currentVal instanceof import_sync10.Y.Text) {
2418 2621 mergeRichTextUpdate(
2419 2622 currentVal,
2420 2623 newVal,
2421 2624 resolveRichTextCursorPosition(cursorPosition, cursorScope, newVal)
2422 2625 );
2423 - } else if (schema?.type === "array" && schema.query && Array.isArray(newVal) && currentVal instanceof import_sync9.Y.Array) {
2626 + } else if (schema?.type === "array" && schema.query && Array.isArray(newVal) && currentVal instanceof import_sync10.Y.Array) {
2424 2627 mergeYArray(currentVal, newVal, schema, cursorPosition, cursorScope);
2425 - } else if (schema?.type === "object" && schema.query && isRecord(newVal) && currentVal instanceof import_sync9.Y.Map) {
2628 + } else if (schema?.type === "object" && schema.query && isRecord(newVal) && currentVal instanceof import_sync10.Y.Map) {
2426 2629 mergeYMapValues(
2427 2630 currentVal,
2428 2631 newVal,
2429 2632 schema.query,
@@ -2431,9 +2634,9 @@
2431 2634 cursorScope
2432 2635 );
2433 2636 } else {
2434 2637 const newYValue = createYValueFromSchema(schema, newVal);
2435 - if (newYValue !== newVal || !(0, import_es62.default)(currentVal, newVal)) {
2638 + if (newYValue !== newVal || !(0, import_es63.default)(currentVal, newVal)) {
2436 2639 yMap.set(key, newYValue);
2437 2640 }
2438 2641 }
2439 2642 }
@@ -2493,18 +2696,18 @@
2493 2696 }
2494 2697 function isExpectedAttributeType(blockName, attributeName, attributeValue) {
2495 2698 const schema = getBlockAttributeSchema(blockName, attributeName);
2496 2699 if (schema?.type === "rich-text") {
2497 - return attributeValue instanceof import_sync9.Y.Text;
2700 + return attributeValue instanceof import_sync10.Y.Text;
2498 2701 }
2499 2702 if (schema?.type === "string") {
2500 2703 return typeof attributeValue === "string";
2501 2704 }
2502 2705 if (schema?.type === "array" && schema.query) {
2503 - return attributeValue instanceof import_sync9.Y.Array;
2706 + return attributeValue instanceof import_sync10.Y.Array;
2504 2707 }
2505 2708 if (schema?.type === "object" && schema.query) {
2506 - return attributeValue instanceof import_sync9.Y.Map;
2709 + return attributeValue instanceof import_sync10.Y.Map;
2507 2710 }
2508 2711 return true;
2509 2712 }
2510 2713 function isLocalAttribute(blockName, attributeName) {
@@ -2522,9 +2725,9 @@
2522 2725 blockYText.applyDelta(safeDiff.ops);
2523 2726 }
2524 2727 function isDeltaVerificationMatch(blockYText, delta, expectedValue) {
2525 2728 if (!localDoc) {
2526 - localDoc = new import_sync9.Y.Doc();
2729 + localDoc = new import_sync10.Y.Doc();
2527 2730 }
2528 2731 const verificationYText = localDoc.getText("verification-text");
2529 2732 verificationYText.delete(0, verificationYText.length);
2530 2733 verificationYText.insert(0, blockYText.toString());
@@ -2535,12 +2738,12 @@
2535 2738 // packages/core-data/build-module/utils/crdt-selection.mjs
2536 2739 var import_data5 = __toESM(require_data(), 1);
2537 2740 var import_block_editor4 = __toESM(require_block_editor(), 1);
2538 2741 var import_blocks2 = __toESM(require_blocks(), 1);
2539 - var import_sync12 = __toESM(require_sync(), 1);
2742 + var import_sync13 = __toESM(require_sync(), 1);
2540 2743
2541 2744 // packages/core-data/build-module/utils/block-selection-history.mjs
2542 - var import_sync11 = __toESM(require_sync(), 1);
2745 + var import_sync12 = __toESM(require_sync(), 1);
2543 2746 var SELECTION_HISTORY_DEFAULT_SIZE = 5;
2544 2747 var YSelectionType = /* @__PURE__ */ ((YSelectionType2) => {
2545 2748 YSelectionType2["RelativeSelection"] = "RelativeSelection";
2546 2749 YSelectionType2["BlockSelection"] = "BlockSelection";
@@ -2588,9 +2791,9 @@
2588 2791 let changedYText = null;
2589 2792 if (attributeKey && attributes) {
2590 2793 changedYText = getYTextByAttributeKey(attributes, attributeKey);
2591 2794 }
2592 - if (!(changedYText instanceof import_sync11.Y.Text) || !attributeKey || !clientId) {
2795 + if (!(changedYText instanceof import_sync12.Y.Text) || !attributeKey || !clientId) {
2593 2796 return {
2594 2797 type: "BlockSelection",
2595 2798 clientId
2596 2799 };
@@ -2595,9 +2798,9 @@
2595 2798 clientId
2596 2799 };
2597 2800 }
2598 2801 const offset = selection.offset ?? 0;
2599 - const relativePosition = import_sync11.Y.createRelativePositionFromTypeIndex(
2802 + const relativePosition = import_sync12.Y.createRelativePositionFromTypeIndex(
2600 2803 changedYText,
2601 2804 richTextOffsetToHtmlIndex(
2602 2805 changedYText.toString(),
2603 2806 asRichTextOffset(offset)
@@ -2630,9 +2833,9 @@
2630 2833 }
2631 2834 function convertYSelectionToBlockSelection(ySelection, ydoc) {
2632 2835 if (ySelection.type === YSelectionType.RelativeSelection) {
2633 2836 const { relativePosition, attributeKey, clientId } = ySelection;
2634 - const absolutePosition = import_sync12.Y.createAbsolutePositionFromRelativePosition(
2837 + const absolutePosition = import_sync13.Y.createAbsolutePositionFromRelativePosition(
2635 2838 relativePosition,
2636 2839 ydoc
2637 2840 );
2638 2841 if (absolutePosition) {
@@ -2789,10 +2992,10 @@
2789 2992 ymap.set(key, void 0);
2790 2993 break;
2791 2994 }
2792 2995 let currentBlocks = ymap.get(key);
2793 - if (!(currentBlocks instanceof import_sync13.Y.Array)) {
2794 - currentBlocks = new import_sync13.Y.Array();
2996 + if (!(currentBlocks instanceof import_sync14.Y.Array)) {
2997 + currentBlocks = new import_sync14.Y.Array();
2795 2998 ymap.set(key, currentBlocks);
2796 2999 }
2797 3000 mergeCrdtBlocks(currentBlocks, newValue, newCursorPosition);
2798 3001 break;
@@ -2804,12 +3007,12 @@
2804 3007 let rawValue = getRawValue(newValue);
2805 3008 if (key === "title" && !currentValue?.toString() && "Auto Draft" === rawValue) {
2806 3009 rawValue = "";
2807 3010 }
2808 - if (currentValue instanceof import_sync13.Y.Text) {
3011 + if (currentValue instanceof import_sync14.Y.Text) {
2809 3012 mergeRichTextUpdate(currentValue, rawValue ?? "");
2810 3013 } else {
2811 - const newYText = new import_sync13.Y.Text(rawValue ?? "");
3014 + const newYText = new import_sync14.Y.Text(rawValue ?? "");
2812 3015 ymap.set(key, newYText);
2813 3016 }
2814 3017 break;
2815 3018 }
@@ -2860,16 +3063,17 @@
2860 3063 }
2861 3064 }
2862 3065 function mergeContentWithoutBlocks(ymap, rawContent, cursorPosition) {
2863 3066 let currentBlocks = ymap.get("blocks");
2864 - if (!(currentBlocks instanceof import_sync13.Y.Array)) {
2865 - currentBlocks = new import_sync13.Y.Array();
3067 + if (!(currentBlocks instanceof import_sync14.Y.Array)) {
3068 + currentBlocks = new import_sync14.Y.Array();
2866 3069 ymap.set("blocks", currentBlocks);
2867 3070 }
2868 3071 mergeCrdtBlocks(
2869 3072 currentBlocks,
2870 3073 (0, import_blocks3.parse)(rawContent),
2871 - cursorPosition
3074 + cursorPosition,
3075 + { preserveClientIds: true }
2872 3076 );
2873 3077 }
2874 3078 function parseCursorSelection(selection) {
2875 3079 const selectionStart = selection?.selectionStart;
@@ -2878,10 +3082,15 @@
2878 3082 clientId: selectionStart.clientId,
2879 3083 offset: asRichTextOffset(selectionStart.offset)
2880 3084 } : null;
2881 3085 }
2882 - function defaultGetChangesFromCRDTDoc(crdtDoc) {
2883 - return getRootMap(crdtDoc, CRDT_RECORD_MAP_KEY).toJSON();
3086 + function defaultGetChangesFromCRDTDoc(crdtDoc, editedRecord) {
3087 + const docRecord = getRootMap(crdtDoc, CRDT_RECORD_MAP_KEY).toJSON();
3088 + return Object.fromEntries(
3089 + Object.entries(docRecord).filter(
3090 + ([key, newValue]) => haveValuesChanged(editedRecord?.[key], newValue)
3091 + )
3092 + );
2884 3093 }
2885 3094 function getPostChangesFromCRDTDoc(ydoc, editedRecord, syncedProperties) {
2886 3095 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY);
2887 3096 let allowedMetaChanges = {};
@@ -2990,9 +3199,9 @@
2990 3199 }
2991 3200 return void 0;
2992 3201 }
2993 3202 function haveValuesChanged(currentValue, newValue) {
2994 - return !(0, import_es63.default)(currentValue, newValue);
3203 + return !(0, import_es64.default)(currentValue, newValue);
2995 3204 }
2996 3205 function updateMapValue(map, key, currentValue, newValue) {
2997 3206 if (void 0 === newValue) {
2998 3207 map.delete(key);
@@ -3022,15 +3231,17 @@
3022 3231 name: "__unstableBase",
3023 3232 baseURL: "/",
3024 3233 baseURLParams: {
3025 3234 // Please also change the preload path when changing this.
3026 - // @see lib/compat/wordpress-7.0/preload.php
3235 + // @see lib/compat/wordpress-7.1/preload.php
3027 3236 _fields: [
3028 3237 "description",
3029 3238 "gmt_offset",
3030 3239 "home",
3240 + "image_max_bit_depth",
3031 3241 "image_sizes",
3032 3242 "image_size_threshold",
3243 + "image_strip_meta",
3033 3244 "name",
3034 3245 "site_icon",
3035 3246 "site_icon_url",
3036 3247 "site_logo",
@@ -3122,9 +3333,9 @@
3122 3333 baseURLParams: { context: "edit" },
3123 3334 plural: "comments",
3124 3335 label: (0, import_i18n.__)("Comment"),
3125 3336 supportsPagination: true,
3126 - syncConfig: defaultCollectionSyncConfig
3337 + ...globalThis.window?.__experimentalEnableRealTimeCollaboration ? { syncConfig: defaultCollectionSyncConfig } : {}
3127 3338 },
3128 3339 {
3129 3340 name: "menu",
3130 3341 kind: "root",
@@ -3196,16 +3407,8 @@
3196 3407 key: "slug",
3197 3408 supportsPagination: false
3198 3409 },
3199 3410 {
3200 - label: (0, import_i18n.__)("Registered Templates"),
3201 - name: "registeredTemplate",
3202 - kind: "root",
3203 - baseURL: "/wp/v2/registered-templates",
3204 - key: "id",
3205 - supportsPagination: false
3206 - },
3207 - {
3208 3411 label: (0, import_i18n.__)("Font Collections"),
3209 3412 name: "fontCollection",
3210 3413 kind: "root",
3211 3414 baseURL: "/wp/v2/font-collections",
@@ -3222,8 +3425,18 @@
3222 3425 baseURLParams: { context: "view" },
3223 3426 plural: "icons",
3224 3427 key: "name",
3225 3428 supportsPagination: false
3429 + },
3430 + {
3431 + label: (0, import_i18n.__)("Icon Collections"),
3432 + name: "iconCollection",
3433 + kind: "root",
3434 + baseURL: "/wp/v2/icon-collections",
3435 + baseURLParams: { context: "view" },
3436 + plural: "iconCollections",
3437 + key: "slug",
3438 + supportsPagination: false
3226 3439 }
3227 3440 ];
3228 3441 var deprecatedEntities = {
3229 3442 root: {
@@ -3255,9 +3468,9 @@
3255 3468 if ((!edits.title || edits.title === "Auto Draft") && !newEdits.title && (!persistedRecord?.title || persistedRecord?.title === "Auto Draft")) {
3256 3469 newEdits.title = "";
3257 3470 }
3258 3471 }
3259 - if (persistedRecord) {
3472 + if (window.__experimentalEnableRealTimeCollaboration && persistedRecord) {
3260 3473 const objectType = `postType/${name}`;
3261 3474 const objectId = persistedRecord.id;
3262 3475 const serializedDoc = await getSyncManager()?.createPersistedCRDTDoc(
3263 3476 objectType,
@@ -3272,10 +3485,10 @@
3272 3485 }
3273 3486 return newEdits;
3274 3487 };
3275 3488 async function loadPostTypeEntities() {
3276 - const postTypesPromise = (0, import_api_fetch.default)({ path: "/wp/v2/types?context=view" });
3277 - const taxonomiesPromise = window._wpCollaborationEnabled ? (0, import_api_fetch.default)({ path: "/wp/v2/taxonomies?context=view" }) : Promise.resolve({});
3489 + const postTypesPromise = (0, import_api_fetch2.default)({ path: "/wp/v2/types?context=view" });
3490 + const taxonomiesPromise = window.__experimentalEnableRealTimeCollaboration ? (0, import_api_fetch2.default)({ path: "/wp/v2/taxonomies?context=view" }) : Promise.resolve({});
3278 3491 const [postTypes, taxonomies] = await Promise.all([
3279 3492 postTypesPromise,
3280 3493 taxonomiesPromise
3281 3494 ]);
@@ -3316,13 +3529,20 @@
3316 3529 rawAttributes: POST_RAW_ATTRIBUTES,
3317 3530 getTitle: (record) => record?.title?.rendered || record?.title || (isTemplate ? capitalCase(record.slug ?? "") : String(record.id)),
3318 3531 __unstablePrePersist: (persistedRecord, edits) => prePersistPostType(persistedRecord, edits, name, isTemplate),
3319 3532 __unstable_rest_base: postType.rest_base,
3320 - supportsPagination: true,
3533 + // The templates controller returns the whole collection and never
3534 + // paginates.
3535 + supportsPagination: !isTemplate,
3321 3536 getRevisionsUrl: (parentId, revisionId) => `/${namespace}/${postType.rest_base}/${parentId}/revisions${revisionId ? "/" + revisionId : ""}`,
3322 - revisionKey: isTemplate && !window?.__experimentalTemplateActivate ? "wp_id" : DEFAULT_ENTITY_KEY
3537 + revisionKey: isTemplate ? "wp_id" : DEFAULT_ENTITY_KEY
3323 3538 };
3539 + if (!window.__experimentalEnableRealTimeCollaboration) {
3540 + return entity2;
3541 + }
3324 3542 entity2.syncConfig = {
3543 + // Save a CRDT document with this entity
3544 + supportsPersistence: true,
3325 3545 /**
3326 3546 * Apply changes from the local editor to the local CRDT document so
3327 3547 * that those changes can be synced to other peers (via the provider).
3328 3548 *
@@ -3364,15 +3584,16 @@
3364 3584 * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record
3365 3585 */
3366 3586 getPersistedCRDTDoc: (record) => {
3367 3587 return record?.meta?.[POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE] || null;
3368 - }
3588 + },
3589 + shouldSync: () => !(Array.isArray(window._wpCollaborationDisabledPostTypes) && window._wpCollaborationDisabledPostTypes.includes(name))
3369 3590 };
3370 3591 return entity2;
3371 3592 });
3372 3593 }
3373 3594 async function loadTaxonomyEntities() {
3374 - const taxonomies = await (0, import_api_fetch.default)({
3595 + const taxonomies = await (0, import_api_fetch2.default)({
3375 3596 path: "/wp/v2/taxonomies?context=view"
3376 3597 });
3377 3598 return Object.entries(taxonomies ?? {}).map(([name, taxonomy]) => {
3378 3599 const namespace = taxonomy?.rest_namespace ?? "wp/v2";
@@ -3384,9 +3605,11 @@
3384 3605 label: taxonomy.name,
3385 3606 getTitle: (record) => record?.name,
3386 3607 supportsPagination: true
3387 3608 };
3388 - entity2.syncConfig = defaultSyncConfig;
3609 + if (window.__experimentalEnableRealTimeCollaboration) {
3610 + entity2.syncConfig = defaultSyncConfig;
3611 + }
3389 3612 return entity2;
3390 3613 });
3391 3614 }
3392 3615 async function loadSiteEntity() {
@@ -3398,9 +3621,9 @@
3398 3621 baseURL: "/wp/v2/settings",
3399 3622 supportsPagination: false,
3400 3623 meta: {}
3401 3624 };
3402 - const site = await (0, import_api_fetch.default)({
3625 + const site = await (0, import_api_fetch2.default)({
3403 3626 path: entity2.baseURL,
3404 3627 method: "OPTIONS"
3405 3628 });
3406 3629 const labels = {};
@@ -3561,8 +3784,29 @@
3561 3784 ),
3562 3785 meta: action.meta
3563 3786 };
3564 3787 });
3788 + function removeQueryItems(queryItems, removedItems) {
3789 + const itemIds = queryItems.itemIds.filter(
3790 + (itemId) => !removedItems[itemId]
3791 + );
3792 + const removedCount = queryItems.itemIds.length - itemIds.length;
3793 + if (removedCount === 0) {
3794 + return queryItems;
3795 + }
3796 + const nextQueryItems = { ...queryItems, itemIds };
3797 + if (Number.isFinite(queryItems.meta?.totalItems)) {
3798 + nextQueryItems.meta = {
3799 + ...queryItems.meta,
3800 + totalItems: Math.max(
3801 + 0,
3802 + queryItems.meta.totalItems - removedCount
3803 + ),
3804 + totalPages: null
3805 + };
3806 + }
3807 + return nextQueryItems;
3808 + }
3565 3809 var queries = (state = {}, action) => {
3566 3810 switch (action.type) {
3567 3811 case "RECEIVE_ITEMS":
3568 3812 return receiveQueries(state, action);
@@ -3578,14 +3822,12 @@
3578 3822 Object.fromEntries(
3579 3823 Object.entries(contextQueries).map(
3580 3824 ([query, queryItems]) => [
3581 3825 query,
3582 - {
3583 - ...queryItems,
3584 - itemIds: queryItems.itemIds.filter(
3585 - (queryId) => !removedItems[queryId]
3586 - )
3587 - }
3826 + removeQueryItems(
3827 + queryItems,
3828 + removedItems
3829 + )
3588 3830 ]
3589 3831 )
3590 3832 )
3591 3833 ]
@@ -3670,20 +3912,23 @@
3670 3912 if (action.type === "UNDO" || action.type === "REDO") {
3671 3913 const { record } = action;
3672 3914 let newState = state;
3673 3915 record.forEach(({ id: { kind, name, recordId }, changes }) => {
3916 + const persistedRecord = state?.queriedData?.items?.default?.[recordId];
3917 + const edits = Object.fromEntries(
3918 + Object.entries(changes).map(([key, value]) => [
3919 + key,
3920 + action.type === "UNDO" ? value.from : value.to
3921 + ])
3922 + );
3674 3923 newState = reducer(newState, {
3675 3924 type: "EDIT_ENTITY_RECORD",
3676 3925 kind,
3677 3926 name,
3678 3927 recordId,
3679 - edits: Object.entries(changes).reduce(
3680 - (acc, [key, value]) => {
3681 - acc[key] = action.type === "UNDO" ? value.from : value.to;
3682 - return acc;
3683 - },
3684 - {}
3685 - )
3928 + // Clear edits matching the persisted record so the entity is
3929 + // no longer dirty after undoing back to its saved state.
3930 + edits: clearUnchangedEdits(edits, persistedRecord)
3686 3931 });
3687 3932 });
3688 3933 return newState;
3689 3934 }
@@ -3727,14 +3972,14 @@
3727 3972 if (
3728 3973 // Edits are the "raw" attribute values, but records may have
3729 3974 // objects with more properties, so we use `get` here for the
3730 3975 // comparison.
3731 - !(0, import_es64.default)(
3976 + !(0, import_es65.default)(
3732 3977 edits[key],
3733 3978 record[key]?.raw ?? record[key]
3734 3979 ) && // Sometimes the server alters the sent value which means
3735 3980 // we need to also remove the edits before the api request.
3736 - (!action.persistedEdits || !(0, import_es64.default)(
3981 + (!action.persistedEdits || !(0, import_es65.default)(
3737 3982 edits[key],
3738 3983 action.persistedEdits[key]
3739 3984 ))
3740 3985 ) {
@@ -3876,8 +4121,18 @@
3876 4121 };
3877 4122 function undoManager(state = (0, import_undo_manager.createUndoManager)()) {
3878 4123 return state;
3879 4124 }
4125 + function syncUndoManagerState(state = { hasRedo: false, hasUndo: false }, action) {
4126 + switch (action.type) {
4127 + case "SYNC_UNDO_MANAGER_CHANGE":
4128 + return {
4129 + hasRedo: action.hasRedo,
4130 + hasUndo: action.hasUndo
4131 + };
4132 + }
4133 + return state;
4134 + }
3880 4135 function editsReference(state = {}, action) {
3881 4136 switch (action.type) {
3882 4137 case "EDIT_ENTITY_RECORD":
3883 4138 case "UNDO":
@@ -4025,13 +4280,18 @@
4025 4280 return state;
4026 4281 }
4027 4282 function viewConfigs(state = {}, action) {
4028 4283 switch (action.type) {
4029 - case "RECEIVE_VIEW_CONFIG":
4284 + case "RECEIVE_VIEW_CONFIG": {
4285 + const key = `${action.kind}/${action.name}`;
4030 4286 return {
4031 4287 ...state,
4032 - [`${action.kind}/${action.name}`]: action.config
4288 + [key]: {
4289 + ...state[key],
4290 + ...action.config
4291 + }
4033 4292 };
4293 + }
4034 4294 }
4035 4295 return state;
4036 4296 }
4037 4297 var reducer_default2 = (0, import_data7.combineReducers)({
@@ -4043,8 +4303,9 @@
4043 4303 themeBaseGlobalStyles,
4044 4304 themeGlobalStyleRevisions,
4045 4305 entities,
4046 4306 editsReference,
4307 + syncUndoManagerState,
4047 4308 undoManager,
4048 4309 embedPreviews,
4049 4310 userPermissions,
4050 4311 autosaves,
@@ -4128,8 +4389,9 @@
4128 4389 getEditorAssets: () => getEditorAssets,
4129 4390 getEditorSettings: () => getEditorSettings,
4130 4391 getEntityRecordPermissions: () => getEntityRecordPermissions,
4131 4392 getEntityRecordsPermissions: () => getEntityRecordsPermissions,
4393 + getEntitySyncConnectionStatus: () => getEntitySyncConnectionStatus,
4132 4394 getHomePage: () => getHomePage,
4133 4395 getNavigationFallbackId: () => getNavigationFallbackId,
4134 4396 getPostsPageId: () => getPostsPageId,
4135 4397 getRegisteredPostMeta: () => getRegisteredPostMeta,
@@ -4286,9 +4548,11 @@
4286 4548 );
4287 4549 if (!templates) {
4288 4550 return;
4289 4551 }
4290 - const id = templates.find(({ slug }) => slug === "front-page")?.id;
4552 + const id = templates.find(
4553 + ({ slug }) => slug === "front-page"
4554 + )?.id;
4291 4555 if (id) {
4292 4556 return id;
4293 4557 }
4294 4558 }
@@ -4355,8 +4619,11 @@
4355 4619 }
4356 4620 }
4357 4621 return coalesced;
4358 4622 }
4623 + function getEntitySyncConnectionStatus(state, kind, name, recordId) {
4624 + return state.syncConnectionStatuses?.[`${kind}/${name}:${recordId}`];
4625 + }
4359 4626
4360 4627 // packages/core-data/build-module/selectors.mjs
4361 4628 var EMPTY_OBJECT2 = {};
4362 4629 var isRequestingEmbedPreview = (0, import_data9.createRegistrySelector)(
@@ -4415,54 +4682,34 @@
4415 4682 return state.entities.config?.find(
4416 4683 (config) => config.kind === kind && config.name === name
4417 4684 );
4418 4685 }
4419 - var getEntityRecord = (0, import_data9.createSelector)(
4420 - ((state, kind, name, key, query) => {
4421 - logEntityDeprecation(kind, name, "getEntityRecord");
4422 - const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4423 - if (!queriedState) {
4686 + var getEntityRecord = ((state, kind, name, recordId, query) => {
4687 + logEntityDeprecation(kind, name, "getEntityRecord");
4688 + const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4689 + if (!queriedState) {
4690 + return void 0;
4691 + }
4692 + const context = query?.context ?? "default";
4693 + if (!query || !query._fields) {
4694 + if (!queriedState.itemIsComplete[context]?.[recordId]) {
4424 4695 return void 0;
4425 4696 }
4426 - const context = query?.context ?? "default";
4427 - if (!query || !query._fields) {
4428 - if (!queriedState.itemIsComplete[context]?.[key]) {
4429 - return void 0;
4430 - }
4431 - return queriedState.items[context][key];
4432 - }
4433 - const item = queriedState.items[context]?.[key];
4434 - if (!item) {
4435 - return item;
4436 - }
4437 - const filteredItem = {};
4438 - const fields = get_normalized_comma_separable_default(query._fields) ?? [];
4439 - for (let f = 0; f < fields.length; f++) {
4440 - const field = fields[f].split(".");
4441 - let value = item;
4442 - field.forEach((fieldName) => {
4443 - value = value?.[fieldName];
4444 - });
4445 - setNestedValue(filteredItem, field, value);
4446 - }
4447 - return filteredItem;
4448 - }),
4449 - (state, kind, name, recordId, query) => {
4450 - const context = query?.context ?? "default";
4451 - const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4452 - return [
4453 - queriedState?.items[context]?.[recordId],
4454 - queriedState?.itemIsComplete[context]?.[recordId]
4455 - ];
4697 + return queriedState.items[context][recordId];
4456 4698 }
4457 - );
4458 - getEntityRecord.__unstableNormalizeArgs = (args) => {
4699 + const item = queriedState.items[context]?.[recordId];
4700 + if (!item) {
4701 + return item;
4702 + }
4703 + return getFilteredItem(item, query._fields);
4704 + });
4705 + getEntityRecord.normalizeArgs = (args) => {
4459 4706 const newArgs = [...args];
4460 4707 const recordKey = newArgs?.[2];
4461 4708 newArgs[2] = isNumericID(recordKey) ? Number(recordKey) : recordKey;
4462 4709 return newArgs;
4463 4710 };
4464 - function hasEntityRecord(state, kind, name, key, query) {
4711 + function hasEntityRecord(state, kind, name, recordId, query) {
4465 4712 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4466 4713 if (!queriedState) {
4467 4714 return false;
4468 4715 }
@@ -4467,11 +4714,11 @@
4467 4714 return false;
4468 4715 }
4469 4716 const context = query?.context ?? "default";
4470 4717 if (!query || !query._fields) {
4471 - return !!queriedState.itemIsComplete[context]?.[key];
4718 + return !!queriedState.itemIsComplete[context]?.[recordId];
4472 4719 }
4473 - const item = queriedState.items[context]?.[key];
4720 + const item = queriedState.items[context]?.[recordId];
4474 4721 if (!item) {
4475 4722 return false;
4476 4723 }
4477 4724 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
@@ -4487,19 +4734,19 @@
4487 4734 }
4488 4735 }
4489 4736 return true;
4490 4737 }
4491 - function __experimentalGetEntityRecordNoResolver(state, kind, name, key) {
4492 - return getEntityRecord(state, kind, name, key);
4738 + function __experimentalGetEntityRecordNoResolver(state, kind, name, recordId) {
4739 + return getEntityRecord(state, kind, name, recordId);
4493 4740 }
4494 4741 var getRawEntityRecord = (0, import_data9.createSelector)(
4495 - (state, kind, name, key) => {
4742 + (state, kind, name, recordId) => {
4496 4743 logEntityDeprecation(kind, name, "getRawEntityRecord");
4497 4744 const record = getEntityRecord(
4498 4745 state,
4499 4746 kind,
4500 4747 name,
4501 - key
4748 + recordId
4502 4749 );
4503 4750 const config = getEntityConfig(state, kind, name);
4504 4751 if (!record || !config?.rawAttributes?.length) {
4505 4752 return record;
@@ -4504,17 +4751,17 @@
4504 4751 if (!record || !config?.rawAttributes?.length) {
4505 4752 return record;
4506 4753 }
4507 4754 return Object.fromEntries(
4508 - Object.keys(record).map((_key) => {
4509 - if (config.rawAttributes.includes(_key)) {
4510 - const rawValue = record[_key]?.raw;
4755 + Object.keys(record).map((key) => {
4756 + if (config.rawAttributes.includes(key)) {
4757 + const rawValue = record[key]?.raw;
4511 4758 return [
4512 - _key,
4513 - rawValue !== void 0 ? rawValue : record[_key]
4759 + key,
4760 + rawValue !== void 0 ? rawValue : record[key]
4514 4761 ];
4515 4762 }
4516 - return [_key, record[_key]];
4763 + return [key, record[key]];
4517 4764 })
4518 4765 );
4519 4766 },
4520 4767 (state, kind, name, recordId, query) => {
@@ -4643,9 +4890,9 @@
4643 4890 (state) => [state.entities.records]
4644 4891 );
4645 4892 function getEntityRecordEdits(state, kind, name, recordId) {
4646 4893 logEntityDeprecation(kind, name, "getEntityRecordEdits");
4647 - return state.entities.records?.[kind]?.[name]?.edits?.[recordId];
4894 + return state.entities.records?.[kind]?.[name]?.edits?.[String(recordId)];
4648 4895 }
4649 4896 var getEntityRecordNonTransientEdits = (0, import_data9.createSelector)(
4650 4897 (state, kind, name, recordId) => {
4651 4898 logEntityDeprecation(kind, name, "getEntityRecordNonTransientEdits");
@@ -4662,9 +4909,9 @@
4662 4909 }, {});
4663 4910 },
4664 4911 (state, kind, name, recordId) => [
4665 4912 state.entities.config,
4666 - state.entities.records?.[kind]?.[name]?.edits?.[recordId]
4913 + state.entities.records?.[kind]?.[name]?.edits?.[String(recordId)]
4667 4914 ]
4668 4915 );
4669 4916 function hasEditsForEntityRecord(state, kind, name, recordId) {
4670 4917 logEntityDeprecation(kind, name, "hasEditsForEntityRecord");
@@ -4690,9 +4937,9 @@
4690 4937 return [
4691 4938 state.entities.config,
4692 4939 state.entities.records?.[kind]?.[name]?.queriedData.items[context]?.[recordId],
4693 4940 state.entities.records?.[kind]?.[name]?.queriedData.itemIsComplete[context]?.[recordId],
4694 - state.entities.records?.[kind]?.[name]?.edits?.[recordId]
4941 + state.entities.records?.[kind]?.[name]?.edits?.[String(recordId)]
4695 4942 ];
4696 4943 }
4697 4944 );
4698 4945 function isAutosavingEntityRecord(state, kind, name, recordId) {
@@ -4701,17 +4948,17 @@
4701 4948 return Boolean(pending && isAutosave);
4702 4949 }
4703 4950 function isSavingEntityRecord(state, kind, name, recordId) {
4704 4951 logEntityDeprecation(kind, name, "isSavingEntityRecord");
4705 - return state.entities.records?.[kind]?.[name]?.saving?.[recordId]?.pending ?? false;
4952 + return state.entities.records?.[kind]?.[name]?.saving?.[String(recordId)]?.pending ?? false;
4706 4953 }
4707 4954 function isDeletingEntityRecord(state, kind, name, recordId) {
4708 4955 logEntityDeprecation(kind, name, "isDeletingEntityRecord");
4709 - return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.pending ?? false;
4956 + return state.entities.records?.[kind]?.[name]?.deleting?.[String(recordId)]?.pending ?? false;
4710 4957 }
4711 4958 function getLastEntitySaveError(state, kind, name, recordId) {
4712 4959 logEntityDeprecation(kind, name, "getLastEntitySaveError");
4713 - return state.entities.records?.[kind]?.[name]?.saving?.[recordId]?.error;
4960 + return state.entities.records?.[kind]?.[name]?.saving?.[String(recordId)]?.error;
4714 4961 }
4715 4962 function getLastEntityDeleteError(state, kind, name, recordId) {
4716 4963 logEntityDeprecation(kind, name, "getLastEntityDeleteError");
4717 4964 return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.error;
@@ -4728,11 +4975,17 @@
4728 4975 });
4729 4976 return void 0;
4730 4977 }
4731 4978 function hasUndo(state) {
4979 + if (getSyncManager()?.undoManager) {
4980 + return state.syncUndoManagerState.hasUndo;
4981 + }
4732 4982 return getUndoManager(state).hasUndo();
4733 4983 }
4734 4984 function hasRedo(state) {
4985 + if (getSyncManager()?.undoManager) {
4986 + return state.syncUndoManagerState.hasRedo;
4987 + }
4735 4988 return getUndoManager(state).hasRedo();
4736 4989 }
4737 4990 function getCurrentTheme(state) {
4738 4991 if (!state.currentTheme) {
@@ -4869,47 +5122,27 @@
4869 5122 }
4870 5123 }
4871 5124 return true;
4872 5125 }
4873 - var getRevision = (0, import_data9.createSelector)(
4874 - (state, kind, name, recordKey, revisionKey, query) => {
4875 - logEntityDeprecation(kind, name, "getRevision");
4876 - const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
4877 - if (!queriedState) {
5126 + var getRevision = (state, kind, name, recordKey, revisionKey, query) => {
5127 + logEntityDeprecation(kind, name, "getRevision");
5128 + const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
5129 + if (!queriedState) {
5130 + return void 0;
5131 + }
5132 + const context = query?.context ?? "default";
5133 + if (!query || !query._fields) {
5134 + if (!queriedState.itemIsComplete[context]?.[revisionKey]) {
4878 5135 return void 0;
4879 5136 }
4880 - const context = query?.context ?? "default";
4881 - if (!query || !query._fields) {
4882 - if (!queriedState.itemIsComplete[context]?.[revisionKey]) {
4883 - return void 0;
4884 - }
4885 - return queriedState.items[context][revisionKey];
4886 - }
4887 - const item = queriedState.items[context]?.[revisionKey];
4888 - if (!item) {
4889 - return item;
4890 - }
4891 - const filteredItem = {};
4892 - const fields = get_normalized_comma_separable_default(query._fields) ?? [];
4893 - for (let f = 0; f < fields.length; f++) {
4894 - const field = fields[f].split(".");
4895 - let value = item;
4896 - field.forEach((fieldName) => {
4897 - value = value?.[fieldName];
4898 - });
4899 - setNestedValue(filteredItem, field, value);
4900 - }
4901 - return filteredItem;
4902 - },
4903 - (state, kind, name, recordKey, revisionKey, query) => {
4904 - const context = query?.context ?? "default";
4905 - const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
4906 - return [
4907 - queriedState?.items?.[context]?.[revisionKey],
4908 - queriedState?.itemIsComplete?.[context]?.[revisionKey]
4909 - ];
5137 + return queriedState.items[context][revisionKey];
4910 5138 }
4911 - );
5139 + const item = queriedState.items[context]?.[revisionKey];
5140 + if (!item) {
5141 + return item;
5142 + }
5143 + return getFilteredItem(item, query._fields);
5144 + };
4912 5145
4913 5146 // packages/core-data/build-module/actions.mjs
4914 5147 var actions_exports = {};
4915 5148 __export(actions_exports, {
@@ -4941,15 +5174,15 @@
4941 5174 saveEditedEntityRecord: () => saveEditedEntityRecord,
4942 5175 saveEntityRecord: () => saveEntityRecord,
4943 5176 undo: () => undo
4944 5177 });
4945 - var import_es65 = __toESM(require_es6(), 1);
4946 - var import_api_fetch3 = __toESM(require_api_fetch(), 1);
5178 + var import_es66 = __toESM(require_es6(), 1);
5179 + var import_api_fetch4 = __toESM(require_api_fetch(), 1);
4947 5180 var import_url3 = __toESM(require_url(), 1);
4948 5181 var import_deprecated3 = __toESM(require_deprecated(), 1);
4949 5182
4950 5183 // packages/core-data/build-module/batch/default-processor.mjs
4951 - var import_api_fetch2 = __toESM(require_api_fetch(), 1);
5184 + var import_api_fetch3 = __toESM(require_api_fetch(), 1);
4952 5185 var maxItems = null;
4953 5186 function chunk(arr, chunkSize) {
4954 5187 const tmp = [...arr];
4955 5188 const cache3 = [];
@@ -4959,9 +5192,9 @@
4959 5192 return cache3;
4960 5193 }
4961 5194 async function defaultProcessor(requests) {
4962 5195 if (maxItems === null) {
4963 - const preflightResponse = await (0, import_api_fetch2.default)({
5196 + const preflightResponse = await (0, import_api_fetch3.default)({
4964 5197 path: "/batch/v1",
4965 5198 method: "OPTIONS"
4966 5199 });
4967 5200 maxItems = preflightResponse.endpoints[0].args.requests.maxItems;
@@ -4967,9 +5200,9 @@
4967 5200 maxItems = preflightResponse.endpoints[0].args.requests.maxItems;
4968 5201 }
4969 5202 const results = [];
4970 5203 for (const batchRequests of chunk(requests, maxItems)) {
4971 - const batchResponse = await (0, import_api_fetch2.default)({
5204 + const batchResponse = await (0, import_api_fetch3.default)({
4972 5205 path: "/batch/v1",
4973 5206 method: "POST",
4974 5207 data: {
4975 5208 validation: "require-all-validate",
@@ -5131,8 +5364,39 @@
5131 5364 // packages/core-data/build-module/actions.mjs
5132 5365 function addTitleToAutoDraft(record) {
5133 5366 return record.status === "auto-draft" ? { ...record, title: "" } : record;
5134 5367 }
5368 + function getServerMutatedMetaFields(updatedMeta, persistedMeta, syncedMeta) {
5369 + const baseline = { ...persistedMeta, ...syncedMeta };
5370 + return Object.fromEntries(
5371 + Object.entries(updatedMeta ?? {}).filter(([key, value]) => {
5372 + if (key === POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE) {
5373 + return false;
5374 + }
5375 + return !(0, import_es66.default)(value, baseline[key]);
5376 + })
5377 + );
5378 + }
5379 + function getServerMutatedFields(updatedRecord, persistedRecord, syncedChanges) {
5380 + return Object.fromEntries(
5381 + Object.entries(updatedRecord).flatMap(([key, value]) => {
5382 + if (key === "meta") {
5383 + const serverMutatedMeta = getServerMutatedMetaFields(
5384 + value,
5385 + persistedRecord.meta,
5386 + syncedChanges.meta
5387 + );
5388 + return Object.keys(serverMutatedMeta).length ? [[key, serverMutatedMeta]] : [];
5389 + }
5390 + const baseline = key in syncedChanges ? syncedChanges[key] : persistedRecord[key];
5391 + const wasServerMutated = !(0, import_es66.default)(
5392 + getRawValue(value) ?? value,
5393 + getRawValue(baseline) ?? baseline
5394 + );
5395 + return wasServerMutated ? [[key, value]] : [];
5396 + })
5397 + );
5398 + }
5135 5399 function receiveUserQuery(queryID, users2) {
5136 5400 return {
5137 5401 type: "RECEIVE_USER_QUERY",
5138 5402 users: Array.isArray(users2) ? users2 : [users2],
@@ -5222,9 +5486,9 @@
5222 5486 url,
5223 5487 preview
5224 5488 };
5225 5489 }
5226 - var deleteEntityRecord = (kind, name, recordId, query, { __unstableFetch = import_api_fetch3.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5490 + var deleteEntityRecord = (kind, name, recordId, query, { __unstableFetch = import_api_fetch4.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5227 5491 logEntityDeprecation(kind, name, "deleteEntityRecord");
5228 5492 const configs = await resolveSelect2.getEntitiesConfig(kind);
5229 5493 const entityConfig = configs.find(
5230 5494 (config) => config.kind === kind && config.name === name
@@ -5246,12 +5510,9 @@
5246 5510 name,
5247 5511 recordId
5248 5512 });
5249 5513 let hasError = false;
5250 - let { baseURL } = entityConfig;
5251 - if (kind === "postType" && name === "wp_template" && (recordId && typeof recordId === "string" && !/^\d+$/.test(recordId) || !window?.__experimentalTemplateActivate)) {
5252 - baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
5253 - }
5514 + const { baseURL } = entityConfig;
5254 5515 try {
5255 5516 let path = `${baseURL}/${recordId}`;
5256 5517 if (query) {
5257 5518 path = (0, import_url3.addQueryArgs)(path, query);
@@ -5309,14 +5570,9 @@
5309 5570 name,
5310 5571 recordId,
5311 5572 // Clear edits when they are equal to their persisted counterparts
5312 5573 // so that the property is not considered dirty.
5313 - edits: Object.keys(edits).reduce((acc, key) => {
5314 - const recordValue = record[key];
5315 - const value = editsWithMerges[key];
5316 - acc[key] = (0, import_es65.default)(recordValue, value) ? void 0 : value;
5317 - return acc;
5318 - }, {})
5574 + edits: clearUnchangedEdits(editsWithMerges, record)
5319 5575 };
5320 5576 if (entityConfig.syncConfig) {
5321 5577 const objectType = `${kind}/${name}`;
5322 5578 const objectId = recordId;
@@ -5408,9 +5664,9 @@
5408 5664 };
5409 5665 var saveEntityRecord = (kind, name, record, options = {}) => async ({ select: select5, resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
5410 5666 const {
5411 5667 isAutosave = false,
5412 - __unstableFetch = import_api_fetch3.default,
5668 + __unstableFetch = import_api_fetch4.default,
5413 5669 __unstableSkipSyncUpdate = false,
5414 5670 throwOnError = false
5415 5671 } = options;
5416 5672 logEntityDeprecation(kind, name, "saveEntityRecord");
@@ -5456,15 +5712,20 @@
5456 5712 });
5457 5713 let updatedRecord;
5458 5714 let error;
5459 5715 let hasError = false;
5460 - let { baseURL } = entityConfig;
5461 - if (kind === "postType" && name === "wp_template" && (recordId && typeof recordId === "string" && !/^\d+$/.test(recordId) || !window?.__experimentalTemplateActivate)) {
5462 - baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
5463 - }
5716 + const { baseURL } = entityConfig;
5464 5717 try {
5465 5718 const path = `${baseURL}${recordId ? "/" + recordId : ""}`;
5466 5719 const persistedRecord = !isNewRecord ? select5.getRawEntityRecord(kind, name, recordId) : {};
5720 + if (entityConfig.syncConfig && !__unstableSkipSyncUpdate && !isNewRecord && persistedRecord) {
5721 + getSyncManager()?.update(
5722 + `${kind}/${name}`,
5723 + recordId,
5724 + record,
5725 + LOCAL_UNDO_IGNORED_ORIGIN
5726 + );
5727 + }
5467 5728 if (isAutosave) {
5468 5729 const merged = { ...persistedRecord, ...record };
5469 5730 const data = [
5470 5731 "title",
@@ -5485,8 +5746,17 @@
5485 5746 // have a draft post and change the status to publish.
5486 5747 status: merged.status === "auto-draft" ? "draft" : void 0
5487 5748 }
5488 5749 );
5750 + if (entityConfig.syncConfig) {
5751 + const crdtSnapshot = getSyncManager()?.getEntitySnapshot(
5752 + `${kind}/${name}`,
5753 + recordId
5754 + );
5755 + if (crdtSnapshot) {
5756 + data[CRDT_AUTOSAVE_SNAPSHOT_KEY] = crdtSnapshot;
5757 + }
5758 + }
5489 5759 updatedRecord = await __unstableFetch({
5490 5760 path: `${path}/autosaves`,
5491 5761 method: "POST",
5492 5762 data
@@ -5549,15 +5819,27 @@
5549 5819 name,
5550 5820 updatedRecord,
5551 5821 void 0,
5552 5822 true,
5553 - edits
5823 + record
5554 5824 );
5555 5825 if (entityConfig.syncConfig) {
5826 + let syncChanges;
5827 + if (__unstableSkipSyncUpdate) {
5828 + syncChanges = {};
5829 + } else if (isNewRecord || !persistedRecord) {
5830 + syncChanges = updatedRecord;
5831 + } else {
5832 + syncChanges = getServerMutatedFields(
5833 + updatedRecord,
5834 + persistedRecord,
5835 + record
5836 + );
5837 + }
5556 5838 getSyncManager()?.update(
5557 5839 `${kind}/${name}`,
5558 5840 recordId,
5559 - __unstableSkipSyncUpdate ? {} : updatedRecord,
5841 + syncChanges,
5560 5842 LOCAL_UNDO_IGNORED_ORIGIN,
5561 5843 { isSave: true }
5562 5844 );
5563 5845 }
@@ -5733,17 +6015,23 @@
5733 6015
5734 6016 // packages/core-data/build-module/private-actions.mjs
5735 6017 var private_actions_exports = {};
5736 6018 __export(private_actions_exports, {
6019 + __unstableNotifySyncUndoManagerChange: () => __unstableNotifySyncUndoManagerChange,
5737 6020 editMediaEntity: () => editMediaEntity,
5738 6021 receiveEditorAssets: () => receiveEditorAssets,
5739 6022 receiveEditorSettings: () => receiveEditorSettings,
5740 6023 receiveRegisteredPostMeta: () => receiveRegisteredPostMeta,
5741 6024 receiveViewConfig: () => receiveViewConfig,
6025 + saveDirtyEntities: () => saveDirtyEntities,
5742 6026 setCollaborationSupported: () => setCollaborationSupported,
5743 6027 setSyncConnectionStatus: () => setSyncConnectionStatus
5744 6028 });
5745 - var import_api_fetch4 = __toESM(require_api_fetch(), 1);
6029 + var import_api_fetch5 = __toESM(require_api_fetch(), 1);
6030 + var import_notices = __toESM(require_notices(), 1);
6031 + var import_block_editor5 = __toESM(require_block_editor(), 1);
6032 + var import_html_entities = __toESM(require_html_entities(), 1);
6033 + var import_i18n2 = __toESM(require_i18n(), 1);
5746 6034 function receiveRegisteredPostMeta(postType, registeredPostMeta2) {
5747 6035 return {
5748 6036 type: "RECEIVE_REGISTERED_POST_META",
5749 6037 postType,
@@ -5749,9 +6037,9 @@
5749 6037 postType,
5750 6038 registeredPostMeta: registeredPostMeta2
5751 6039 };
5752 6040 }
5753 - var editMediaEntity = (recordId, edits = {}, { __unstableFetch = import_api_fetch4.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6041 + var editMediaEntity = (recordId, edits = {}, { __unstableFetch = import_api_fetch5.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5754 6042 if (!recordId) {
5755 6043 return;
5756 6044 }
5757 6045 const kind = "postType";
@@ -5833,8 +6121,12 @@
5833 6121 var setCollaborationSupported = (supported) => ({ dispatch: dispatch3 }) => {
5834 6122 dispatch3({ type: "SET_COLLABORATION_SUPPORTED", supported });
5835 6123 if (!supported && hasSyncManager()) {
5836 6124 getSyncManager().unloadAll();
6125 + dispatch3.__unstableNotifySyncUndoManagerChange({
6126 + hasUndo: false,
6127 + hasRedo: false
6128 + });
5837 6129 }
5838 6130 };
5839 6131 function receiveViewConfig(kind, name, config) {
5840 6132 return {
@@ -5843,8 +6135,14 @@
5843 6135 name,
5844 6136 config
5845 6137 };
5846 6138 }
6139 + function __unstableNotifySyncUndoManagerChange(state) {
6140 + return {
6141 + type: "SYNC_UNDO_MANAGER_CHANGE",
6142 + ...state
6143 + };
6144 + }
5847 6145 function setSyncConnectionStatus(kind, name, key, status) {
5848 6146 if (!status) {
5849 6147 return {
5850 6148 type: "CLEAR_SYNC_CONNECTION_STATUS",
@@ -5860,8 +6158,134 @@
5860 6158 key,
5861 6159 status
5862 6160 };
5863 6161 }
6162 + var saveDirtyEntities = ({
6163 + onSave,
6164 + dirtyEntityRecords = [],
6165 + entitiesToSkip = [],
6166 + close,
6167 + successNoticeContent
6168 + } = {}) => ({ registry }) => {
6169 + const PUBLISH_ON_SAVE_ENTITIES = [
6170 + { kind: "postType", name: "wp_navigation" }
6171 + ];
6172 + const saveNoticeId = "site-editor-save-success";
6173 + const homeUrl = registry.select(STORE_NAME).getEntityRecord("root", "__unstableBase")?.home;
6174 + registry.dispatch(import_notices.store).removeNotice(saveNoticeId);
6175 + const entitiesToSave = dirtyEntityRecords.filter(
6176 + ({ kind, name, key, property }) => {
6177 + return !entitiesToSkip.some(
6178 + (elt) => elt.kind === kind && elt.name === name && elt.key === key && elt.property === property
6179 + );
6180 + }
6181 + );
6182 + close?.(entitiesToSave);
6183 + const siteItemsToSave = [];
6184 + const pendingSavedRecords = [];
6185 + entitiesToSave.forEach(({ kind, name, key, property }) => {
6186 + if ("root" === kind && "site" === name) {
6187 + siteItemsToSave.push(property);
6188 + } else {
6189 + if (PUBLISH_ON_SAVE_ENTITIES.some(
6190 + (typeToPublish) => typeToPublish.kind === kind && typeToPublish.name === name
6191 + )) {
6192 + registry.dispatch(STORE_NAME).editEntityRecord(kind, name, key, {
6193 + status: "publish"
6194 + });
6195 + }
6196 + pendingSavedRecords.push(
6197 + registry.dispatch(STORE_NAME).saveEditedEntityRecord(kind, name, key, {
6198 + throwOnError: true
6199 + }).catch(ensureError)
6200 + );
6201 + }
6202 + });
6203 + if (siteItemsToSave.length) {
6204 + pendingSavedRecords.push(
6205 + registry.dispatch(STORE_NAME).__experimentalSaveSpecifiedEntityEdits(
6206 + "root",
6207 + "site",
6208 + void 0,
6209 + siteItemsToSave,
6210 + {
6211 + throwOnError: true
6212 + }
6213 + ).catch(ensureError)
6214 + );
6215 + }
6216 + registry.dispatch(import_block_editor5.store).__unstableMarkLastChangeAsPersistent();
6217 + return Promise.all(pendingSavedRecords).then(async (values) => {
6218 + if (onSave) {
6219 + await onSave();
6220 + }
6221 + return values;
6222 + }).then((values) => {
6223 + const errors = values.filter((v) => v instanceof Error);
6224 + if (errors.length) {
6225 + const firstMessage = errors.find(
6226 + (e) => e.message
6227 + )?.message;
6228 + registry.dispatch(import_notices.store).createErrorNotice(
6229 + (0, import_html_entities.decodeEntities)(
6230 + firstMessage || (0, import_i18n2.__)("Saving failed.")
6231 + ),
6232 + {
6233 + type: "snackbar",
6234 + id: saveNoticeId
6235 + }
6236 + );
6237 + } else {
6238 + registry.dispatch(import_notices.store).createSuccessNotice(
6239 + successNoticeContent || (0, import_i18n2.__)("Site updated."),
6240 + {
6241 + type: "snackbar",
6242 + id: saveNoticeId,
6243 + actions: [
6244 + {
6245 + label: (0, import_i18n2.__)("View site"),
6246 + url: homeUrl,
6247 + openInNewTab: true
6248 + }
6249 + ]
6250 + }
6251 + );
6252 + }
6253 + }).catch(
6254 + (error) => registry.dispatch(import_notices.store).createErrorNotice(
6255 + (0, import_html_entities.decodeEntities)(
6256 + error?.message || (0, import_i18n2.__)("Saving failed.")
6257 + ),
6258 + {
6259 + type: "snackbar",
6260 + id: saveNoticeId
6261 + }
6262 + )
6263 + );
6264 + function ensureError(error) {
6265 + if (error instanceof Error) {
6266 + return error;
6267 + }
6268 + let message;
6269 + if (!error) {
6270 + } else if (typeof error.message === "string") {
6271 + message = error.message;
6272 + } else if (typeof error === "string") {
6273 + message = error;
6274 + } else if (
6275 + // Only consider own method, lest we erroneously end up calling
6276 + // `Object#toString` at the end of the prototype chain, thereby
6277 + // returning `"[object Object]"`.
6278 + Object.hasOwn(error, "toString") && typeof error.toString === "function"
6279 + ) {
6280 + const result = error.toString();
6281 + if (typeof result === "string") {
6282 + message = result;
6283 + }
6284 + }
6285 + return new Error(message, { cause: error });
6286 + }
6287 + };
5864 6288
5865 6289 // packages/core-data/build-module/resolvers.mjs
5866 6290 var resolvers_exports = {};
5867 6291 __export(resolvers_exports, {
@@ -5897,19 +6321,19 @@
5897 6321 getUserPatternCategories: () => getUserPatternCategories2,
5898 6322 getViewConfig: () => getViewConfig2
5899 6323 });
5900 6324 var import_url6 = __toESM(require_url(), 1);
5901 - var import_html_entities2 = __toESM(require_html_entities(), 1);
5902 - var import_api_fetch8 = __toESM(require_api_fetch(), 1);
6325 + var import_html_entities3 = __toESM(require_html_entities(), 1);
6326 + var import_api_fetch9 = __toESM(require_api_fetch(), 1);
5903 6327
5904 6328 // packages/core-data/build-module/fetch/index.mjs
5905 - var import_api_fetch7 = __toESM(require_api_fetch(), 1);
6329 + var import_api_fetch8 = __toESM(require_api_fetch(), 1);
5906 6330
5907 6331 // packages/core-data/build-module/fetch/__experimental-fetch-link-suggestions.mjs
5908 - var import_api_fetch5 = __toESM(require_api_fetch(), 1);
6332 + var import_api_fetch6 = __toESM(require_api_fetch(), 1);
5909 6333 var import_url4 = __toESM(require_url(), 1);
5910 - var import_html_entities = __toESM(require_html_entities(), 1);
5911 - var import_i18n2 = __toESM(require_i18n(), 1);
6334 + var import_html_entities2 = __toESM(require_html_entities(), 1);
6335 + var import_i18n3 = __toESM(require_i18n(), 1);
5912 6336 async function fetchLinkSuggestions(search, searchOptions = {}, editorSettings2 = {}) {
5913 6337 const searchOptionsToUse = searchOptions.isInitialSuggestions && searchOptions.initialSuggestionsSearchOptions ? {
5914 6338 ...searchOptions,
5915 6339 ...searchOptions.initialSuggestionsSearchOptions
@@ -5923,9 +6347,9 @@
5923 6347 const { disablePostFormats = false } = editorSettings2;
5924 6348 const queries2 = [];
5925 6349 if (!type || type === "post") {
5926 6350 queries2.push(
5927 - (0, import_api_fetch5.default)({
6351 + (0, import_api_fetch6.default)({
5928 6352 path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
5929 6353 search,
5930 6354 page,
5931 6355 per_page: perPage,
@@ -5936,9 +6360,9 @@
5936 6360 return results2.map((result) => {
5937 6361 return {
5938 6362 id: result.id,
5939 6363 url: result.url,
5940 - title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
6364 + title: (0, import_html_entities2.decodeEntities)(result.title || "") || (0, import_i18n3.__)("(no title)"),
5941 6365 type: result.subtype || result.type,
5942 6366 kind: "post-type"
5943 6367 };
5944 6368 });
@@ -5947,9 +6371,9 @@
5947 6371 );
5948 6372 }
5949 6373 if (!type || type === "term") {
5950 6374 queries2.push(
5951 - (0, import_api_fetch5.default)({
6375 + (0, import_api_fetch6.default)({
5952 6376 path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
5953 6377 search,
5954 6378 page,
5955 6379 per_page: perPage,
@@ -5960,9 +6384,9 @@
5960 6384 return results2.map((result) => {
5961 6385 return {
5962 6386 id: result.id,
5963 6387 url: result.url,
5964 - title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
6388 + title: (0, import_html_entities2.decodeEntities)(result.title || "") || (0, import_i18n3.__)("(no title)"),
5965 6389 type: result.subtype || result.type,
5966 6390 kind: "taxonomy"
5967 6391 };
5968 6392 });
@@ -5971,9 +6395,9 @@
5971 6395 );
5972 6396 }
5973 6397 if (!disablePostFormats && (!type || type === "post-format")) {
5974 6398 queries2.push(
5975 - (0, import_api_fetch5.default)({
6399 + (0, import_api_fetch6.default)({
5976 6400 path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
5977 6401 search,
5978 6402 page,
5979 6403 per_page: perPage,
@@ -5984,9 +6408,9 @@
5984 6408 return results2.map((result) => {
5985 6409 return {
5986 6410 id: result.id,
5987 6411 url: result.url,
5988 - title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
6412 + title: (0, import_html_entities2.decodeEntities)(result.title || "") || (0, import_i18n3.__)("(no title)"),
5989 6413 type: result.subtype || result.type,
5990 6414 kind: "taxonomy"
5991 6415 };
5992 6416 });
@@ -5995,9 +6419,9 @@
5995 6419 );
5996 6420 }
5997 6421 if (!type || type === "attachment") {
5998 6422 queries2.push(
5999 - (0, import_api_fetch5.default)({
6423 + (0, import_api_fetch6.default)({
6000 6424 path: (0, import_url4.addQueryArgs)("/wp/v2/media", {
6001 6425 search,
6002 6426 page,
6003 6427 per_page: perPage
@@ -6006,9 +6430,9 @@
6006 6430 return results2.map((result) => {
6007 6431 return {
6008 6432 id: result.id,
6009 6433 url: result.source_url,
6010 - title: (0, import_html_entities.decodeEntities)(result.title.rendered || "") || (0, import_i18n2.__)("(no title)"),
6434 + title: (0, import_html_entities2.decodeEntities)(result.title.rendered || "") || (0, import_i18n3.__)("(no title)"),
6011 6435 type: result.type,
6012 6436 kind: "media"
6013 6437 };
6014 6438 });
@@ -6024,8 +6448,9 @@
6024 6448 return results;
6025 6449 }
6026 6450 function sortResults(results, search) {
6027 6451 const searchTokens = tokenize(search);
6452 + const scoreKey = (result) => `${result.kind}:${result.type}:${result.id}`;
6028 6453 const scores = {};
6029 6454 for (const result of results) {
6030 6455 if (result.title) {
6031 6456 const titleTokens = tokenize(result.title);
@@ -6040,14 +6465,16 @@
6040 6465 )
6041 6466 );
6042 6467 const exactMatchScore = exactMatchingTokens.length / titleTokens.length * 10;
6043 6468 const subMatchScore = subMatchingTokens.length / titleTokens.length;
6044 - scores[result.id] = exactMatchScore + subMatchScore;
6469 + scores[scoreKey(result)] = exactMatchScore + subMatchScore;
6045 6470 } else {
6046 - scores[result.id] = 0;
6471 + scores[scoreKey(result)] = 0;
6047 6472 }
6048 6473 }
6049 - return results.sort((a, b) => scores[b.id] - scores[a.id]);
6474 + return results.sort(
6475 + (a, b) => scores[scoreKey(b)] - scores[scoreKey(a)]
6476 + );
6050 6477 }
6051 6478 function tokenize(text) {
6052 6479 return text.toLowerCase().match(/[\p{L}\p{N}]+/gu) || [];
6053 6480 }
@@ -6052,9 +6479,9 @@
6052 6479 return text.toLowerCase().match(/[\p{L}\p{N}]+/gu) || [];
6053 6480 }
6054 6481
6055 6482 // packages/core-data/build-module/fetch/__experimental-fetch-url-data.mjs
6056 - var import_api_fetch6 = __toESM(require_api_fetch(), 1);
6483 + var import_api_fetch7 = __toESM(require_api_fetch(), 1);
6057 6484 var import_url5 = __toESM(require_url(), 1);
6058 6485 var CACHE = /* @__PURE__ */ new Map();
6059 6486 var fetchUrlData = async (url, options = {}) => {
6060 6487 const endpoint = "/wp-block-editor/v1/url-details";
@@ -6072,9 +6499,9 @@
6072 6499 }
6073 6500 if (CACHE.has(url)) {
6074 6501 return CACHE.get(url);
6075 6502 }
6076 - return (0, import_api_fetch6.default)({
6503 + return (0, import_api_fetch7.default)({
6077 6504 path: (0, import_url5.addQueryArgs)(endpoint, args),
6078 6505 ...options
6079 6506 }).then((res) => {
6080 6507 CACHE.set(url, res);
@@ -6084,9 +6511,9 @@
6084 6511 var experimental_fetch_url_data_default = fetchUrlData;
6085 6512
6086 6513 // packages/core-data/build-module/fetch/index.mjs
6087 6514 async function fetchBlockPatterns() {
6088 - const restPatterns = await (0, import_api_fetch7.default)({
6515 + const restPatterns = await (0, import_api_fetch8.default)({
6089 6516 path: "/wp/v2/block-patterns/patterns"
6090 6517 });
6091 6518 if (!restPatterns) {
6092 6519 return [];
@@ -6101,12 +6528,32 @@
6101 6528 );
6102 6529 }
6103 6530
6104 6531 // packages/core-data/build-module/parsed-blocks-cache.mjs
6105 - var parsedBlocksCache = /* @__PURE__ */ new Map();
6532 + var import_data10 = __toESM(require_data(), 1);
6533 + var import_blocks5 = __toESM(require_blocks(), 1);
6534 + var caches = /* @__PURE__ */ new WeakMap();
6106 6535 function getCacheKey(kind, name, id) {
6107 6536 return `${kind}:${name}:${id}`;
6108 6537 }
6538 + function getBlockTypes2() {
6539 + return (0, import_data10.select)(import_blocks5.store).getBlockTypes();
6540 + }
6541 + function getCachedBlocks(kind, name, id, content) {
6542 + const cached = caches.get(getBlockTypes2())?.get(getCacheKey(kind, name, id));
6543 + if (cached && cached.content === content) {
6544 + return cached.blocks;
6545 + }
6546 + }
6547 + function setCachedBlocks(kind, name, id, content, blocks) {
6548 + const blockTypes = getBlockTypes2();
6549 + let cache3 = caches.get(blockTypes);
6550 + if (!cache3) {
6551 + cache3 = /* @__PURE__ */ new Map();
6552 + caches.set(blockTypes, cache3);
6553 + }
6554 + cache3.set(getCacheKey(kind, name, id), { content, blocks });
6555 + }
6109 6556
6110 6557 // packages/core-data/build-module/resolvers.mjs
6111 6558 var getAuthors2 = (query) => async ({ dispatch: dispatch3 }) => {
6112 6559 const path = (0, import_url6.addQueryArgs)(
@@ -6112,13 +6559,13 @@
6112 6559 const path = (0, import_url6.addQueryArgs)(
6113 6560 "/wp/v2/users/?who=authors&per_page=100",
6114 6561 query
6115 6562 );
6116 - const users2 = await (0, import_api_fetch8.default)({ path });
6563 + const users2 = await (0, import_api_fetch9.default)({ path });
6117 6564 dispatch3.receiveUserQuery(path, users2);
6118 6565 };
6119 6566 var getCurrentUser2 = () => async ({ dispatch: dispatch3 }) => {
6120 - const currentUser2 = await (0, import_api_fetch8.default)({ path: "/wp/v2/users/me" });
6567 + const currentUser2 = await (0, import_api_fetch9.default)({ path: "/wp/v2/users/me" });
6121 6568 dispatch3.receiveCurrentUser(currentUser2);
6122 6569 };
6123 6570 var getEntityRecord2 = (kind, name, key = "", query) => async ({ select: select5, dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
6124 6571 const configs = await resolveSelect2.getEntitiesConfig(kind);
@@ -6155,22 +6602,18 @@
6155 6602 if (hasRecord) {
6156 6603 return;
6157 6604 }
6158 6605 }
6159 - let { baseURL } = entityConfig;
6160 - if (kind === "postType" && name === "wp_template" && (key && typeof key === "string" && !/^\d+$/.test(key) || !window?.__experimentalTemplateActivate)) {
6161 - baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
6162 - }
6606 + const { baseURL } = entityConfig;
6163 6607 const path = (0, import_url6.addQueryArgs)(baseURL + (key ? "/" + key : ""), {
6164 6608 ...entityConfig.baseURLParams,
6165 6609 ...query
6166 6610 });
6167 - const response = await (0, import_api_fetch8.default)({ path, parse: false });
6611 + const response = await (0, import_api_fetch9.default)({ path, parse: false });
6168 6612 const record = await response.json();
6169 6613 const permissions = getUserPermissionsFromAllowHeader(
6170 6614 response.headers?.get("allow")
6171 6615 );
6172 - const canUserResolutionsArgs = [];
6173 6616 const receiveUserPermissionArgs = {};
6174 6617 for (const action of ALLOWED_RESOURCE_ACTIONS) {
6175 6618 receiveUserPermissionArgs[getUserPermissionCacheKey(action, {
6176 6619 kind,
@@ -6176,13 +6619,10 @@
6176 6619 kind,
6177 6620 name,
6178 6621 id: key
6179 6622 })] = permissions[action];
6180 - canUserResolutionsArgs.push([
6181 - action,
6182 - { kind, name, id: key }
6183 - ]);
6184 6623 }
6624 + const canUserResolutionsArgs = [[{ kind, name, id: key }]];
6185 6625 if (entityConfig.syncConfig && isNumericID(key) && !query) {
6186 6626 const objectType = `${kind}/${name}`;
6187 6627 const objectId = key;
6188 6628 const recordWithTransients = { ...record };
@@ -6191,14 +6631,18 @@
6191 6631 ).forEach(([propName, transientConfig]) => {
6192 6632 recordWithTransients[propName] = transientConfig.read(recordWithTransients);
6193 6633 });
6194 6634 if (recordWithTransients.blocks && typeof recordWithTransients.content?.raw === "string") {
6195 - parsedBlocksCache.set(getCacheKey(kind, name, key), {
6196 - content: recordWithTransients.content.raw,
6197 - blocks: recordWithTransients.blocks
6198 - });
6635 + setCachedBlocks(
6636 + kind,
6637 + name,
6638 + key,
6639 + recordWithTransients.content.raw,
6640 + recordWithTransients.blocks
6641 + );
6199 6642 }
6200 - void getSyncManager()?.load(
6643 + const syncManager2 = select5?.isCollaborationSupported?.() === false ? void 0 : getSyncManager();
6644 + void syncManager2?.load(
6201 6645 entityConfig.syncConfig,
6202 6646 objectType,
6203 6647 objectId,
6204 6648 recordWithTransients,
@@ -6239,9 +6683,9 @@
6239 6683 refetchRecord: async () => {
6240 6684 dispatch3.receiveEntityRecords(
6241 6685 kind,
6242 6686 name,
6243 - await (0, import_api_fetch8.default)({ path, parse: true }),
6687 + await (0, import_api_fetch9.default)({ path, parse: true }),
6244 6688 query
6245 6689 );
6246 6690 },
6247 6691 // Persist the CRDT document.
@@ -6250,21 +6694,21 @@
6250 6694 // This effectively means that only post entities support CRDT
6251 6695 // persistence. As we add support for syncing additional entity,
6252 6696 // we'll need to revisit where persisted CRDT documents are stored.
6253 6697 persistCRDTDoc: () => {
6254 - resolveSelect2.getEditedEntityRecord(kind, name, key).then((editedRecord) => {
6698 + if (!entityConfig.syncConfig?.supportsPersistence) {
6699 + return;
6700 + }
6701 + return resolveSelect2.getEditedEntityRecord(kind, name, key).then(async (editedRecord) => {
6255 6702 const { meta, status } = editedRecord;
6256 6703 if ("auto-draft" === status || !meta) {
6257 6704 return;
6258 6705 }
6259 6706 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
6260 - dispatch3.saveEntityRecord(
6261 - kind,
6262 - name,
6263 - {
6264 - [entityIdKey]: editedRecord[entityIdKey]
6265 - },
6266 - { __unstableSkipSyncUpdate: true }
6707 + const entityId = editedRecord[entityIdKey];
6708 + await saveCRDTDoc(
6709 + `${kind}/${name}`,
6710 + entityId
6267 6711 );
6268 6712 });
6269 6713 },
6270 6714 addUndoMeta: (ydoc, meta) => {
@@ -6275,8 +6719,13 @@
6275 6719 selectionHistory
6276 6720 );
6277 6721 }
6278 6722 },
6723 + onUndoStackChange: (undoState) => {
6724 + dispatch3.__unstableNotifySyncUndoManagerChange(
6725 + undoState
6726 + );
6727 + },
6279 6728 restoreUndoMeta: (ydoc, meta) => {
6280 6729 const selectionHistory = meta.get("selectionHistory");
6281 6730 if (selectionHistory) {
6282 6731 setTimeout(() => {
@@ -6339,13 +6788,9 @@
6339 6788 ])
6340 6789 ].join()
6341 6790 };
6342 6791 }
6343 - let { baseURL } = entityConfig;
6344 - const { combinedTemplates = true } = query;
6345 - if (kind === "postType" && name === "wp_template" && combinedTemplates) {
6346 - baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
6347 - }
6792 + const { baseURL } = entityConfig;
6348 6793 const path = (0, import_url6.addQueryArgs)(baseURL, {
6349 6794 ...entityConfig.baseURLParams,
6350 6795 ...query
6351 6796 });
@@ -6350,35 +6795,25 @@
6350 6795 ...query
6351 6796 });
6352 6797 let records = [], meta;
6353 6798 if (entityConfig.supportsPagination && query.per_page !== -1) {
6354 - const response = await (0, import_api_fetch8.default)({ path, parse: false });
6799 + const response = await (0, import_api_fetch9.default)({ path, parse: false });
6355 6800 records = Object.values(await response.json());
6356 - meta = {
6357 - totalItems: parseInt(
6358 - response.headers.get("X-WP-Total")
6359 - ),
6360 - totalPages: parseInt(
6361 - response.headers.get("X-WP-TotalPages")
6362 - )
6363 - };
6801 + meta = getPaginationMeta(response.headers);
6364 6802 } else if (query.per_page === -1 && query[RECEIVE_INTERMEDIATE_RESULTS] === true) {
6365 6803 let page = 1;
6366 6804 let totalPages;
6367 6805 do {
6368 - const response = await (0, import_api_fetch8.default)({
6806 + const response = await (0, import_api_fetch9.default)({
6369 6807 path: (0, import_url6.addQueryArgs)(path, { page, per_page: 100 }),
6370 6808 parse: false
6371 6809 });
6372 6810 const pageRecords = Object.values(await response.json());
6373 - totalPages = parseInt(
6374 - response.headers.get("X-WP-TotalPages")
6375 - );
6811 + const pageMeta = getPaginationMeta(response.headers);
6812 + totalPages = pageMeta.totalPages ?? 1;
6376 6813 if (!meta) {
6377 6814 meta = {
6378 - totalItems: parseInt(
6379 - response.headers.get("X-WP-Total")
6380 - ),
6815 + totalItems: pageMeta.totalItems,
6381 6816 totalPages: 1
6382 6817 };
6383 6818 }
6384 6819 records.push(...pageRecords);
@@ -6399,9 +6834,9 @@
6399 6834 });
6400 6835 page++;
6401 6836 } while (page <= totalPages);
6402 6837 } else {
6403 - records = Object.values(await (0, import_api_fetch8.default)({ path }));
6838 + records = Object.values(await (0, import_api_fetch9.default)({ path }));
6404 6839 meta = {
6405 6840 totalItems: records.length,
6406 6841 totalPages: 1
6407 6842 };
@@ -6423,9 +6858,9 @@
6423 6858 refetchRecords: async () => {
6424 6859 dispatch3.receiveEntityRecords(
6425 6860 kind,
6426 6861 name,
6427 - await (0, import_api_fetch8.default)({ path, parse: true }),
6862 + await (0, import_api_fetch9.default)({ path, parse: true }),
6428 6863 query
6429 6864 );
6430 6865 }
6431 6866 }
@@ -6461,13 +6896,12 @@
6461 6896 }));
6462 6897 const canUserResolutionsArgs = [];
6463 6898 const receiveUserPermissionArgs = {};
6464 6899 for (const targetHint of targetHints) {
6900 + canUserResolutionsArgs.push([
6901 + { kind, name, id: targetHint.id }
6902 + ]);
6465 6903 for (const action of ALLOWED_RESOURCE_ACTIONS) {
6466 - canUserResolutionsArgs.push([
6467 - action,
6468 - { kind, name, id: targetHint.id }
6469 - ]);
6470 6904 receiveUserPermissionArgs[getUserPermissionCacheKey(action, {
6471 6905 kind,
6472 6906 name,
6473 6907 id: targetHint.id
@@ -6508,9 +6942,9 @@
6508 6942 };
6509 6943 var getThemeSupports2 = forward_resolver_default("getCurrentTheme");
6510 6944 var getEmbedPreview2 = (url) => async ({ dispatch: dispatch3 }) => {
6511 6945 try {
6512 - const embedProxyResponse = await (0, import_api_fetch8.default)({
6946 + const embedProxyResponse = await (0, import_api_fetch9.default)({
6513 6947 path: (0, import_url6.addQueryArgs)("/oembed/1.0/proxy", { url })
6514 6948 });
6515 6949 dispatch3.receiveEmbedPreview(url, embedProxyResponse);
6516 6950 } catch {
@@ -6516,26 +6950,9 @@
6516 6950 } catch {
6517 6951 dispatch3.receiveEmbedPreview(url, false);
6518 6952 }
6519 6953 };
6520 - var canUser2 = (requestedAction, resource, id) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
6521 - if (!ALLOWED_RESOURCE_ACTIONS.includes(requestedAction)) {
6522 - throw new Error(`'${requestedAction}' is not a valid action.`);
6523 - }
6524 - const { hasStartedResolution } = registry.select(STORE_NAME);
6525 - for (const relatedAction of ALLOWED_RESOURCE_ACTIONS) {
6526 - if (relatedAction === requestedAction) {
6527 - continue;
6528 - }
6529 - const isAlreadyResolving = hasStartedResolution("canUser", [
6530 - relatedAction,
6531 - resource,
6532 - id
6533 - ]);
6534 - if (isAlreadyResolving) {
6535 - return;
6536 - }
6537 - }
6954 + var canUser2 = (resource, id) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6538 6955 let resourcePath = null;
6539 6956 if (typeof resource === "object") {
6540 6957 if (!resource.kind || !resource.name) {
6541 6958 throw new Error("The entity resource object is not valid.");
@@ -6554,9 +6971,9 @@
6554 6971 resourcePath = `/wp/v2/${resource}` + (id ? "/" + id : "");
6555 6972 }
6556 6973 let response;
6557 6974 try {
6558 - response = await (0, import_api_fetch8.default)({
6975 + response = await (0, import_api_fetch9.default)({
6559 6976 path: resourcePath,
6560 6977 method: "OPTIONS",
6561 6978 parse: false
6562 6979 });
@@ -6566,22 +6983,16 @@
6566 6983 const permissions = getUserPermissionsFromAllowHeader(
6567 6984 response.headers?.get("allow")
6568 6985 );
6569 6986 const receiveUserPermissionArgs = {};
6570 - const canUserResolutionsArgs = [];
6571 6987 for (const action of ALLOWED_RESOURCE_ACTIONS) {
6572 6988 receiveUserPermissionArgs[getUserPermissionCacheKey(action, resource, id)] = permissions[action];
6573 - if (action !== requestedAction) {
6574 - canUserResolutionsArgs.push([action, resource, id]);
6575 - }
6576 6989 }
6577 - registry.batch(() => {
6578 - dispatch3.receiveUserPermissions(receiveUserPermissionArgs);
6579 - dispatch3.finishResolutions("canUser", canUserResolutionsArgs);
6580 - });
6990 + dispatch3.receiveUserPermissions(receiveUserPermissionArgs);
6581 6991 };
6582 - var canUserEditEntityRecord2 = (kind, name, recordId) => async ({ dispatch: dispatch3 }) => {
6583 - await dispatch3(canUser2("update", { kind, name, id: recordId }));
6992 + canUser2.getResolutionArgs = (action, resource, id) => [resource, id];
6993 + var canUserEditEntityRecord2 = (kind, name, recordId) => async ({ resolveSelect: resolveSelect2 }) => {
6994 + await resolveSelect2.canUser("update", { kind, name, id: recordId });
6584 6995 };
6585 6996 var getAutosaves2 = (postType, postId) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6586 6997 const {
6587 6998 rest_base: restBase,
@@ -6590,9 +7001,9 @@
6590 7001 } = await resolveSelect2.getPostType(postType);
6591 7002 if (!supports?.autosave) {
6592 7003 return;
6593 7004 }
6594 - const autosaves2 = await (0, import_api_fetch8.default)({
7005 + const autosaves2 = await (0, import_api_fetch9.default)({
6595 7006 path: `/${restNamespace}/${restBase}/${postId}/autosaves?context=edit`
6596 7007 });
6597 7008 if (autosaves2 && autosaves2.length) {
6598 7009 dispatch3.receiveAutosaves(postId, autosaves2);
@@ -6618,9 +7029,9 @@
6618 7029 }
6619 7030 };
6620 7031 var __experimentalGetCurrentThemeBaseGlobalStyles2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
6621 7032 const currentTheme2 = await resolveSelect2.getCurrentTheme();
6622 - const themeGlobalStyles = await (0, import_api_fetch8.default)({
7033 + const themeGlobalStyles = await (0, import_api_fetch9.default)({
6623 7034 path: `/wp/v2/global-styles/themes/${currentTheme2.stylesheet}?context=view`
6624 7035 });
6625 7036 dispatch3.__experimentalReceiveThemeBaseGlobalStyles(
6626 7037 currentTheme2.stylesheet,
@@ -6628,9 +7039,9 @@
6628 7039 );
6629 7040 };
6630 7041 var __experimentalGetCurrentThemeGlobalStylesVariations2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
6631 7042 const currentTheme2 = await resolveSelect2.getCurrentTheme();
6632 - const variations = await (0, import_api_fetch8.default)({
7043 + const variations = await (0, import_api_fetch9.default)({
6633 7044 path: `/wp/v2/global-styles/themes/${currentTheme2.stylesheet}/variations?context=view`
6634 7045 });
6635 7046 dispatch3.__experimentalReceiveThemeGlobalStyleVariations(
6636 7047 currentTheme2.stylesheet,
@@ -6645,9 +7056,9 @@
6645 7056 globalStylesId
6646 7057 ) : void 0;
6647 7058 const revisionsURL = record?._links?.["version-history"]?.[0]?.href;
6648 7059 if (revisionsURL) {
6649 - const resetRevisions = await (0, import_api_fetch8.default)({
7060 + const resetRevisions = await (0, import_api_fetch9.default)({
6650 7061 url: revisionsURL
6651 7062 });
6652 7063 const revisions = resetRevisions?.map(
6653 7064 (revision) => Object.fromEntries(
@@ -6670,9 +7081,9 @@
6670 7081 const patterns = await fetchBlockPatterns();
6671 7082 dispatch3({ type: "RECEIVE_BLOCK_PATTERNS", patterns });
6672 7083 };
6673 7084 var getBlockPatternCategories2 = () => async ({ dispatch: dispatch3 }) => {
6674 - const categories = await (0, import_api_fetch8.default)({
7085 + const categories = await (0, import_api_fetch9.default)({
6675 7086 path: "/wp/v2/block-patterns/categories"
6676 7087 });
6677 7088 dispatch3({ type: "RECEIVE_BLOCK_PATTERN_CATEGORIES", categories });
6678 7089 };
@@ -6687,9 +7098,9 @@
6687 7098 }
6688 7099 );
6689 7100 const mappedPatternCategories = patternCategories?.map((userCategory) => ({
6690 7101 ...userCategory,
6691 - label: (0, import_html_entities2.decodeEntities)(userCategory.name),
7102 + label: (0, import_html_entities3.decodeEntities)(userCategory.name),
6692 7103 name: userCategory.slug
6693 7104 })) || [];
6694 7105 dispatch3({
6695 7106 type: "RECEIVE_USER_PATTERN_CATEGORIES",
@@ -6696,9 +7107,9 @@
6696 7107 patternCategories: mappedPatternCategories
6697 7108 });
6698 7109 };
6699 7110 var getNavigationFallbackId2 = () => async ({ dispatch: dispatch3, select: select5, registry }) => {
6700 - const fallback = await (0, import_api_fetch8.default)({
7111 + const fallback = await (0, import_api_fetch9.default)({
6701 7112 path: (0, import_url6.addQueryArgs)("/wp-block-editor/v1/navigation-fallback", {
6702 7113 _embed: true
6703 7114 })
6704 7115 });
@@ -6728,13 +7139,13 @@
6728 7139 ]);
6729 7140 });
6730 7141 };
6731 7142 var getDefaultTemplateId2 = (query) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
6732 - const template = await (0, import_api_fetch8.default)({
7143 + const template = await (0, import_api_fetch9.default)({
6733 7144 path: (0, import_url6.addQueryArgs)("/wp/v2/templates/lookup", query)
6734 7145 });
6735 7146 await resolveSelect2.getEntitiesConfig("postType");
6736 - const id = window?.__experimentalTemplateActivate ? template?.wp_id || template?.id : template?.id;
7147 + const id = template?.id;
6737 7148 registry.batch(() => {
6738 7149 dispatch3.receiveDefaultTemplateId(query, id || "");
6739 7150 if (id) {
6740 7151 template.id = id;
@@ -6750,12 +7161,9 @@
6750 7161 ]);
6751 7162 }
6752 7163 });
6753 7164 };
6754 - getDefaultTemplateId2.shouldInvalidate = (action) => {
6755 - return action.type === "RECEIVE_ITEMS" && action.kind === "root" && action.name === "site" && !!action.persistedEdits;
6756 - };
6757 - var getRevisions2 = (kind, name, recordKey, query = {}) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
7165 + var getRevisions2 = (kind, name, recordKey, query = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6758 7166 const configs = await resolveSelect2.getEntitiesConfig(kind);
6759 7167 const entityConfig = configs.find(
6760 7168 (config) => config.name === name && config.kind === kind
6761 7169 );
@@ -6787,9 +7195,9 @@
6787 7195 let records, response;
6788 7196 const meta = {};
6789 7197 const isPaginated = entityConfig.supportsPagination && query.per_page !== -1;
6790 7198 try {
6791 - response = await (0, import_api_fetch8.default)({ path, parse: !isPaginated });
7199 + response = await (0, import_api_fetch9.default)({ path, parse: !isPaginated });
6792 7200 } catch {
6793 7201 return;
6794 7202 }
6795 7203 if (response) {
@@ -6794,11 +7202,11 @@
6794 7202 }
6795 7203 if (response) {
6796 7204 if (isPaginated) {
6797 7205 records = Object.values(await response.json());
6798 - meta.totalItems = parseInt(
6799 - response.headers.get("X-WP-Total")
6800 - );
7206 + meta.totalItems = getPaginationMeta(
7207 + response.headers
7208 + ).totalItems;
6801 7209 } else {
6802 7210 records = Object.values(response);
6803 7211 }
6804 7212 if (query._fields) {
@@ -6810,32 +7218,27 @@
6810 7218 });
6811 7219 return record;
6812 7220 });
6813 7221 }
6814 - registry.batch(() => {
6815 - dispatch3.receiveRevisions(
6816 - kind,
6817 - name,
6818 - recordKey,
6819 - records,
6820 - query,
6821 - false,
6822 - meta
6823 - );
6824 - const key = entityConfig.revisionKey || DEFAULT_ENTITY_KEY;
6825 - const normalizedQuery = normalizeQueryForResolution(rawQuery);
6826 - const resolutionsArgs = records.filter((record) => record[key]).map((record) => [
6827 - kind,
6828 - name,
6829 - recordKey,
6830 - record[key],
6831 - normalizedQuery
6832 - ]);
6833 - dispatch3.finishResolutions(
6834 - "getRevision",
6835 - resolutionsArgs
6836 - );
6837 - });
7222 + await dispatch3.receiveRevisions(
7223 + kind,
7224 + name,
7225 + recordKey,
7226 + records,
7227 + query,
7228 + false,
7229 + meta
7230 + );
7231 + const key = entityConfig.revisionKey || DEFAULT_ENTITY_KEY;
7232 + const normalizedQuery = normalizeQueryForResolution(rawQuery);
7233 + const resolutionsArgs = records.filter((record) => record[key]).map((record) => [
7234 + kind,
7235 + name,
7236 + recordKey,
7237 + record[key],
7238 + normalizedQuery
7239 + ]);
7240 + dispatch3.finishResolutions("getRevision", resolutionsArgs);
6838 7241 }
6839 7242 } finally {
6840 7243 dispatch3.__unstableReleaseStoreLock(lock2);
6841 7244 }
@@ -6882,14 +7285,14 @@
6882 7285 query
6883 7286 );
6884 7287 let record;
6885 7288 try {
6886 - record = await (0, import_api_fetch8.default)({ path });
7289 + record = await (0, import_api_fetch9.default)({ path });
6887 7290 } catch {
6888 7291 return;
6889 7292 }
6890 7293 if (record) {
6891 - dispatch3.receiveRevisions(
7294 + await dispatch3.receiveRevisions(
6892 7295 kind,
6893 7296 name,
6894 7297 recordKey,
6895 7298 record,
@@ -6906,9 +7309,9 @@
6906 7309 const {
6907 7310 rest_namespace: restNamespace = "wp/v2",
6908 7311 rest_base: restBase
6909 7312 } = await resolveSelect2.getPostType(postType) || {};
6910 - options = await (0, import_api_fetch8.default)({
7313 + options = await (0, import_api_fetch9.default)({
6911 7314 path: `${restNamespace}/${restBase}/?context=edit`,
6912 7315 method: "OPTIONS"
6913 7316 });
6914 7317 } catch {
@@ -6937,22 +7340,27 @@
6937 7340 } catch {
6938 7341 }
6939 7342 };
6940 7343 var getEditorSettings2 = () => async ({ dispatch: dispatch3 }) => {
6941 - const settings = await (0, import_api_fetch8.default)({
7344 + const settings = await (0, import_api_fetch9.default)({
6942 7345 path: "/wp-block-editor/v1/settings"
6943 7346 });
6944 7347 dispatch3.receiveEditorSettings(settings);
6945 7348 };
6946 7349 var getEditorAssets2 = () => async ({ dispatch: dispatch3 }) => {
6947 - const assets = await (0, import_api_fetch8.default)({
7350 + const assets = await (0, import_api_fetch9.default)({
6948 7351 path: "/wp-block-editor/v1/assets"
6949 7352 });
6950 7353 dispatch3.receiveEditorAssets(assets);
6951 7354 };
6952 - var getViewConfig2 = (kind, name) => async ({ dispatch: dispatch3 }) => {
6953 - const config = await (0, import_api_fetch8.default)({
6954 - path: (0, import_url6.addQueryArgs)("/wp/v2/view-config", { kind, name })
7355 + var getViewConfig2 = (kind, name, options = {}) => async ({ dispatch: dispatch3 }) => {
7356 + const query = { kind, name };
7357 + const fields = get_normalized_comma_separable_default(options.fields);
7358 + if (fields?.length) {
7359 + query._fields = fields.join(",");
7360 + }
7361 + const config = await (0, import_api_fetch9.default)({
7362 + path: (0, import_url6.addQueryArgs)("/wp/v2/view-config", query)
6955 7363 });
6956 7364 dispatch3.receiveViewConfig(kind, name, config);
6957 7365 };
6958 7366
@@ -7039,9 +7447,9 @@
7039 7447 const node = getNode(newTree, storePath);
7040 7448 node.locks = [...node.locks, lock2];
7041 7449 return {
7042 7450 ...state,
7043 - requests: state.requests.filter((r) => r !== request),
7451 + requests: state.requests.filter((r2) => r2 !== request),
7044 7452 tree: newTree
7045 7453 };
7046 7454 }
7047 7455 case "RELEASE_LOCK": {
@@ -7161,9 +7569,17 @@
7161 7569 ...parent?.[kind],
7162 7570 [name]: id
7163 7571 }
7164 7572 },
7165 - ...revisionId !== void 0 && { revisionId }
7573 + ...revisionId !== void 0 && kind && {
7574 + revision: {
7575 + ...parent?.revision,
7576 + [kind]: {
7577 + ...parent?.revision?.[kind],
7578 + [name]: revisionId
7579 + }
7580 + }
7581 + }
7166 7582 }),
7167 7583 [parent, kind, name, id, revisionId]
7168 7584 );
7169 7585 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EntityContext.Provider, { value: childContext, children });
@@ -7173,79 +7589,8 @@
7173 7589 var import_data11 = __toESM(require_data(), 1);
7174 7590 var import_deprecated4 = __toESM(require_deprecated(), 1);
7175 7591 var import_element3 = __toESM(require_element(), 1);
7176 7592
7177 - // packages/core-data/build-module/hooks/use-query-select.mjs
7178 - var import_data10 = __toESM(require_data(), 1);
7179 -
7180 - // node_modules/memize/dist/index.js
7181 - function memize(fn, options) {
7182 - var size = 0;
7183 - var head;
7184 - var tail;
7185 - options = options || {};
7186 - function memoized() {
7187 - var node = head, len = arguments.length, args, i;
7188 - searchCache: while (node) {
7189 - if (node.args.length !== arguments.length) {
7190 - node = node.next;
7191 - continue;
7192 - }
7193 - for (i = 0; i < len; i++) {
7194 - if (node.args[i] !== arguments[i]) {
7195 - node = node.next;
7196 - continue searchCache;
7197 - }
7198 - }
7199 - if (node !== head) {
7200 - if (node === tail) {
7201 - tail = node.prev;
7202 - }
7203 - node.prev.next = node.next;
7204 - if (node.next) {
7205 - node.next.prev = node.prev;
7206 - }
7207 - node.next = head;
7208 - node.prev = null;
7209 - head.prev = node;
7210 - head = node;
7211 - }
7212 - return node.val;
7213 - }
7214 - args = new Array(len);
7215 - for (i = 0; i < len; i++) {
7216 - args[i] = arguments[i];
7217 - }
7218 - node = {
7219 - args,
7220 - // Generate the result from original function
7221 - val: fn.apply(null, args)
7222 - };
7223 - if (head) {
7224 - head.prev = node;
7225 - node.next = head;
7226 - } else {
7227 - tail = node;
7228 - }
7229 - if (size === /** @type {MemizeOptions} */
7230 - options.maxSize) {
7231 - tail = /** @type {MemizeCacheNode} */
7232 - tail.prev;
7233 - tail.next = null;
7234 - } else {
7235 - size++;
7236 - }
7237 - head = node;
7238 - return node.val;
7239 - }
7240 - memoized.clear = function() {
7241 - head = null;
7242 - tail = null;
7243 - size = 0;
7244 - };
7245 - return memoized;
7246 - }
7247 -
7248 7593 // packages/core-data/build-module/hooks/constants.mjs
7249 7594 var Status = /* @__PURE__ */ ((Status2) => {
7250 7595 Status2["Idle"] = "IDLE";
7251 7596 Status2["Resolving"] = "RESOLVING";
@@ -7253,62 +7598,31 @@
7253 7598 Status2["Success"] = "SUCCESS";
7254 7599 return Status2;
7255 7600 })(Status || {});
7256 7601
7257 - // packages/core-data/build-module/hooks/use-query-select.mjs
7258 - var META_SELECTORS = [
7259 - "getIsResolving",
7260 - "hasStartedResolution",
7261 - "hasFinishedResolution",
7262 - "isResolving",
7263 - "getCachedResolvers"
7264 - ];
7265 - function useQuerySelect(mapQuerySelect, deps) {
7266 - return (0, import_data10.useSelect)((select5, registry) => {
7267 - const resolve = (store2) => enrichSelectors(select5(store2));
7268 - return mapQuerySelect(resolve, registry);
7269 - }, deps);
7602 + // packages/core-data/build-module/hooks/utils.mjs
7603 + function getResolutionStatus(resolutionStatus) {
7604 + let status;
7605 + switch (resolutionStatus) {
7606 + case "resolving":
7607 + status = Status.Resolving;
7608 + break;
7609 + case "finished":
7610 + status = Status.Success;
7611 + break;
7612 + case "error":
7613 + status = Status.Error;
7614 + break;
7615 + default:
7616 + status = Status.Idle;
7617 + }
7618 + return {
7619 + status,
7620 + isResolving: status === Status.Resolving,
7621 + hasStarted: status !== Status.Idle,
7622 + hasResolved: status === Status.Success || status === Status.Error
7623 + };
7270 7624 }
7271 - var enrichSelectors = memize(((selectors) => {
7272 - const resolvers = {};
7273 - for (const selectorName in selectors) {
7274 - if (META_SELECTORS.includes(selectorName)) {
7275 - continue;
7276 - }
7277 - Object.defineProperty(resolvers, selectorName, {
7278 - get: () => (...args) => {
7279 - const data = selectors[selectorName](...args);
7280 - const resolutionStatus = selectors.getResolutionState(
7281 - selectorName,
7282 - args
7283 - )?.status;
7284 - let status;
7285 - switch (resolutionStatus) {
7286 - case "resolving":
7287 - status = Status.Resolving;
7288 - break;
7289 - case "finished":
7290 - status = Status.Success;
7291 - break;
7292 - case "error":
7293 - status = Status.Error;
7294 - break;
7295 - case void 0:
7296 - status = Status.Idle;
7297 - break;
7298 - }
7299 - return {
7300 - data,
7301 - status,
7302 - isResolving: status === Status.Resolving,
7303 - hasStarted: status !== Status.Idle,
7304 - hasResolved: status === Status.Success || status === Status.Error
7305 - };
7306 - }
7307 - });
7308 - }
7309 - return resolvers;
7310 - }));
7311 7625
7312 7626 // packages/core-data/build-module/hooks/use-entity-record.mjs
7313 7627 var EMPTY_OBJECT3 = {};
7314 7628 function useEntityRecord(kind, name, recordId, options = { enabled: true }) {
@@ -7322,54 +7636,56 @@
7322 7636 })
7323 7637 }),
7324 7638 [editEntityRecord2, kind, name, recordId, saveEditedEntityRecord2]
7325 7639 );
7326 - const { editedRecord, hasEdits, edits } = (0, import_data11.useSelect)(
7640 + const { record, editedRecord, hasEdits, edits, ...resolution } = (0, import_data11.useSelect)(
7327 7641 (select5) => {
7328 7642 if (!options.enabled) {
7329 7643 return {
7644 + record: null,
7330 7645 editedRecord: EMPTY_OBJECT3,
7331 7646 hasEdits: false,
7332 - edits: EMPTY_OBJECT3
7647 + edits: EMPTY_OBJECT3,
7648 + ...getResolutionStatus()
7333 7649 };
7334 7650 }
7651 + const storeSelectors = select5(store);
7652 + const resolutionStatus = storeSelectors.getResolutionState(
7653 + "getEntityRecord",
7654 + [kind, name, recordId]
7655 + )?.status;
7335 7656 return {
7336 - editedRecord: select5(store).getEditedEntityRecord(
7657 + record: storeSelectors.getEntityRecord(
7337 7658 kind,
7338 7659 name,
7339 7660 recordId
7661 + ) ?? null,
7662 + editedRecord: storeSelectors.getEditedEntityRecord(
7663 + kind,
7664 + name,
7665 + recordId
7340 7666 ),
7341 - hasEdits: select5(store).hasEditsForEntityRecord(
7667 + hasEdits: storeSelectors.hasEditsForEntityRecord(
7342 7668 kind,
7343 7669 name,
7344 7670 recordId
7345 7671 ),
7346 - edits: select5(store).getEntityRecordNonTransientEdits(
7672 + edits: storeSelectors.getEntityRecordNonTransientEdits(
7347 7673 kind,
7348 7674 name,
7349 7675 recordId
7350 - )
7676 + ),
7677 + ...getResolutionStatus(resolutionStatus)
7351 7678 };
7352 7679 },
7353 7680 [kind, name, recordId, options.enabled]
7354 7681 );
7355 - const { data: record, ...querySelectRest } = useQuerySelect(
7356 - (query) => {
7357 - if (!options.enabled) {
7358 - return {
7359 - data: null
7360 - };
7361 - }
7362 - return query(store).getEntityRecord(kind, name, recordId);
7363 - },
7364 - [kind, name, recordId, options.enabled]
7365 - );
7366 7682 return {
7367 7683 record,
7368 7684 editedRecord,
7369 7685 hasEdits,
7370 7686 edits,
7371 - ...querySelectRest,
7687 + ...resolution,
7372 7688 ...mutations
7373 7689 };
7374 7690 }
7375 7691 function useDeprecatedEntityRecord(kind, name, recordId, options) {
@@ -7387,39 +7703,41 @@
7387 7703 var import_element4 = __toESM(require_element(), 1);
7388 7704 var EMPTY_ARRAY = [];
7389 7705 function useEntityRecords(kind, name, queryArgs = {}, options = { enabled: true }) {
7390 7706 const queryAsString = (0, import_url7.addQueryArgs)("", queryArgs);
7391 - const { data: records, ...rest } = useQuerySelect(
7392 - (query) => {
7707 + const { records, totalItems, totalPages, ...rest } = (0, import_data12.useSelect)(
7708 + (select5) => {
7393 7709 if (!options.enabled) {
7394 7710 return {
7395 7711 // Avoiding returning a new reference on every execution.
7396 - data: EMPTY_ARRAY
7397 - };
7398 - }
7399 - return query(store).getEntityRecords(kind, name, queryArgs);
7400 - },
7401 - [kind, name, queryAsString, options.enabled]
7402 - );
7403 - const { totalItems, totalPages } = (0, import_data12.useSelect)(
7404 - (select5) => {
7405 - if (!options.enabled) {
7406 - return {
7712 + records: EMPTY_ARRAY,
7407 7713 totalItems: null,
7408 - totalPages: null
7714 + totalPages: null,
7715 + ...getResolutionStatus()
7409 7716 };
7410 7717 }
7718 + const storeSelectors = select5(store);
7719 + const resolutionStatus = storeSelectors.getResolutionState(
7720 + "getEntityRecords",
7721 + [kind, name, queryArgs]
7722 + )?.status;
7411 7723 return {
7412 - totalItems: select5(store).getEntityRecordsTotalItems(
7724 + records: storeSelectors.getEntityRecords(
7413 7725 kind,
7414 7726 name,
7415 7727 queryArgs
7416 7728 ),
7417 - totalPages: select5(store).getEntityRecordsTotalPages(
7729 + totalItems: storeSelectors.getEntityRecordsTotalItems(
7418 7730 kind,
7419 7731 name,
7420 7732 queryArgs
7421 - )
7733 + ),
7734 + totalPages: storeSelectors.getEntityRecordsTotalPages(
7735 + kind,
7736 + name,
7737 + queryArgs
7738 + ),
7739 + ...getResolutionStatus(resolutionStatus)
7422 7740 };
7423 7741 },
7424 7742 [kind, name, queryAsString, options.enabled]
7425 7743 );
@@ -7462,9 +7780,9 @@
7462 7780 options
7463 7781 );
7464 7782 const ids = (0, import_element4.useMemo)(
7465 7783 () => data?.map(
7466 - // @ts-ignore
7784 + // @ts-expect-error `data` is `unknown[]`, so the callback signature does not line up.
7467 7785 (record) => record[entityConfig?.key ?? "id"]
7468 7786 ) ?? [],
7469 7787 [data, entityConfig?.key]
7470 7788 );
@@ -7478,9 +7796,9 @@
7478 7796 [ids, kind, name]
7479 7797 );
7480 7798 const dataWithPermissions = (0, import_element4.useMemo)(
7481 7799 () => data?.map((record, index) => ({
7482 - // @ts-ignore
7800 + // @ts-expect-error `record` is `unknown`, which cannot be spread.
7483 7801 ...record,
7484 7802 permissions: permissions[index]
7485 7803 })) ?? [],
7486 7804 [data, permissions]
@@ -7490,8 +7808,118 @@
7490 7808
7491 7809 // packages/core-data/build-module/hooks/use-resource-permissions.mjs
7492 7810 var import_deprecated6 = __toESM(require_deprecated(), 1);
7493 7811 var import_warning = __toESM(require_warning(), 1);
7812 +
7813 + // packages/core-data/build-module/hooks/use-query-select.mjs
7814 + var import_data13 = __toESM(require_data(), 1);
7815 +
7816 + // node_modules/memize/dist/index.js
7817 + function memize(fn, options) {
7818 + var size = 0;
7819 + var head;
7820 + var tail;
7821 + options = options || {};
7822 + function memoized() {
7823 + var node = head, len = arguments.length, args, i;
7824 + searchCache: while (node) {
7825 + if (node.args.length !== arguments.length) {
7826 + node = node.next;
7827 + continue;
7828 + }
7829 + for (i = 0; i < len; i++) {
7830 + if (node.args[i] !== arguments[i]) {
7831 + node = node.next;
7832 + continue searchCache;
7833 + }
7834 + }
7835 + if (node !== head) {
7836 + if (node === tail) {
7837 + tail = node.prev;
7838 + }
7839 + node.prev.next = node.next;
7840 + if (node.next) {
7841 + node.next.prev = node.prev;
7842 + }
7843 + node.next = head;
7844 + node.prev = null;
7845 + head.prev = node;
7846 + head = node;
7847 + }
7848 + return node.val;
7849 + }
7850 + args = new Array(len);
7851 + for (i = 0; i < len; i++) {
7852 + args[i] = arguments[i];
7853 + }
7854 + node = {
7855 + args,
7856 + // Generate the result from original function
7857 + val: fn.apply(null, args)
7858 + };
7859 + if (head) {
7860 + head.prev = node;
7861 + node.next = head;
7862 + } else {
7863 + tail = node;
7864 + }
7865 + if (size === /** @type {MemizeOptions} */
7866 + options.maxSize) {
7867 + tail = /** @type {MemizeCacheNode} */
7868 + tail.prev;
7869 + tail.next = null;
7870 + } else {
7871 + size++;
7872 + }
7873 + head = node;
7874 + return node.val;
7875 + }
7876 + memoized.clear = function() {
7877 + head = null;
7878 + tail = null;
7879 + size = 0;
7880 + };
7881 + return memoized;
7882 + }
7883 +
7884 + // packages/core-data/build-module/hooks/use-query-select.mjs
7885 + var META_SELECTORS = [
7886 + "getIsResolving",
7887 + "hasStartedResolution",
7888 + "hasFinishedResolution",
7889 + "isResolving",
7890 + "getCachedResolvers"
7891 + ];
7892 + function useQuerySelect(mapQuerySelect, deps) {
7893 + return (0, import_data13.useSelect)((select5, registry) => {
7894 + const resolve = (store2) => enrichSelectors(select5(store2));
7895 + return mapQuerySelect(resolve, registry);
7896 + }, deps);
7897 + }
7898 + var enrichSelectors = memize(((selectors) => {
7899 + const resolvers = {};
7900 + for (const selectorName in selectors) {
7901 + if (META_SELECTORS.includes(selectorName)) {
7902 + continue;
7903 + }
7904 + Object.defineProperty(resolvers, selectorName, {
7905 + get: () => (...args) => {
7906 + const data = selectors[selectorName](...args);
7907 + const resolutionStatus = selectors.getResolutionState(
7908 + selectorName,
7909 + args
7910 + )?.status;
7911 + return {
7912 + data,
7913 + ...getResolutionStatus(resolutionStatus)
7914 + };
7915 + }
7916 + });
7917 + }
7918 + return resolvers;
7919 + }));
7920 +
7921 + // packages/core-data/build-module/hooks/use-resource-permissions.mjs
7494 7922 function useResourcePermissions(resource, id) {
7495 7923 const isEntity = typeof resource === "object";
7496 7924 const resourceAsString = isEntity ? JSON.stringify(resource) : resource;
7497 7925 if (isEntity && typeof id !== "undefined") {
@@ -7557,10 +7985,10 @@
7557 7985 }
7558 7986
7559 7987 // packages/core-data/build-module/hooks/use-entity-block-editor.mjs
7560 7988 var import_element6 = __toESM(require_element(), 1);
7561 - var import_data13 = __toESM(require_data(), 1);
7562 - var import_blocks5 = __toESM(require_blocks(), 1);
7989 + var import_data14 = __toESM(require_data(), 1);
7990 + var import_blocks6 = __toESM(require_blocks(), 1);
7563 7991
7564 7992 // packages/core-data/build-module/hooks/use-entity-id.mjs
7565 7993 var import_element5 = __toESM(require_element(), 1);
7566 7994 function useEntityId(kind, name) {
@@ -7569,16 +7997,17 @@
7569 7997 }
7570 7998
7571 7999 // packages/core-data/build-module/footnotes/index.mjs
7572 8000 var import_rich_text4 = __toESM(require_rich_text(), 1);
8001 + var import_warning2 = __toESM(require_warning(), 1);
7573 8002
7574 8003 // packages/core-data/build-module/footnotes/get-rich-text-values-cached.mjs
7575 - var import_block_editor5 = __toESM(require_block_editor(), 1);
8004 + var import_block_editor6 = __toESM(require_block_editor(), 1);
7576 8005 var unlockedApis;
7577 8006 var cache = /* @__PURE__ */ new WeakMap();
7578 8007 function getRichTextValuesCached(block) {
7579 8008 if (!unlockedApis) {
7580 - unlockedApis = unlock(import_block_editor5.privateApis);
8009 + unlockedApis = unlock(import_block_editor6.privateApis);
7581 8010 }
7582 8011 if (!cache.has(block)) {
7583 8012 const values = unlockedApis.getRichTextValues([block]);
7584 8013 cache.set(block, values);
@@ -7619,9 +8048,19 @@
7619 8048 if (meta.footnotes === void 0) {
7620 8049 return output;
7621 8050 }
7622 8051 const newOrder = getFootnotesOrder(blocks);
7623 - const footnotes = meta.footnotes ? JSON.parse(meta.footnotes) : [];
8052 + let parsed;
8053 + try {
8054 + parsed = JSON.parse(meta.footnotes || "[]");
8055 + } catch {
8056 + }
8057 + let footnotes = [];
8058 + if (Array.isArray(parsed)) {
8059 + footnotes = parsed;
8060 + } else {
8061 + (0, import_warning2.default)("Footnotes post meta is not a JSON array; ignoring it.");
8062 + }
7624 8063 const currentOrder = footnotes.map((fn) => fn.id);
7625 8064 if (currentOrder.join("") === newOrder.join("")) {
7626 8065 return output;
7627 8066 }
@@ -7707,9 +8146,9 @@
7707 8146 var EMPTY_ARRAY2 = [];
7708 8147 function useEntityBlockEditor(kind, name, { id: _id } = {}) {
7709 8148 const providerId = useEntityId(kind, name);
7710 8149 const id = _id ?? providerId;
7711 - const { content, editedBlocks, meta } = (0, import_data13.useSelect)(
8150 + const { content, editedBlocks, meta } = (0, import_data14.useSelect)(
7712 8151 (select5) => {
7713 8152 if (!id) {
7714 8153 return {};
7715 8154 }
@@ -7722,9 +8161,9 @@
7722 8161 };
7723 8162 },
7724 8163 [kind, name, id]
7725 8164 );
7726 - const { __unstableCreateUndoLevel: __unstableCreateUndoLevel2, editEntityRecord: editEntityRecord2 } = (0, import_data13.useDispatch)(STORE_NAME);
8165 + const { __unstableCreateUndoLevel: __unstableCreateUndoLevel2, editEntityRecord: editEntityRecord2 } = (0, import_data14.useDispatch)(STORE_NAME);
7727 8166 const blocks = (0, import_element6.useMemo)(() => {
7728 8167 if (!id) {
7729 8168 return void 0;
7730 8169 }
@@ -7733,16 +8172,12 @@
7733 8172 }
7734 8173 if (!content || typeof content !== "string") {
7735 8174 return EMPTY_ARRAY2;
7736 8175 }
7737 - const cacheKey = getCacheKey(kind, name, id);
7738 - const cached = parsedBlocksCache.get(cacheKey);
7739 - let _blocks;
7740 - if (cached && cached.content === content) {
7741 - _blocks = cached.blocks;
7742 - } else {
7743 - _blocks = (0, import_blocks5.parse)(content);
7744 - parsedBlocksCache.set(cacheKey, { content, blocks: _blocks });
8176 + let _blocks = getCachedBlocks(kind, name, id, content);
8177 + if (!_blocks) {
8178 + _blocks = (0, import_blocks6.parse)(content);
8179 + setCachedBlocks(kind, name, id, content, _blocks);
7745 8180 }
7746 8181 return _blocks;
7747 8182 }, [kind, name, id, editedBlocks, content]);
7748 8183 const onChange = (0, import_element6.useCallback)(
@@ -7753,9 +8188,9 @@
7753 8188 }
7754 8189 const { selection, ...rest } = options;
7755 8190 const edits = {
7756 8191 selection,
7757 - content: ({ blocks: blocksForSerialization = [] }) => (0, import_blocks5.__unstableSerializeAndClean)(blocksForSerialization),
8192 + content: ({ blocks: blocksForSerialization = [] }) => (0, import_blocks6.__unstableSerializeAndClean)(blocksForSerialization),
7758 8193 ...updateFootnotesFromMeta(newBlocks, meta)
7759 8194 };
7760 8195 editEntityRecord2(kind, name, id, edits, {
7761 8196 isCached: false,
@@ -7790,39 +8225,37 @@
7790 8225 }
7791 8226
7792 8227 // packages/core-data/build-module/hooks/use-entity-prop.mjs
7793 8228 var import_element7 = __toESM(require_element(), 1);
7794 - var import_data14 = __toESM(require_data(), 1);
8229 + var import_data15 = __toESM(require_data(), 1);
8230 + var REVISION_QUERY = {
8231 + context: "edit",
8232 + _fields: "id,date,author,meta,title,excerpt,content.raw"
8233 + };
7795 8234 function useEntityProp(kind, name, prop, _id) {
7796 8235 const providerId = useEntityId(kind, name);
7797 8236 const id = _id ?? providerId;
7798 8237 const context = (0, import_element7.useContext)(EntityContext);
7799 - const revisionId = context?.revisionId;
7800 - const { value, fullValue } = (0, import_data14.useSelect)(
8238 + const revisionId = String(id) === String(providerId) ? context?.revision?.[kind]?.[name] : void 0;
8239 + const { value, fullValue } = (0, import_data15.useSelect)(
7801 8240 (select5) => {
7802 8241 if (revisionId) {
7803 - const revisions = select5(STORE_NAME).getRevisions(
8242 + const revision = select5(STORE_NAME).getRevision(
7804 8243 kind,
7805 8244 name,
7806 8245 id,
7807 - {
7808 - per_page: -1,
7809 - context: "edit",
7810 - _fields: "id,date,author,meta,title.raw,excerpt.raw,content.raw"
7811 - }
8246 + revisionId,
8247 + REVISION_QUERY
7812 8248 );
7813 - const entityConfig = select5(STORE_NAME).getEntityConfig(
7814 - kind,
7815 - name
7816 - );
7817 - const revKey = entityConfig?.revisionKey || DEFAULT_ENTITY_KEY;
7818 - const revision = revisions?.find(
7819 - (r) => r[revKey] === revisionId
7820 - );
7821 - return revision ? {
7822 - value: revision[prop]?.raw ?? revision[prop],
7823 - fullValue: revision[prop]
7824 - } : {};
8249 + const propValue = revision?.[prop];
8250 + if (propValue === void 0) {
8251 + return {};
8252 + }
8253 + const isRawAttribute = propValue !== null && typeof propValue === "object" && "raw" in propValue;
8254 + return {
8255 + value: isRawAttribute ? propValue.raw : propValue,
8256 + fullValue: propValue
8257 + };
7825 8258 }
7826 8259 const { getEntityRecord: getEntityRecord3, getEditedEntityRecord: getEditedEntityRecord3 } = select5(STORE_NAME);
7827 8260 const record = getEntityRecord3(kind, name, id);
7828 8261 const editedRecord = getEditedEntityRecord3(kind, name, id);
@@ -7832,9 +8265,9 @@
7832 8265 } : {};
7833 8266 },
7834 8267 [kind, name, id, prop, revisionId]
7835 8268 );
7836 - const { editEntityRecord: editEntityRecord2 } = (0, import_data14.useDispatch)(STORE_NAME);
8269 + const { editEntityRecord: editEntityRecord2 } = (0, import_data15.useDispatch)(STORE_NAME);
7837 8270 const setValue = (0, import_element7.useCallback)(
7838 8271 (newValue) => {
7839 8272 if (revisionId) {
7840 8273 return;
@@ -7866,12 +8299,14 @@
7866 8299 }),
7867 8300 isCurrentCollaboratorDisconnected: false
7868 8301 };
7869 8302 function getAwarenessState(awareness, newState) {
7870 - const activeCollaborators = newState ?? awareness.getCurrentState();
8303 + const activeCollaborators = (newState ?? awareness.getCurrentState()).filter(
8304 + (collaborator) => isCollaboratorInfo(collaborator.collaboratorInfo)
8305 + );
7871 8306 return {
7872 8307 activeCollaborators,
7873 - resolveSelection: (selection) => awareness.convertSelectionStateToAbsolute(selection),
8308 + resolveSelection: (selection, blocks) => awareness.convertSelectionStateToAbsolute(selection, blocks),
7874 8309 getDebugData: () => awareness.getDebugData(),
7875 8310 isCurrentCollaboratorDisconnected: activeCollaborators.find((collaborator) => collaborator.isMe)?.isConnected === false
7876 8311 };
7877 8312 }
@@ -7906,9 +8341,14 @@
7906 8341 function useActiveCollaborators(postId, postType) {
7907 8342 return usePostEditorAwarenessState(postId, postType).activeCollaborators;
7908 8343 }
7909 8344 function useResolvedSelection(postId, postType) {
7910 - return usePostEditorAwarenessState(postId, postType).resolveSelection;
8345 + const blocks = usePostContentBlocks();
8346 + const awarenessState = usePostEditorAwarenessState(postId, postType);
8347 + return (0, import_element8.useCallback)(
8348 + (selection) => awarenessState.resolveSelection(selection, blocks),
8349 + [blocks, awarenessState]
8350 + );
7911 8351 }
7912 8352 function useLastPostSave(postId, postType) {
7913 8353 const [lastSave, setLastSave] = (0, import_element8.useState)(null);
7914 8354 (0, import_element8.useEffect)(() => {
@@ -8021,12 +8461,700 @@
8021 8461 callback(lastPostSave, saver, prevPostSave ?? null);
8022 8462 }, [lastPostSave, prevPostSave, activeCollaborators, callback]);
8023 8463 }
8024 8464
8465 + // packages/icons/build-module/library/footer.mjs
8466 + var import_primitives = __toESM(require_primitives(), 1);
8467 + var import_jsx_runtime2 = __toESM(require_jsx_runtime(), 1);
8468 + var footer_default = /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_primitives.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [
8469 + /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_primitives.Path, { d: "M9.75 4.75H18C18.6904 4.75 19.25 5.30964 19.25 6V14.25M9.75 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V14.25M9.75 4.75V14.25M19.25 14.25V18C19.25 18.6904 18.6904 19.25 18 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V14.25M19.25 14.25H9.75M9.75 14.25H4.75", vectorEffect: "non-scaling-stroke" }),
8470 + /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_primitives.Path, { d: "M19.25 15.5V18C19.25 18.6904 18.6904 19.25 18 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V15.5C4.75 14.8096 5.30964 14.25 6 14.25H18C18.6904 14.25 19.25 14.8096 19.25 15.5Z", fill: "currentColor", vectorEffect: "non-scaling-stroke" })
8471 + ] });
8472 +
8473 + // packages/icons/build-module/library/header.mjs
8474 + var import_primitives2 = __toESM(require_primitives(), 1);
8475 + var import_jsx_runtime3 = __toESM(require_jsx_runtime(), 1);
8476 + var header_default = /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_primitives2.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [
8477 + /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives2.Path, { d: "M9.75 19.25H18C18.6904 19.25 19.25 18.6904 19.25 18V9.75M9.75 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V9.75M9.75 19.25V9.75M19.25 9.75V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V9.75M19.25 9.75H9.75M9.75 9.75H4.75", vectorEffect: "non-scaling-stroke" }),
8478 + /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_primitives2.Path, { d: "M19.25 8.5V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V8.5C4.75 9.19036 5.30964 9.75 6 9.75H18C18.6904 9.75 19.25 9.19036 19.25 8.5Z", fill: "currentColor", vectorEffect: "non-scaling-stroke" })
8479 + ] });
8480 +
8481 + // packages/icons/build-module/library/layout.mjs
8482 + var import_primitives3 = __toESM(require_primitives(), 1);
8483 + var import_jsx_runtime4 = __toESM(require_jsx_runtime(), 1);
8484 + var layout_default = /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives3.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_primitives3.Path, { d: "M9.75 19.25H18C18.6904 19.25 19.25 18.6904 19.25 18V9.75M9.75 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V9.75M9.75 19.25V9.75M19.25 9.75V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V9.75M19.25 9.75H9.75M9.75 9.75H4.75", vectorEffect: "non-scaling-stroke" }) });
8485 +
8486 + // packages/icons/build-module/library/navigation-overlay.mjs
8487 + var import_primitives4 = __toESM(require_primitives(), 1);
8488 + var import_jsx_runtime5 = __toESM(require_jsx_runtime(), 1);
8489 + var navigation_overlay_default = /* @__PURE__ */ (0, import_jsx_runtime5.jsxs)(import_primitives4.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [
8490 + /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives4.Path, { d: "M4.75 9.25V16C4.75 16.6904 5.30964 17.25 6 17.25H8M4.75 9.25V6C4.75 5.30964 5.30964 4.75 6 4.75H16C16.6904 4.75 17.25 5.30964 17.25 6V8M4.75 9.25H8", vectorEffect: "non-scaling-stroke" }),
8491 + /* @__PURE__ */ (0, import_jsx_runtime5.jsx)(import_primitives4.Path, { d: "M10.75 11.25C10.75 10.9739 10.9739 10.75 11.25 10.75H18.75C19.0261 10.75 19.25 10.9739 19.25 11.25V18.75C19.25 19.0261 19.0261 19.25 18.75 19.25H11.25C10.9739 19.25 10.75 19.0261 10.75 18.75V11.25Z", fill: "currentColor", vectorEffect: "non-scaling-stroke" })
8492 + ] });
8493 +
8494 + // packages/icons/build-module/library/sidebar.mjs
8495 + var import_primitives5 = __toESM(require_primitives(), 1);
8496 + var import_jsx_runtime6 = __toESM(require_jsx_runtime(), 1);
8497 + var sidebar_default = /* @__PURE__ */ (0, import_jsx_runtime6.jsxs)(import_primitives5.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [
8498 + /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives5.Path, { d: "M9.75 19.25H18C18.6904 19.25 19.25 18.6904 19.25 18V9.75M9.75 19.25H6C5.30964 19.25 4.75 18.6904 4.75 18V9.75M9.75 19.25V9.75M19.25 9.75V6C19.25 5.30964 18.6904 4.75 18 4.75H6C5.30964 4.75 4.75 5.30964 4.75 6V9.75M19.25 9.75H9.75M9.75 9.75H4.75", vectorEffect: "non-scaling-stroke" }),
8499 + /* @__PURE__ */ (0, import_jsx_runtime6.jsx)(import_primitives5.Path, { d: "M6 19.25H9.75V9.75H4.75V18C4.75 18.6904 5.30964 19.25 6 19.25Z", fill: "currentColor", vectorEffect: "non-scaling-stroke" })
8500 + ] });
8501 +
8502 + // packages/icons/build-module/library/symbol-filled.mjs
8503 + var import_primitives6 = __toESM(require_primitives(), 1);
8504 + var import_jsx_runtime7 = __toESM(require_jsx_runtime(), 1);
8505 + var symbol_filled_default = /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_primitives6.SVG, { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 0 24 24", style: { fill: "none" }, stroke: "currentColor", strokeWidth: "1.5", children: [
8506 + /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives6.Path, { d: "M15.2071 6.20711L20.2929 11.2929C20.6834 11.6834 20.6834 12.3166 20.2929 12.7071L15.2071 17.7929C14.8166 18.1834 14.1834 18.1834 13.7929 17.7929L8.70711 12.7071C8.31658 12.3166 8.31658 11.6834 8.70711 11.2929L13.7929 6.20711C14.1834 5.81658 14.8166 5.81658 15.2071 6.20711Z", fill: "currentColor", vectorEffect: "non-scaling-stroke" }),
8507 + /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_primitives6.Path, { d: "M9.5 5.5L3.70711 11.2929C3.31658 11.6834 3.31658 12.3166 3.70711 12.7071L9.5 18.5", vectorEffect: "non-scaling-stroke" })
8508 + ] });
8509 +
8510 + // packages/core-data/build-module/utils/get-template-part-icon.mjs
8511 + function getTemplatePartIcon(areaOrIconName) {
8512 + if ("header" === areaOrIconName) {
8513 + return header_default;
8514 + } else if ("footer" === areaOrIconName) {
8515 + return footer_default;
8516 + } else if ("sidebar" === areaOrIconName) {
8517 + return sidebar_default;
8518 + } else if ("navigation-overlay" === areaOrIconName) {
8519 + return navigation_overlay_default;
8520 + }
8521 + return symbol_filled_default;
8522 + }
8523 +
8524 + // packages/core-data/build-module/utils/get-template-info.mjs
8525 + var EMPTY_OBJECT4 = {};
8526 + var getTemplateInfo = (params) => {
8527 + if (!params) {
8528 + return EMPTY_OBJECT4;
8529 + }
8530 + const { templateTypes, templateAreas, template } = params;
8531 + const { description, slug, title, area } = template;
8532 + const { title: defaultTitle, description: defaultDescription } = Object.values(templateTypes).find((type) => type.slug === slug) ?? EMPTY_OBJECT4;
8533 + const templateTitle = typeof title === "string" ? title : title?.rendered;
8534 + const templateDescription = typeof description === "string" ? description : description?.raw;
8535 + const templateAreasWithIcon = templateAreas?.map((item) => ({
8536 + ...item,
8537 + icon: getTemplatePartIcon(item.icon)
8538 + }));
8539 + const templateIcon = templateAreasWithIcon?.find((item) => area === item.area)?.icon || layout_default;
8540 + return {
8541 + title: templateTitle && templateTitle !== slug ? templateTitle : defaultTitle || slug,
8542 + description: templateDescription || defaultDescription,
8543 + icon: templateIcon
8544 + };
8545 + };
8546 +
8547 + // node_modules/clsx/dist/clsx.mjs
8548 + function r(e) {
8549 + var t, f, n = "";
8550 + if ("string" == typeof e || "number" == typeof e) n += e;
8551 + else if ("object" == typeof e) if (Array.isArray(e)) {
8552 + var o = e.length;
8553 + for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
8554 + } else for (f in e) e[f] && (n && (n += " "), n += f);
8555 + return n;
8556 + }
8557 + function clsx() {
8558 + for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t);
8559 + return n;
8560 + }
8561 + var clsx_default = clsx;
8562 +
8563 + // packages/core-data/build-module/components/entities-saved-states/index.mjs
8564 + var import_components3 = __toESM(require_components(), 1);
8565 + var import_i18n7 = __toESM(require_i18n(), 1);
8566 + var import_element10 = __toESM(require_element(), 1);
8567 + var import_compose4 = __toESM(require_compose(), 1);
8568 + var import_data19 = __toESM(require_data(), 1);
8569 +
8570 + // packages/core-data/build-module/components/entities-saved-states/entity-type-list.mjs
8571 + var import_i18n6 = __toESM(require_i18n(), 1);
8572 + var import_data17 = __toESM(require_data(), 1);
8573 + var import_components2 = __toESM(require_components(), 1);
8574 +
8575 + // packages/global-styles-engine/build-module/utils/get-global-styles-changes.mjs
8576 + var import_i18n4 = __toESM(require_i18n(), 1);
8577 + var import_blocks7 = __toESM(require_blocks(), 1);
8578 + var globalStylesChangesCache = /* @__PURE__ */ new Map();
8579 + var EMPTY_ARRAY3 = [];
8580 + var translationMap = {
8581 + caption: (0, import_i18n4.__)("Caption"),
8582 + link: (0, import_i18n4.__)("Link"),
8583 + button: (0, import_i18n4.__)("Button"),
8584 + heading: (0, import_i18n4.__)("Heading"),
8585 + h1: (0, import_i18n4.__)("H1"),
8586 + h2: (0, import_i18n4.__)("H2"),
8587 + h3: (0, import_i18n4.__)("H3"),
8588 + h4: (0, import_i18n4.__)("H4"),
8589 + h5: (0, import_i18n4.__)("H5"),
8590 + h6: (0, import_i18n4.__)("H6"),
8591 + "settings.color": (0, import_i18n4.__)("Color"),
8592 + "settings.typography": (0, import_i18n4.__)("Typography"),
8593 + "settings.shadow": (0, import_i18n4.__)("Shadow"),
8594 + "settings.layout": (0, import_i18n4.__)("Layout"),
8595 + "styles.color": (0, import_i18n4.__)("Colors"),
8596 + "styles.spacing": (0, import_i18n4.__)("Spacing"),
8597 + "styles.background": (0, import_i18n4.__)("Background"),
8598 + "styles.typography": (0, import_i18n4.__)("Typography"),
8599 + "styles.border": (0, import_i18n4.__)("Border"),
8600 + "styles.shadow": (0, import_i18n4.__)("Shadow"),
8601 + "styles.outline": (0, import_i18n4.__)("Outline"),
8602 + "styles.filter": (0, import_i18n4.__)("Filter"),
8603 + "styles.dimensions": (0, import_i18n4.__)("Dimensions")
8604 + };
8605 + var getBlockNames = memize(
8606 + () => (0, import_blocks7.getBlockTypes)().reduce(
8607 + (accumulator, {
8608 + name,
8609 + title
8610 + }) => {
8611 + accumulator[name] = title;
8612 + return accumulator;
8613 + },
8614 + {}
8615 + )
8616 + );
8617 + var isObject = (obj) => obj !== null && typeof obj === "object";
8618 + function getTranslation(key) {
8619 + if (translationMap[key]) {
8620 + return translationMap[key];
8621 + }
8622 + const keyArray = key.split(".");
8623 + if (keyArray?.[0] === "blocks") {
8624 + const blockName = getBlockNames()?.[keyArray[1]];
8625 + return blockName || keyArray[1];
8626 + }
8627 + if (keyArray?.[0] === "elements") {
8628 + return translationMap[keyArray[1]] || keyArray[1];
8629 + }
8630 + return void 0;
8631 + }
8632 + function deepCompare(changedObject, originalObject, parentPath = "") {
8633 + if (!isObject(changedObject) && !isObject(originalObject)) {
8634 + return changedObject !== originalObject ? parentPath.split(".").slice(0, 2).join(".") : void 0;
8635 + }
8636 + changedObject = isObject(changedObject) ? changedObject : {};
8637 + originalObject = isObject(originalObject) ? originalObject : {};
8638 + const allKeys = /* @__PURE__ */ new Set([
8639 + ...Object.keys(changedObject),
8640 + ...Object.keys(originalObject)
8641 + ]);
8642 + let diffs = [];
8643 + for (const key of allKeys) {
8644 + const path = parentPath ? parentPath + "." + key : key;
8645 + const changedPath = deepCompare(
8646 + changedObject[key],
8647 + originalObject[key],
8648 + path
8649 + );
8650 + if (changedPath) {
8651 + diffs = diffs.concat(changedPath);
8652 + }
8653 + }
8654 + return diffs;
8655 + }
8656 + var COMPARED_STYLE_KEYS = [
8657 + "background",
8658 + "color",
8659 + "typography",
8660 + "spacing",
8661 + "border",
8662 + "shadow",
8663 + "outline",
8664 + "filter",
8665 + "dimensions"
8666 + ];
8667 + function pickComparedStyles(config) {
8668 + return Object.fromEntries(
8669 + COMPARED_STYLE_KEYS.map((key) => [key, config?.styles?.[key]])
8670 + );
8671 + }
8672 + function getGlobalStylesChangelist(next, previous) {
8673 + const cacheKey = JSON.stringify({ next, previous });
8674 + if (globalStylesChangesCache.has(cacheKey)) {
8675 + return globalStylesChangesCache.get(cacheKey);
8676 + }
8677 + const changedValueTree = deepCompare(
8678 + {
8679 + styles: pickComparedStyles(next),
8680 + blocks: next?.styles?.blocks,
8681 + elements: next?.styles?.elements,
8682 + settings: next?.settings
8683 + },
8684 + {
8685 + styles: pickComparedStyles(previous),
8686 + blocks: previous?.styles?.blocks,
8687 + elements: previous?.styles?.elements,
8688 + settings: previous?.settings
8689 + }
8690 + );
8691 + if (!changedValueTree || Array.isArray(changedValueTree) && !changedValueTree.length) {
8692 + globalStylesChangesCache.set(cacheKey, []);
8693 + return [];
8694 + }
8695 + const changedValueArray = Array.isArray(changedValueTree) ? changedValueTree : [changedValueTree];
8696 + const result = [...new Set(changedValueArray)].reduce((acc, curr) => {
8697 + const translation = getTranslation(curr);
8698 + if (translation) {
8699 + acc.push([curr.split(".")[0], translation]);
8700 + }
8701 + return acc;
8702 + }, []);
8703 + globalStylesChangesCache.set(cacheKey, result);
8704 + return result;
8705 + }
8706 + function getGlobalStylesChanges(next, previous, options = {}) {
8707 + let changeList = getGlobalStylesChangelist(next, previous);
8708 + const changesLength = changeList.length;
8709 + const { maxResults } = options;
8710 + if (changesLength) {
8711 + if (!!maxResults && changesLength > maxResults) {
8712 + changeList = changeList.slice(0, maxResults);
8713 + }
8714 + return Object.entries(
8715 + changeList.reduce((acc, curr) => {
8716 + const group = acc[curr[0]] || [];
8717 + if (!group.includes(curr[1])) {
8718 + acc[curr[0]] = [...group, curr[1]];
8719 + }
8720 + return acc;
8721 + }, {})
8722 + ).map(([key, changeValues]) => {
8723 + const changeValuesLength = changeValues.length;
8724 + const joinedChangesValue = changeValues.join(
8725 + /* translators: Used between list items, there is a space after the comma. */
8726 + (0, import_i18n4.__)(", ")
8727 + // eslint-disable-line @wordpress/i18n-no-flanking-whitespace
8728 + );
8729 + switch (key) {
8730 + case "blocks": {
8731 + return (0, import_i18n4.sprintf)(
8732 + // translators: %s: a list of block names separated by a comma.
8733 + (0, import_i18n4._n)("%s block.", "%s blocks.", changeValuesLength),
8734 + joinedChangesValue
8735 + );
8736 + }
8737 + case "elements": {
8738 + return (0, import_i18n4.sprintf)(
8739 + // translators: %s: a list of element names separated by a comma.
8740 + (0, import_i18n4._n)("%s element.", "%s elements.", changeValuesLength),
8741 + joinedChangesValue
8742 + );
8743 + }
8744 + case "settings": {
8745 + return (0, import_i18n4.sprintf)(
8746 + // translators: %s: a list of theme.json setting labels separated by a comma.
8747 + (0, import_i18n4.__)("%s settings."),
8748 + joinedChangesValue
8749 + );
8750 + }
8751 + case "styles": {
8752 + return (0, import_i18n4.sprintf)(
8753 + // translators: %s: a list of theme.json top-level styles labels separated by a comma.
8754 + (0, import_i18n4.__)("%s styles."),
8755 + joinedChangesValue
8756 + );
8757 + }
8758 + default: {
8759 + return (0, import_i18n4.sprintf)(
8760 + // translators: %s: a list of global styles changes separated by a comma.
8761 + (0, import_i18n4.__)("%s."),
8762 + joinedChangesValue
8763 + );
8764 + }
8765 + }
8766 + });
8767 + }
8768 + return EMPTY_ARRAY3;
8769 + }
8770 +
8771 + // packages/core-data/build-module/components/entities-saved-states/entity-record-item.mjs
8772 + var import_components = __toESM(require_components(), 1);
8773 + var import_i18n5 = __toESM(require_i18n(), 1);
8774 + var import_data16 = __toESM(require_data(), 1);
8775 + var import_html_entities4 = __toESM(require_html_entities(), 1);
8776 + var import_jsx_runtime8 = __toESM(require_jsx_runtime(), 1);
8777 + function EntityRecordItem({ record, checked, onChange }) {
8778 + const { name, kind, title, key } = record;
8779 + const { entityRecordTitle } = (0, import_data16.useSelect)(
8780 + (select5) => {
8781 + if ("postType" !== kind || "wp_template" !== name) {
8782 + return {
8783 + entityRecordTitle: title
8784 + };
8785 + }
8786 + const template = select5(STORE_NAME).getEditedEntityRecord(
8787 + kind,
8788 + name,
8789 + key
8790 + );
8791 + const { default_template_types: templateTypes = [] } = select5(STORE_NAME).getCurrentTheme() ?? {};
8792 + return {
8793 + entityRecordTitle: getTemplateInfo({
8794 + template,
8795 + templateTypes
8796 + }).title
8797 + };
8798 + },
8799 + [name, kind, title, key]
8800 + );
8801 + return /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_jsx_runtime8.Fragment, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(import_components.PanelRow, { children: /* @__PURE__ */ (0, import_jsx_runtime8.jsx)(
8802 + import_components.CheckboxControl,
8803 + {
8804 + label: (0, import_html_entities4.decodeEntities)(entityRecordTitle) || (0, import_i18n5.__)("Untitled"),
8805 + checked,
8806 + onChange,
8807 + className: "entities-saved-states__change-control"
8808 + }
8809 + ) }) });
8810 + }
8811 +
8812 + // packages/core-data/build-module/components/entities-saved-states/entity-type-list.mjs
8813 + var import_jsx_runtime9 = __toESM(require_jsx_runtime(), 1);
8814 + function getEntityDescription(entity2, count) {
8815 + switch (entity2) {
8816 + case "site":
8817 + return 1 === count ? (0, import_i18n6.__)("This change will affect your whole site.") : (0, import_i18n6.__)("These changes will affect your whole site.");
8818 + case "wp_template":
8819 + return (0, import_i18n6.__)(
8820 + "This change will affect other parts of your site that use this template."
8821 + );
8822 + case "page":
8823 + case "post":
8824 + return (0, import_i18n6.__)("The following has been modified.");
8825 + }
8826 + }
8827 + function GlobalStylesDescription({ record }) {
8828 + const { editedRecord, savedRecord } = (0, import_data17.useSelect)(
8829 + (select5) => {
8830 + const { getEditedEntityRecord: getEditedEntityRecord3, getEntityRecord: getEntityRecord3 } = select5(STORE_NAME);
8831 + return {
8832 + editedRecord: getEditedEntityRecord3(
8833 + record.kind,
8834 + record.name,
8835 + record.key
8836 + ),
8837 + savedRecord: getEntityRecord3(
8838 + record.kind,
8839 + record.name,
8840 + record.key
8841 + )
8842 + };
8843 + },
8844 + [record.kind, record.name, record.key]
8845 + );
8846 + const globalStylesChanges = getGlobalStylesChanges(
8847 + editedRecord,
8848 + savedRecord,
8849 + {
8850 + maxResults: 10
8851 + }
8852 + );
8853 + return globalStylesChanges.length ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("ul", { className: "entities-saved-states__changes", children: globalStylesChanges.map((change) => /* @__PURE__ */ (0, import_jsx_runtime9.jsx)("li", { children: change }, change)) }) : null;
8854 + }
8855 + function EntityDescription({ record, count }) {
8856 + if ("globalStyles" === record?.name) {
8857 + return null;
8858 + }
8859 + const description = getEntityDescription(record?.name, count);
8860 + return description ? /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(import_components2.PanelRow, { children: description }) : null;
8861 + }
8862 + function EntityTypeList({
8863 + list,
8864 + unselectedEntities,
8865 + setUnselectedEntities
8866 + }) {
8867 + const count = list.length;
8868 + const firstRecord = list[0];
8869 + const entityConfig = (0, import_data17.useSelect)(
8870 + (select5) => select5(STORE_NAME).getEntityConfig(
8871 + firstRecord.kind,
8872 + firstRecord.name
8873 + ),
8874 + [firstRecord.kind, firstRecord.name]
8875 + );
8876 + let entityLabel = entityConfig.label;
8877 + if (firstRecord?.name === "wp_template_part") {
8878 + entityLabel = 1 === count ? (0, import_i18n6.__)("Template Part") : (0, import_i18n6.__)("Template Parts");
8879 + }
8880 + return /* @__PURE__ */ (0, import_jsx_runtime9.jsxs)(
8881 + import_components2.PanelBody,
8882 + {
8883 + title: entityLabel,
8884 + initialOpen: true,
8885 + className: "entities-saved-states__panel-body",
8886 + children: [
8887 + /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(EntityDescription, { record: firstRecord, count }),
8888 + list.map((record) => {
8889 + return /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(
8890 + EntityRecordItem,
8891 + {
8892 + record,
8893 + checked: !unselectedEntities.some(
8894 + (elt) => elt.kind === record.kind && elt.name === record.name && elt.key === record.key && elt.property === record.property
8895 + ),
8896 + onChange: (value) => setUnselectedEntities(record, value)
8897 + },
8898 + record.key || record.property
8899 + );
8900 + }),
8901 + "globalStyles" === firstRecord?.name && /* @__PURE__ */ (0, import_jsx_runtime9.jsx)(GlobalStylesDescription, { record: firstRecord })
8902 + ]
8903 + }
8904 + );
8905 + }
8906 +
8907 + // packages/core-data/build-module/components/entities-saved-states/hooks/use-is-dirty.mjs
8908 + var import_data18 = __toESM(require_data(), 1);
8909 + var import_element9 = __toESM(require_element(), 1);
8910 + var useIsDirty = () => {
8911 + const { editedEntities, siteEdits, siteEntityConfig } = (0, import_data18.useSelect)(
8912 + (select5) => {
8913 + const {
8914 + __experimentalGetDirtyEntityRecords: __experimentalGetDirtyEntityRecords2,
8915 + getEntityRecordEdits: getEntityRecordEdits2,
8916 + getEntityConfig: getEntityConfig2
8917 + } = select5(STORE_NAME);
8918 + return {
8919 + editedEntities: __experimentalGetDirtyEntityRecords2(),
8920 + siteEdits: getEntityRecordEdits2("root", "site"),
8921 + siteEntityConfig: getEntityConfig2("root", "site")
8922 + };
8923 + },
8924 + []
8925 + );
8926 + const dirtyEntityRecords = (0, import_element9.useMemo)(() => {
8927 + const editedEntitiesWithoutSite = editedEntities.filter(
8928 + (record) => !(record.kind === "root" && record.name === "site")
8929 + );
8930 + const siteEntityLabels = siteEntityConfig?.meta?.labels ?? {};
8931 + const {
8932 + title: siteTitleEdit,
8933 + description: siteDescriptionEdit,
8934 + site_logo: siteLogoEdit,
8935 + site_icon: siteIconEdit,
8936 + ...otherSiteEdits
8937 + } = siteEdits ?? {};
8938 + const orderedSiteProperties = [
8939 + siteTitleEdit !== void 0 && "title",
8940 + siteDescriptionEdit !== void 0 && "description",
8941 + siteLogoEdit !== void 0 && "site_logo",
8942 + siteIconEdit !== void 0 && "site_icon",
8943 + ...Object.keys(otherSiteEdits)
8944 + ].filter(Boolean);
8945 + const editedSiteEntities = orderedSiteProperties.map(
8946 + (property) => ({
8947 + kind: "root",
8948 + name: "site",
8949 + title: siteEntityLabels[property] || property,
8950 + property
8951 + })
8952 + );
8953 + return [...editedEntitiesWithoutSite, ...editedSiteEntities];
8954 + }, [editedEntities, siteEdits, siteEntityConfig]);
8955 + const [unselectedEntities, _setUnselectedEntities] = (0, import_element9.useState)([]);
8956 + const setUnselectedEntities = ({ kind, name, key, property }, checked) => {
8957 + if (checked) {
8958 + _setUnselectedEntities(
8959 + unselectedEntities.filter(
8960 + (elt) => elt.kind !== kind || elt.name !== name || elt.key !== key || elt.property !== property
8961 + )
8962 + );
8963 + } else {
8964 + _setUnselectedEntities([
8965 + ...unselectedEntities,
8966 + { kind, name, key, property }
8967 + ]);
8968 + }
8969 + };
8970 + const isDirty = dirtyEntityRecords.length - unselectedEntities.length > 0;
8971 + return {
8972 + dirtyEntityRecords,
8973 + isDirty,
8974 + setUnselectedEntities,
8975 + unselectedEntities
8976 + };
8977 + };
8978 +
8979 + // packages/core-data/build-module/components/entities-saved-states/index.mjs
8980 + var import_jsx_runtime10 = __toESM(require_jsx_runtime(), 1);
8981 + function EntitiesSavedStates({
8982 + close,
8983 + renderDialog,
8984 + variant
8985 + }) {
8986 + const isDirtyProps = useIsDirty();
8987 + return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
8988 + EntitiesSavedStatesExtensible,
8989 + {
8990 + close,
8991 + renderDialog,
8992 + variant,
8993 + ...isDirtyProps
8994 + }
8995 + );
8996 + }
8997 + function EntitiesSavedStatesExtensible({
8998 + additionalPrompt = void 0,
8999 + close,
9000 + onSave = void 0,
9001 + saveEnabled: saveEnabledProp = void 0,
9002 + saveLabel = (0, import_i18n7.__)("Save"),
9003 + renderDialog,
9004 + dirtyEntityRecords,
9005 + isDirty,
9006 + setUnselectedEntities,
9007 + unselectedEntities,
9008 + variant = "default",
9009 + successNoticeContent
9010 + }) {
9011 + const saveButtonRef = (0, import_element10.useRef)();
9012 + const { saveDirtyEntities: saveDirtyEntities2 } = unlock((0, import_data19.useDispatch)(STORE_NAME));
9013 + const partitionedSavables = dirtyEntityRecords.reduce((acc, record) => {
9014 + const { name } = record;
9015 + if (!acc[name]) {
9016 + acc[name] = [];
9017 + }
9018 + acc[name].push(record);
9019 + return acc;
9020 + }, {});
9021 + const {
9022 + site: siteSavables,
9023 + wp_template: templateSavables,
9024 + wp_template_part: templatePartSavables,
9025 + ...contentSavables
9026 + } = partitionedSavables;
9027 + const sortedPartitionedSavables = [
9028 + siteSavables,
9029 + templateSavables,
9030 + templatePartSavables,
9031 + ...Object.values(contentSavables)
9032 + ].filter(Array.isArray);
9033 + const saveEnabled = saveEnabledProp ?? isDirty;
9034 + const dismissPanel = (0, import_element10.useCallback)(() => close(), [close]);
9035 + const [saveDialogRef, saveDialogProps] = (0, import_compose4.__experimentalUseDialog)({
9036 + onClose: () => dismissPanel()
9037 + });
9038 + const dialogLabelId = (0, import_compose4.useInstanceId)(
9039 + EntitiesSavedStatesExtensible,
9040 + "entities-saved-states__panel-label"
9041 + );
9042 + const dialogDescriptionId = (0, import_compose4.useInstanceId)(
9043 + EntitiesSavedStatesExtensible,
9044 + "entities-saved-states__panel-description"
9045 + );
9046 + const selectItemsToSaveDescription = !!dirtyEntityRecords.length ? (0, import_i18n7.__)("Select the items you want to save.") : void 0;
9047 + const isInline = variant === "inline";
9048 + const actionButtons = /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(import_jsx_runtime10.Fragment, { children: [
9049 + /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
9050 + import_components3.FlexItem,
9051 + {
9052 + isBlock: isInline ? false : true,
9053 + as: import_components3.Button,
9054 + variant: isInline ? "tertiary" : "secondary",
9055 + size: isInline ? void 0 : "compact",
9056 + onClick: dismissPanel,
9057 + children: (0, import_i18n7.__)("Cancel")
9058 + }
9059 + ),
9060 + /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
9061 + import_components3.FlexItem,
9062 + {
9063 + isBlock: isInline ? false : true,
9064 + as: import_components3.Button,
9065 + ref: saveButtonRef,
9066 + variant: "primary",
9067 + size: isInline ? void 0 : "compact",
9068 + disabled: !saveEnabled,
9069 + accessibleWhenDisabled: true,
9070 + onClick: () => saveDirtyEntities2({
9071 + onSave,
9072 + dirtyEntityRecords,
9073 + entitiesToSkip: unselectedEntities,
9074 + close,
9075 + successNoticeContent
9076 + }),
9077 + className: "entities-saved-states__save-button",
9078 + children: saveLabel
9079 + }
9080 + )
9081 + ] });
9082 + return /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)(
9083 + "div",
9084 + {
9085 + ref: renderDialog ? saveDialogRef : void 0,
9086 + ...renderDialog && saveDialogProps,
9087 + className: clsx_default("entities-saved-states__panel", {
9088 + "is-inline": isInline
9089 + }),
9090 + role: renderDialog ? "dialog" : void 0,
9091 + "aria-labelledby": renderDialog ? dialogLabelId : void 0,
9092 + "aria-describedby": renderDialog ? dialogDescriptionId : void 0,
9093 + children: [
9094 + !isInline && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(import_components3.Flex, { className: "entities-saved-states__panel-header", gap: 2, children: actionButtons }),
9095 + /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { className: "entities-saved-states__text-prompt", children: [
9096 + /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("div", { className: "entities-saved-states__text-prompt--header-wrapper", children: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
9097 + "strong",
9098 + {
9099 + id: renderDialog ? dialogLabelId : void 0,
9100 + className: "entities-saved-states__text-prompt--header",
9101 + children: (0, import_i18n7.__)("Are you ready to save?")
9102 + }
9103 + ) }),
9104 + /* @__PURE__ */ (0, import_jsx_runtime10.jsxs)("div", { id: renderDialog ? dialogDescriptionId : void 0, children: [
9105 + additionalPrompt,
9106 + /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("p", { className: "entities-saved-states__text-prompt--changes-count", children: isDirty ? (0, import_element10.createInterpolateElement)(
9107 + (0, import_i18n7.sprintf)(
9108 + /* translators: %d: number of site changes waiting to be saved. */
9109 + (0, import_i18n7._n)(
9110 + "There is <strong>%d site change</strong> waiting to be saved.",
9111 + "There are <strong>%d site changes</strong> waiting to be saved.",
9112 + dirtyEntityRecords.length
9113 + ),
9114 + dirtyEntityRecords.length
9115 + ),
9116 + { strong: /* @__PURE__ */ (0, import_jsx_runtime10.jsx)("strong", {}) }
9117 + ) : selectItemsToSaveDescription })
9118 + ] })
9119 + ] }),
9120 + sortedPartitionedSavables.map((list) => {
9121 + return /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
9122 + EntityTypeList,
9123 + {
9124 + list,
9125 + unselectedEntities,
9126 + setUnselectedEntities
9127 + },
9128 + list[0].name
9129 + );
9130 + }),
9131 + isInline && /* @__PURE__ */ (0, import_jsx_runtime10.jsx)(
9132 + import_components3.Flex,
9133 + {
9134 + direction: "row",
9135 + justify: "flex-end",
9136 + className: "entities-saved-states__panel-footer",
9137 + children: actionButtons
9138 + }
9139 + )
9140 + ]
9141 + }
9142 + );
9143 + }
9144 +
8025 9145 // packages/core-data/build-module/private-apis.mjs
8026 9146 var lockedApis = {
9147 + EntitiesSavedStates,
9148 + EntitiesSavedStatesExtensible,
9149 + getTemplateInfo,
9150 + getTemplatePartIcon,
9151 + useEntitiesSavedStatesIsDirty: useIsDirty,
8027 9152 useEntityRecordsWithPermissions,
8028 9153 RECEIVE_INTERMEDIATE_RESULTS,
9154 + CRDT_AUTOSAVE_SNAPSHOT_KEY,
9155 + entityContainsSnapshot,
9156 + getEntitySnapshot,
8029 9157 retrySyncConnection,
8030 9158 useActiveCollaborators,
8031 9159 useResolvedSelection,
8032 9160 useOnCollaboratorJoin,
@@ -8122,11 +9250,13 @@
8122 9250 ...entitySelectors
8123 9251 },
8124 9252 resolvers: { ...resolvers_exports, ...entityResolvers }
8125 9253 });
8126 - var store = (0, import_data15.createReduxStore)(STORE_NAME, storeConfig());
9254 + var store = (0, import_data20.createReduxStore)(STORE_NAME, storeConfig());
8127 9255 unlock(store).registerPrivateSelectors(private_selectors_exports);
8128 9256 unlock(store).registerPrivateActions(private_actions_exports);
8129 - (0, import_data15.register)(store);
9257 + (0, import_data20.register)(store);
8130 9258 return __toCommonJS(index_exports);
9259 +})();
9260 +(window.wp ||= {}).coreData = wp.coreData;
8131 9261 })();
8132 9262 //# sourceMappingURL=index.js.map