@wordpress/core-data
Version:
Access to and manipulation of core WordPress entities.
275 lines (274 loc) • 7.16 kB
JavaScript
// packages/core-data/src/private-actions.js
import apiFetch from "@wordpress/api-fetch";
import { store as noticesStore } from "@wordpress/notices";
import { store as blockEditorStore } from "@wordpress/block-editor";
import { decodeEntities } from "@wordpress/html-entities";
import { __ } from "@wordpress/i18n";
import { STORE_NAME } from "./name.mjs";
import { getSyncManager, hasSyncManager } from "./sync.mjs";
function receiveRegisteredPostMeta(postType, registeredPostMeta) {
return {
type: "RECEIVE_REGISTERED_POST_META",
postType,
registeredPostMeta
};
}
var editMediaEntity = (recordId, edits = {}, { __unstableFetch = apiFetch, throwOnError = false } = {}) => async ({ dispatch, resolveSelect }) => {
if (!recordId) {
return;
}
const kind = "postType";
const name = "attachment";
const configs = await resolveSelect.getEntitiesConfig(kind);
const entityConfig = configs.find(
(config) => config.kind === kind && config.name === name
);
if (!entityConfig) {
return;
}
const lock = await dispatch.__unstableAcquireStoreLock(
STORE_NAME,
["entities", "records", kind, name, recordId],
{ exclusive: true }
);
let updatedRecord;
let error;
let hasError = false;
try {
dispatch({
type: "SAVE_ENTITY_RECORD_START",
kind,
name,
recordId
});
try {
const path = `${entityConfig.baseURL}/${recordId}/edit`;
const newRecord = await __unstableFetch({
path,
method: "POST",
data: {
...edits
}
});
if (newRecord) {
dispatch.receiveEntityRecords(
kind,
name,
newRecord,
void 0,
true,
void 0,
void 0
);
updatedRecord = newRecord;
}
} catch (e) {
error = e;
hasError = true;
}
dispatch({
type: "SAVE_ENTITY_RECORD_FINISH",
kind,
name,
recordId,
error
});
if (hasError && throwOnError) {
throw error;
}
return updatedRecord;
} finally {
dispatch.__unstableReleaseStoreLock(lock);
}
};
function receiveEditorSettings(settings) {
return {
type: "RECEIVE_EDITOR_SETTINGS",
settings
};
}
function receiveEditorAssets(assets) {
return {
type: "RECEIVE_EDITOR_ASSETS",
assets
};
}
var setCollaborationSupported = (supported) => ({ dispatch }) => {
dispatch({ type: "SET_COLLABORATION_SUPPORTED", supported });
if (!supported && hasSyncManager()) {
getSyncManager().unloadAll();
dispatch.__unstableNotifySyncUndoManagerChange({
hasUndo: false,
hasRedo: false
});
}
};
function receiveViewConfig(kind, name, config) {
return {
type: "RECEIVE_VIEW_CONFIG",
kind,
name,
config
};
}
function __unstableNotifySyncUndoManagerChange(state) {
return {
type: "SYNC_UNDO_MANAGER_CHANGE",
...state
};
}
function setSyncConnectionStatus(kind, name, key, status) {
if (!status) {
return {
type: "CLEAR_SYNC_CONNECTION_STATUS",
kind,
name,
key
};
}
return {
type: "SET_SYNC_CONNECTION_STATUS",
kind,
name,
key,
status
};
}
var saveDirtyEntities = ({
onSave,
dirtyEntityRecords = [],
entitiesToSkip = [],
close,
successNoticeContent
} = {}) => ({ registry }) => {
const PUBLISH_ON_SAVE_ENTITIES = [
{ kind: "postType", name: "wp_navigation" }
];
const saveNoticeId = "site-editor-save-success";
const homeUrl = registry.select(STORE_NAME).getEntityRecord("root", "__unstableBase")?.home;
registry.dispatch(noticesStore).removeNotice(saveNoticeId);
const entitiesToSave = dirtyEntityRecords.filter(
({ kind, name, key, property }) => {
return !entitiesToSkip.some(
(elt) => elt.kind === kind && elt.name === name && elt.key === key && elt.property === property
);
}
);
close?.(entitiesToSave);
const siteItemsToSave = [];
const pendingSavedRecords = [];
entitiesToSave.forEach(({ kind, name, key, property }) => {
if ("root" === kind && "site" === name) {
siteItemsToSave.push(property);
} else {
if (PUBLISH_ON_SAVE_ENTITIES.some(
(typeToPublish) => typeToPublish.kind === kind && typeToPublish.name === name
)) {
registry.dispatch(STORE_NAME).editEntityRecord(kind, name, key, {
status: "publish"
});
}
pendingSavedRecords.push(
registry.dispatch(STORE_NAME).saveEditedEntityRecord(kind, name, key, {
throwOnError: true
}).catch(ensureError)
);
}
});
if (siteItemsToSave.length) {
pendingSavedRecords.push(
registry.dispatch(STORE_NAME).__experimentalSaveSpecifiedEntityEdits(
"root",
"site",
void 0,
siteItemsToSave,
{
throwOnError: true
}
).catch(ensureError)
);
}
registry.dispatch(blockEditorStore).__unstableMarkLastChangeAsPersistent();
return Promise.all(pendingSavedRecords).then(async (values) => {
if (onSave) {
await onSave();
}
return values;
}).then((values) => {
const errors = values.filter((v) => v instanceof Error);
if (errors.length) {
const firstMessage = errors.find(
(e) => e.message
)?.message;
registry.dispatch(noticesStore).createErrorNotice(
decodeEntities(
firstMessage || __("Saving failed.")
),
{
type: "snackbar",
id: saveNoticeId
}
);
} else {
registry.dispatch(noticesStore).createSuccessNotice(
successNoticeContent || __("Site updated."),
{
type: "snackbar",
id: saveNoticeId,
actions: [
{
label: __("View site"),
url: homeUrl,
openInNewTab: true
}
]
}
);
}
}).catch(
(error) => registry.dispatch(noticesStore).createErrorNotice(
decodeEntities(
error?.message || __("Saving failed.")
),
{
type: "snackbar",
id: saveNoticeId
}
)
);
function ensureError(error) {
if (error instanceof Error) {
return error;
}
let message;
if (!error) {
} else if (typeof error.message === "string") {
message = error.message;
} else if (typeof error === "string") {
message = error;
} else if (
// Only consider own method, lest we erroneously end up calling
// `Object#toString` at the end of the prototype chain, thereby
// returning `"[object Object]"`.
Object.hasOwn(error, "toString") && typeof error.toString === "function"
) {
const result = error.toString();
if (typeof result === "string") {
message = result;
}
}
return new Error(message, { cause: error });
}
};
export {
__unstableNotifySyncUndoManagerChange,
editMediaEntity,
receiveEditorAssets,
receiveEditorSettings,
receiveRegisteredPostMeta,
receiveViewConfig,
saveDirtyEntities,
setCollaborationSupported,
setSyncConnectionStatus
};
//# sourceMappingURL=private-actions.mjs.map