@wordpress/block-library
Version:
Block library for the WordPress editor.
89 lines (88 loc) • 3.05 kB
JavaScript
// packages/block-library/src/navigation/edit/use-create-navigation-menu.js
import { serialize } from "@wordpress/blocks";
import { store as coreStore } from "@wordpress/core-data";
import { useDispatch } from "@wordpress/data";
import { useState, useCallback } from "@wordpress/element";
import useGenerateDefaultNavigationTitle from "./use-generate-default-navigation-title";
var CREATE_NAVIGATION_MENU_SUCCESS = "success";
var CREATE_NAVIGATION_MENU_ERROR = "error";
var CREATE_NAVIGATION_MENU_PENDING = "pending";
var CREATE_NAVIGATION_MENU_IDLE = "idle";
function useCreateNavigationMenu(clientId) {
const [status, setStatus] = useState(CREATE_NAVIGATION_MENU_IDLE);
const [value, setValue] = useState(null);
const [error, setError] = useState(null);
const { saveEntityRecord, editEntityRecord } = useDispatch(coreStore);
const generateDefaultTitle = useGenerateDefaultNavigationTitle(clientId);
const create = useCallback(
async (title = null, blocks = [], postStatus) => {
if (title && typeof title !== "string") {
setError(
"Invalid title supplied when creating Navigation Menu."
);
setStatus(CREATE_NAVIGATION_MENU_ERROR);
throw new Error(
`Value of supplied title argument was not a string.`
);
}
setStatus(CREATE_NAVIGATION_MENU_PENDING);
setValue(null);
setError(null);
if (!title) {
title = await generateDefaultTitle().catch((err) => {
setError(err?.message);
setStatus(CREATE_NAVIGATION_MENU_ERROR);
throw new Error(
"Failed to create title when saving new Navigation Menu.",
{
cause: err
}
);
});
}
const record = {
title,
content: serialize(blocks),
status: postStatus
};
return saveEntityRecord("postType", "wp_navigation", record).then((response) => {
setValue(response);
setStatus(CREATE_NAVIGATION_MENU_SUCCESS);
if (postStatus !== "publish") {
editEntityRecord(
"postType",
"wp_navigation",
response.id,
{ status: "publish" }
);
}
return response;
}).catch((err) => {
setError(err?.message);
setStatus(CREATE_NAVIGATION_MENU_ERROR);
throw new Error("Unable to save new Navigation Menu", {
cause: err
});
});
},
[saveEntityRecord, editEntityRecord, generateDefaultTitle]
);
return {
create,
status,
value,
error,
isIdle: status === CREATE_NAVIGATION_MENU_IDLE,
isPending: status === CREATE_NAVIGATION_MENU_PENDING,
isSuccess: status === CREATE_NAVIGATION_MENU_SUCCESS,
isError: status === CREATE_NAVIGATION_MENU_ERROR
};
}
export {
CREATE_NAVIGATION_MENU_ERROR,
CREATE_NAVIGATION_MENU_IDLE,
CREATE_NAVIGATION_MENU_PENDING,
CREATE_NAVIGATION_MENU_SUCCESS,
useCreateNavigationMenu as default
};
//# sourceMappingURL=use-create-navigation-menu.js.map