"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.BlockTypesTab = BlockTypesTab;
exports.BlockTypesTabPanel = BlockTypesTabPanel;
exports.default = void 0;
var _i18n = require("@wordpress/i18n");
var _element = require("@wordpress/element");
var _compose = require("@wordpress/compose");
var _blockTypesList = _interopRequireDefault(require("../block-types-list"));
var _panel = _interopRequireDefault(require("./panel"));
var _useBlockTypesState = _interopRequireDefault(require("./hooks/use-block-types-state"));
var _inserterListbox = _interopRequireDefault(require("../inserter-listbox"));
var _sorting = require("../../utils/sorting");
var _noResults = _interopRequireDefault(require("./no-results"));
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const getBlockNamespace = item => item.name.split('/')[0];
const MAX_SUGGESTED_ITEMS = 6;

/**
 * Shared reference to an empty array for cases where it is important to avoid
 * returning a new array reference on every invocation and rerendering the component.
 *
 * @type {Array}
 */
const EMPTY_ARRAY = [];
function BlockTypesTabPanel({
  items,
  collections,
  categories,
  onSelectItem,
  onHover,
  showMostUsedBlocks,
  className
}) {
  const suggestedItems = (0, _element.useMemo)(() => {
    return (0, _sorting.orderBy)(items, 'frecency', 'desc').slice(0, MAX_SUGGESTED_ITEMS);
  }, [items]);
  const uncategorizedItems = (0, _element.useMemo)(() => {
    return items.filter(item => !item.category);
  }, [items]);
  const itemsPerCollection = (0, _element.useMemo)(() => {
    // Create a new Object to avoid mutating collection.
    const result = {
      ...collections
    };
    Object.keys(collections).forEach(namespace => {
      result[namespace] = items.filter(item => getBlockNamespace(item) === namespace);
      if (result[namespace].length === 0) {
        delete result[namespace];
      }
    });
    return result;
  }, [items, collections]);

  // Hide block preview on unmount.
  (0, _element.useEffect)(() => () => onHover(null), []);

  /**
   * The inserter contains a big number of blocks and opening it is a costful operation.
   * The rendering is the most costful part of it, in order to improve the responsiveness
   * of the "opening" action, these lazy lists allow us to render the inserter category per category,
   * once all the categories are rendered, we start rendering the collections and the uncategorized block types.
   */
  const currentlyRenderedCategories = (0, _compose.useAsyncList)(categories);
  const didRenderAllCategories = categories.length === currentlyRenderedCategories.length;

  // Async List requires an array.
  const collectionEntries = (0, _element.useMemo)(() => {
    return Object.entries(collections);
  }, [collections]);
  const currentlyRenderedCollections = (0, _compose.useAsyncList)(didRenderAllCategories ? collectionEntries : EMPTY_ARRAY);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: className,
    children: [showMostUsedBlocks &&
    // Only show the most used blocks if the total amount of block
    // is larger than 1 row, otherwise it is not so useful.
    items.length > 3 && !!suggestedItems.length && /*#__PURE__*/(0, _jsxRuntime.jsx)(_panel.default, {
      title: (0, _i18n._x)('Most used', 'blocks'),
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockTypesList.default, {
        items: suggestedItems,
        onSelect: onSelectItem,
        onHover: onHover,
        label: (0, _i18n._x)('Most used', 'blocks')
      })
    }), currentlyRenderedCategories.map(category => {
      const categoryItems = items.filter(item => item.category === category.slug);
      if (!categoryItems || !categoryItems.length) {
        return null;
      }
      return /*#__PURE__*/(0, _jsxRuntime.jsx)(_panel.default, {
        title: category.title,
        icon: category.icon,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockTypesList.default, {
          items: categoryItems,
          onSelect: onSelectItem,
          onHover: onHover,
          label: category.title
        })
      }, category.slug);
    }), didRenderAllCategories && uncategorizedItems.length > 0 && /*#__PURE__*/(0, _jsxRuntime.jsx)(_panel.default, {
      className: "block-editor-inserter__uncategorized-blocks-panel",
      title: (0, _i18n.__)('Uncategorized'),
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockTypesList.default, {
        items: uncategorizedItems,
        onSelect: onSelectItem,
        onHover: onHover,
        label: (0, _i18n.__)('Uncategorized')
      })
    }), currentlyRenderedCollections.map(([namespace, collection]) => {
      const collectionItems = itemsPerCollection[namespace];
      if (!collectionItems || !collectionItems.length) {
        return null;
      }
      return /*#__PURE__*/(0, _jsxRuntime.jsx)(_panel.default, {
        title: collection.title,
        icon: collection.icon,
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockTypesList.default, {
          items: collectionItems,
          onSelect: onSelectItem,
          onHover: onHover,
          label: collection.title
        })
      }, namespace);
    })]
  });
}
function BlockTypesTab({
  rootClientId,
  onInsert,
  onHover,
  showMostUsedBlocks
}, ref) {
  const [items, categories, collections, onSelectItem] = (0, _useBlockTypesState.default)(rootClientId, onInsert);
  if (!items.length) {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_noResults.default, {});
  }
  const itemsForCurrentRoot = [];
  const itemsRemaining = [];
  for (const item of items) {
    // Skip reusable blocks, they moved to the patterns tab.
    if (item.category === 'reusable') {
      continue;
    }
    if (rootClientId && item.rootClientId === rootClientId) {
      itemsForCurrentRoot.push(item);
    } else {
      itemsRemaining.push(item);
    }
  }
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_inserterListbox.default, {
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      ref: ref,
      children: [!!itemsForCurrentRoot.length && /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(BlockTypesTabPanel, {
          items: itemsForCurrentRoot,
          categories: categories,
          collections: collections,
          onSelectItem: onSelectItem,
          onHover: onHover,
          showMostUsedBlocks: showMostUsedBlocks,
          className: "block-editor-inserter__insertable-blocks-at-selection"
        })
      }), /*#__PURE__*/(0, _jsxRuntime.jsx)(BlockTypesTabPanel, {
        items: itemsRemaining,
        categories: categories,
        collections: collections,
        onSelectItem: onSelectItem,
        onHover: onHover,
        showMostUsedBlocks: showMostUsedBlocks,
        className: "block-editor-inserter__all-blocks"
      })]
    })
  });
}
var _default = exports.default = (0, _element.forwardRef)(BlockTypesTab);
//# sourceMappingURL=block-types-tab.js.map