@wordpress/editor
Version:
Enhanced block editor for WordPress posts.
63 lines (62 loc) • 1.97 kB
JavaScript
// packages/editor/src/components/post-author/hook.js
import { __ } from "@wordpress/i18n";
import { useMemo } from "@wordpress/element";
import { useSelect } from "@wordpress/data";
import { decodeEntities } from "@wordpress/html-entities";
import { store as coreStore } from "@wordpress/core-data";
import { store as editorStore } from "../../store/index.mjs";
import { AUTHORS_QUERY, BASE_QUERY } from "./constants.mjs";
function useAuthorsQuery(search) {
const { authorId, authors, postAuthor, isLoading } = useSelect(
(select) => {
const { getUser, getUsers, isResolving } = select(coreStore);
const { getEditedPostAttribute } = select(editorStore);
const _authorId = getEditedPostAttribute("author");
const query = { ...AUTHORS_QUERY };
if (search) {
query.search = search;
query.search_columns = ["name"];
}
return {
authorId: _authorId,
authors: getUsers(query),
postAuthor: getUser(_authorId, BASE_QUERY),
isLoading: isResolving("getUsers", [query])
};
},
[search]
);
const authorOptions = useMemo(() => {
const fetchedAuthors = (authors ?? []).map((author) => {
return {
value: author.id,
label: decodeEntities(author.name)
};
});
const foundAuthor = fetchedAuthors.findIndex(
({ value }) => postAuthor?.id === value
);
let currentAuthor = [];
if (foundAuthor < 0 && postAuthor) {
currentAuthor = [
{
value: postAuthor.id,
label: decodeEntities(postAuthor.name)
}
];
} else if (foundAuthor < 0 && !postAuthor) {
currentAuthor = [
{
value: 0,
label: __("(No author)")
}
];
}
return [...currentAuthor, ...fetchedAuthors];
}, [authors, postAuthor]);
return { authorId, authorOptions, postAuthor, isLoading };
}
export {
useAuthorsQuery
};
//# sourceMappingURL=hook.mjs.map