UNPKG

@wordpress/editor

Version:
128 lines (107 loc) 2.98 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _element = require("@wordpress/element"); var _lodash = require("lodash"); var _data = require("@wordpress/data"); var _i18n = require("@wordpress/i18n"); var _components = require("@wordpress/components"); /** * External dependencies */ /** * WordPress dependencies */ function PostAuthorCombobox() { const [fieldValue, setFieldValue] = (0, _element.useState)(); const { authorId, isLoading, authors, postAuthor } = (0, _data.useSelect)(select => { const { __unstableGetAuthor, getAuthors, isResolving } = select('core'); const { getEditedPostAttribute } = select('core/editor'); const author = __unstableGetAuthor(getEditedPostAttribute('author')); const query = !fieldValue || '' === fieldValue ? {} : { search: fieldValue }; return { authorId: getEditedPostAttribute('author'), postAuthor: author, authors: getAuthors(query), isLoading: isResolving('core', 'getAuthors', [query]) }; }, [fieldValue]); const { editPost } = (0, _data.useDispatch)('core/editor'); const authorOptions = (0, _element.useMemo)(() => { const fetchedAuthors = (authors !== null && authors !== void 0 ? authors : []).map(author => { return { value: author.id, label: author.name }; }); // Ensure the current author is included in the dropdown list. const foundAuthor = fetchedAuthors.findIndex(({ value }) => (postAuthor === null || postAuthor === void 0 ? void 0 : postAuthor.id) === value); if (foundAuthor < 0 && postAuthor) { return [{ value: postAuthor.id, label: postAuthor.name }, ...fetchedAuthors]; } return fetchedAuthors; }, [authors, postAuthor]); // Initializes the post author properly // Also ensures external changes are reflected. (0, _element.useEffect)(() => { if (postAuthor) { setFieldValue(postAuthor.name); } }, [postAuthor]); /** * Handle author selection. * * @param {number} postAuthorId The selected Author. */ const handleSelect = postAuthorId => { if (!postAuthorId) { return; } editPost({ author: postAuthorId }); }; /** * Handle user input. * * @param {string} inputValue The current value of the input field. */ const handleKeydown = inputValue => { setFieldValue(inputValue); }; if (!postAuthor) { return null; } return (0, _element.createElement)(_components.ComboboxControl, { label: (0, _i18n.__)('Author'), options: authorOptions, value: authorId, onFilterValueChange: (0, _lodash.debounce)(handleKeydown, 300), onChange: handleSelect, isLoading: isLoading, allowReset: false }); } var _default = PostAuthorCombobox; exports.default = _default; //# sourceMappingURL=combobox.js.map