/* wp:polyfill */
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useAuthorsQuery = useAuthorsQuery;
var _i18n = require("@wordpress/i18n");
var _element = require("@wordpress/element");
var _data = require("@wordpress/data");
var _htmlEntities = require("@wordpress/html-entities");
var _coreData = require("@wordpress/core-data");
var _store = require("../../store");
var _constants = require("./constants");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

function useAuthorsQuery(search) {
  const {
    authorId,
    authors,
    postAuthor
  } = (0, _data.useSelect)(select => {
    const {
      getUser,
      getUsers
    } = select(_coreData.store);
    const {
      getEditedPostAttribute
    } = select(_store.store);
    const _authorId = getEditedPostAttribute('author');
    const query = {
      ..._constants.AUTHORS_QUERY
    };
    if (search) {
      query.search = search;
      query.search_columns = ['name'];
    }
    return {
      authorId: _authorId,
      authors: getUsers(query),
      postAuthor: getUser(_authorId, _constants.BASE_QUERY)
    };
  }, [search]);
  const authorOptions = (0, _element.useMemo)(() => {
    const fetchedAuthors = (authors !== null && authors !== void 0 ? authors : []).map(author => {
      return {
        value: author.id,
        label: (0, _htmlEntities.decodeEntities)(author.name)
      };
    });

    // Ensure the current author is included in the dropdown list.
    const foundAuthor = fetchedAuthors.findIndex(({
      value
    }) => postAuthor?.id === value);
    let currentAuthor = [];
    if (foundAuthor < 0 && postAuthor) {
      currentAuthor = [{
        value: postAuthor.id,
        label: (0, _htmlEntities.decodeEntities)(postAuthor.name)
      }];
    } else if (foundAuthor < 0 && !postAuthor) {
      currentAuthor = [{
        value: 0,
        label: (0, _i18n.__)('(No author)')
      }];
    }
    return [...currentAuthor, ...fetchedAuthors];
  }, [authors, postAuthor]);
  return {
    authorId,
    authorOptions,
    postAuthor
  };
}
//# sourceMappingURL=hook.js.map