"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _element = require("@wordpress/element");
var _i18n = require("@wordpress/i18n");
var _components = require("@wordpress/components");
var _compose = require("@wordpress/compose");
var _a11y = require("@wordpress/a11y");
var _data = require("@wordpress/data");
var _blockTypesList = _interopRequireDefault(require("../block-types-list"));
var _blockPatternsList = _interopRequireDefault(require("../block-patterns-list"));
var _inserterMenuExtension = _interopRequireDefault(require("../inserter-menu-extension"));
var _panel = _interopRequireDefault(require("./panel"));
var _noResults = _interopRequireDefault(require("./no-results"));
var _useInsertionPoint = _interopRequireDefault(require("./hooks/use-insertion-point"));
var _usePatternsState = _interopRequireDefault(require("./hooks/use-patterns-state"));
var _useBlockTypesState = _interopRequireDefault(require("./hooks/use-block-types-state"));
var _searchItems = require("./search-items");
var _inserterListbox = _interopRequireDefault(require("../inserter-listbox"));
var _sorting = require("../../utils/sorting");
var _orderInserterBlockItems = require("../../utils/order-inserter-block-items");
var _store = require("../../store");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const INITIAL_INSERTER_RESULTS = 9;
/**
 * 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 InserterSearchResults({
  filterValue,
  onSelect,
  onHover,
  onHoverPattern,
  rootClientId,
  clientId,
  isAppender,
  __experimentalInsertionIndex,
  maxBlockPatterns,
  maxBlockTypes,
  showBlockDirectory = false,
  isDraggable = true,
  shouldFocusBlock = true,
  prioritizePatterns,
  selectBlockOnInsert,
  isQuick
}) {
  const debouncedSpeak = (0, _compose.useDebounce)(_a11y.speak, 500);
  const {
    prioritizedBlocks
  } = (0, _data.useSelect)(select => {
    const blockListSettings = select(_store.store).getBlockListSettings(rootClientId);
    return {
      prioritizedBlocks: blockListSettings?.prioritizedInserterBlocks || EMPTY_ARRAY
    };
  }, [rootClientId]);
  const [destinationRootClientId, onInsertBlocks] = (0, _useInsertionPoint.default)({
    onSelect,
    rootClientId,
    clientId,
    isAppender,
    insertionIndex: __experimentalInsertionIndex,
    shouldFocusBlock,
    selectBlockOnInsert
  });
  const [blockTypes, blockTypeCategories, blockTypeCollections, onSelectBlockType] = (0, _useBlockTypesState.default)(destinationRootClientId, onInsertBlocks, isQuick);
  const [patterns,, onClickPattern] = (0, _usePatternsState.default)(onInsertBlocks, destinationRootClientId);
  const filteredBlockPatterns = (0, _element.useMemo)(() => {
    if (maxBlockPatterns === 0) {
      return [];
    }
    const results = (0, _searchItems.searchItems)(patterns, filterValue);
    return maxBlockPatterns !== undefined ? results.slice(0, maxBlockPatterns) : results;
  }, [filterValue, patterns, maxBlockPatterns]);
  let maxBlockTypesToShow = maxBlockTypes;
  if (prioritizePatterns && filteredBlockPatterns.length > 2) {
    maxBlockTypesToShow = 0;
  }
  const filteredBlockTypes = (0, _element.useMemo)(() => {
    if (maxBlockTypesToShow === 0) {
      return [];
    }
    const nonPatternBlockTypes = blockTypes.filter(blockType => blockType.name !== 'core/block');
    let orderedItems = (0, _sorting.orderBy)(nonPatternBlockTypes, 'frecency', 'desc');
    if (!filterValue && prioritizedBlocks.length) {
      orderedItems = (0, _orderInserterBlockItems.orderInserterBlockItems)(orderedItems, prioritizedBlocks);
    }
    const results = (0, _searchItems.searchBlockItems)(orderedItems, blockTypeCategories, blockTypeCollections, filterValue);
    return maxBlockTypesToShow !== undefined ? results.slice(0, maxBlockTypesToShow) : results;
  }, [filterValue, blockTypes, blockTypeCategories, blockTypeCollections, maxBlockTypesToShow, prioritizedBlocks]);

  // Announce search results on change.
  (0, _element.useEffect)(() => {
    if (!filterValue) {
      return;
    }
    const count = filteredBlockTypes.length + filteredBlockPatterns.length;
    const resultsFoundMessage = (0, _i18n.sprintf)( /* translators: %d: number of results. */
    (0, _i18n._n)('%d result found.', '%d results found.', count), count);
    debouncedSpeak(resultsFoundMessage);
  }, [filterValue, debouncedSpeak, filteredBlockTypes, filteredBlockPatterns]);
  const currentShownBlockTypes = (0, _compose.useAsyncList)(filteredBlockTypes, {
    step: INITIAL_INSERTER_RESULTS
  });
  const currentShownPatterns = (0, _compose.useAsyncList)(currentShownBlockTypes.length === filteredBlockTypes.length ? filteredBlockPatterns : EMPTY_ARRAY);
  const hasItems = filteredBlockTypes.length > 0 || filteredBlockPatterns.length > 0;
  const blocksUI = !!filteredBlockTypes.length && /*#__PURE__*/(0, _jsxRuntime.jsx)(_panel.default, {
    title: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.VisuallyHidden, {
      children: (0, _i18n.__)('Blocks')
    }),
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockTypesList.default, {
      items: currentShownBlockTypes,
      onSelect: onSelectBlockType,
      onHover: onHover,
      label: (0, _i18n.__)('Blocks'),
      isDraggable: isDraggable
    })
  });
  const patternsUI = !!filteredBlockPatterns.length && /*#__PURE__*/(0, _jsxRuntime.jsx)(_panel.default, {
    title: /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.VisuallyHidden, {
      children: (0, _i18n.__)('Block patterns')
    }),
    children: /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "block-editor-inserter__quick-inserter-patterns",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockPatternsList.default, {
        shownPatterns: currentShownPatterns,
        blockPatterns: filteredBlockPatterns,
        onClickPattern: onClickPattern,
        onHover: onHoverPattern,
        isDraggable: isDraggable
      })
    })
  });
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_inserterListbox.default, {
    children: [!showBlockDirectory && !hasItems && /*#__PURE__*/(0, _jsxRuntime.jsx)(_noResults.default, {}), prioritizePatterns ? patternsUI : blocksUI, !!filteredBlockTypes.length && !!filteredBlockPatterns.length && /*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "block-editor-inserter__quick-inserter-separator"
    }), prioritizePatterns ? blocksUI : patternsUI, showBlockDirectory && /*#__PURE__*/(0, _jsxRuntime.jsx)(_inserterMenuExtension.default.Slot, {
      fillProps: {
        onSelect: onSelectBlockType,
        onHover,
        filterValue,
        hasItems,
        rootClientId: destinationRootClientId
      },
      children: fills => {
        if (fills.length) {
          return fills;
        }
        if (!hasItems) {
          return /*#__PURE__*/(0, _jsxRuntime.jsx)(_noResults.default, {});
        }
        return null;
      }
    })]
  });
}
var _default = exports.default = InserterSearchResults;
//# sourceMappingURL=search-results.js.map