"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.PrivateInserterMenu = void 0;
var _clsx = _interopRequireDefault(require("clsx"));
var _element = require("@wordpress/element");
var _components = require("@wordpress/components");
var _i18n = require("@wordpress/i18n");
var _compose = require("@wordpress/compose");
var _data = require("@wordpress/data");
var _tips = _interopRequireDefault(require("./tips"));
var _previewPanel = _interopRequireDefault(require("./preview-panel"));
var _blockTypesTab = _interopRequireDefault(require("./block-types-tab"));
var _blockPatternsTab = _interopRequireDefault(require("./block-patterns-tab"));
var _patternCategoryPreviewPanel = require("./block-patterns-tab/pattern-category-preview-panel");
var _mediaTab = require("./media-tab");
var _searchResults = _interopRequireDefault(require("./search-results"));
var _useInsertionPoint = _interopRequireDefault(require("./hooks/use-insertion-point"));
var _store = require("../../store");
var _tabbedSidebar = _interopRequireDefault(require("../tabbed-sidebar"));
var _useZoomOut = require("../../hooks/use-zoom-out");
var _jsxRuntime = require("react/jsx-runtime");
/**
 * External dependencies
 */

/**
 * WordPress dependencies
 */

/**
 * Internal dependencies
 */

const NOOP = () => {};
function InserterMenu({
  rootClientId,
  clientId,
  isAppender,
  __experimentalInsertionIndex,
  onSelect,
  showInserterHelpPanel,
  showMostUsedBlocks,
  __experimentalFilterValue = '',
  shouldFocusBlock = true,
  onPatternCategorySelection,
  onClose,
  __experimentalInitialTab,
  __experimentalInitialCategory
}, ref) {
  const isZoomOutMode = (0, _data.useSelect)(select => select(_store.store).__unstableGetEditorMode() === 'zoom-out', []);
  const [filterValue, setFilterValue, delayedFilterValue] = (0, _compose.useDebouncedInput)(__experimentalFilterValue);
  const [hoveredItem, setHoveredItem] = (0, _element.useState)(null);
  const [selectedPatternCategory, setSelectedPatternCategory] = (0, _element.useState)(__experimentalInitialCategory);
  const [patternFilter, setPatternFilter] = (0, _element.useState)('all');
  const [selectedMediaCategory, setSelectedMediaCategory] = (0, _element.useState)(null);
  const [selectedTab, setSelectedTab] = (0, _element.useState)(__experimentalInitialTab);
  const [destinationRootClientId, onInsertBlocks, onToggleInsertionPoint] = (0, _useInsertionPoint.default)({
    rootClientId,
    clientId,
    isAppender,
    insertionIndex: __experimentalInsertionIndex,
    shouldFocusBlock
  });
  const blockTypesTabRef = (0, _element.useRef)();
  const onInsert = (0, _element.useCallback)((blocks, meta, shouldForceFocusBlock, _rootClientId) => {
    onInsertBlocks(blocks, meta, shouldForceFocusBlock, _rootClientId);
    onSelect(blocks);

    // Check for focus loss due to filtering blocks by selected block type
    window.requestAnimationFrame(() => {
      if (!shouldFocusBlock && !blockTypesTabRef?.current.contains(ref.current.ownerDocument.activeElement)) {
        // There has been a focus loss, so focus the first button in the block types tab
        blockTypesTabRef?.current.querySelector('button').focus();
      }
    });
  }, [onInsertBlocks, onSelect, shouldFocusBlock]);
  const onInsertPattern = (0, _element.useCallback)((blocks, patternName) => {
    onInsertBlocks(blocks, {
      patternName
    });
    onSelect();
  }, [onInsertBlocks, onSelect]);
  const onHover = (0, _element.useCallback)(item => {
    onToggleInsertionPoint(item);
    setHoveredItem(item);
  }, [onToggleInsertionPoint, setHoveredItem]);
  const onHoverPattern = (0, _element.useCallback)(item => {
    onToggleInsertionPoint(!!item);
  }, [onToggleInsertionPoint]);
  const onClickPatternCategory = (0, _element.useCallback)((patternCategory, filter) => {
    setSelectedPatternCategory(patternCategory);
    setPatternFilter(filter);
    onPatternCategorySelection?.();
  }, [setSelectedPatternCategory, onPatternCategorySelection]);
  const showPatternPanel = selectedTab === 'patterns' && !delayedFilterValue && !!selectedPatternCategory;
  const showMediaPanel = selectedTab === 'media' && !!selectedMediaCategory;
  const showZoomOut = showPatternPanel && !!window.__experimentalEnableZoomedOutPatternsTab;
  (0, _useZoomOut.useZoomOut)(showZoomOut);
  const inserterSearch = (0, _element.useMemo)(() => {
    if (selectedTab === 'media') {
      return null;
    }
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.SearchControl, {
        __nextHasNoMarginBottom: true,
        className: "block-editor-inserter__search",
        onChange: value => {
          if (hoveredItem) {
            setHoveredItem(null);
          }
          setFilterValue(value);
        },
        value: filterValue,
        label: (0, _i18n.__)('Search for blocks and patterns'),
        placeholder: (0, _i18n.__)('Search')
      }), !!delayedFilterValue && /*#__PURE__*/(0, _jsxRuntime.jsx)(_searchResults.default, {
        filterValue: delayedFilterValue,
        onSelect: onSelect,
        onHover: onHover,
        onHoverPattern: onHoverPattern,
        rootClientId: rootClientId,
        clientId: clientId,
        isAppender: isAppender,
        __experimentalInsertionIndex: __experimentalInsertionIndex,
        showBlockDirectory: true,
        shouldFocusBlock: shouldFocusBlock,
        prioritizePatterns: selectedTab === 'patterns'
      })]
    });
  }, [selectedTab, hoveredItem, setHoveredItem, setFilterValue, filterValue, delayedFilterValue, onSelect, onHover, onHoverPattern, shouldFocusBlock, clientId, rootClientId, __experimentalInsertionIndex, isAppender]);
  const blocksTab = (0, _element.useMemo)(() => {
    return /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
        className: "block-editor-inserter__block-list",
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockTypesTab.default, {
          ref: blockTypesTabRef,
          rootClientId: destinationRootClientId,
          onInsert: onInsert,
          onHover: onHover,
          showMostUsedBlocks: showMostUsedBlocks
        })
      }), showInserterHelpPanel && /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
        className: "block-editor-inserter__tips",
        children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_components.VisuallyHidden, {
          as: "h2",
          children: (0, _i18n.__)('A tip for using the block editor')
        }), /*#__PURE__*/(0, _jsxRuntime.jsx)(_tips.default, {})]
      })]
    });
  }, [destinationRootClientId, onInsert, onHover, showMostUsedBlocks, showInserterHelpPanel]);
  const patternsTab = (0, _element.useMemo)(() => {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_blockPatternsTab.default, {
      rootClientId: destinationRootClientId,
      onInsert: onInsertPattern,
      onSelectCategory: onClickPatternCategory,
      selectedCategory: selectedPatternCategory,
      children: showPatternPanel && /*#__PURE__*/(0, _jsxRuntime.jsx)(_patternCategoryPreviewPanel.PatternCategoryPreviewPanel, {
        rootClientId: destinationRootClientId,
        onInsert: onInsertPattern,
        onHover: onHoverPattern,
        category: selectedPatternCategory,
        patternFilter: patternFilter,
        showTitlesAsTooltip: true
      })
    });
  }, [destinationRootClientId, onHoverPattern, onInsertPattern, onClickPatternCategory, patternFilter, selectedPatternCategory, showPatternPanel]);
  const mediaTab = (0, _element.useMemo)(() => {
    return /*#__PURE__*/(0, _jsxRuntime.jsx)(_mediaTab.MediaTab, {
      rootClientId: destinationRootClientId,
      selectedCategory: selectedMediaCategory,
      onSelectCategory: setSelectedMediaCategory,
      onInsert: onInsert,
      children: showMediaPanel && /*#__PURE__*/(0, _jsxRuntime.jsx)(_mediaTab.MediaCategoryPanel, {
        rootClientId: destinationRootClientId,
        onInsert: onInsert,
        category: selectedMediaCategory
      })
    });
  }, [destinationRootClientId, onInsert, selectedMediaCategory, setSelectedMediaCategory, showMediaPanel]);
  const handleSetSelectedTab = value => {
    // If no longer on patterns tab remove the category setting.
    if (value !== 'patterns') {
      setSelectedPatternCategory(null);
    }
    setSelectedTab(value);
  };

  // Focus first active tab, if any
  const tabsRef = (0, _element.useRef)();
  (0, _element.useLayoutEffect)(() => {
    if (tabsRef.current) {
      window.requestAnimationFrame(() => {
        tabsRef.current.querySelector('[role="tab"][aria-selected="true"]')?.focus();
      });
    }
  }, []);
  return /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
    className: (0, _clsx.default)('block-editor-inserter__menu', {
      'show-panel': showPatternPanel || showMediaPanel,
      'is-zoom-out': isZoomOutMode
    }),
    ref: ref,
    children: [/*#__PURE__*/(0, _jsxRuntime.jsx)("div", {
      className: "block-editor-inserter__main-area",
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_tabbedSidebar.default, {
        ref: tabsRef,
        onSelect: handleSetSelectedTab,
        onClose: onClose,
        selectedTab: selectedTab,
        closeButtonLabel: (0, _i18n.__)('Close block inserter'),
        tabs: [{
          name: 'blocks',
          title: (0, _i18n.__)('Blocks'),
          panel: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
            children: [inserterSearch, selectedTab === 'blocks' && !delayedFilterValue && blocksTab]
          })
        }, {
          name: 'patterns',
          title: (0, _i18n.__)('Patterns'),
          panel: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
            children: [inserterSearch, selectedTab === 'patterns' && !delayedFilterValue && patternsTab]
          })
        }, {
          name: 'media',
          title: (0, _i18n.__)('Media'),
          panel: /*#__PURE__*/(0, _jsxRuntime.jsxs)(_jsxRuntime.Fragment, {
            children: [inserterSearch, mediaTab]
          })
        }]
      })
    }), showInserterHelpPanel && hoveredItem && /*#__PURE__*/(0, _jsxRuntime.jsx)(_components.Popover, {
      className: "block-editor-inserter__preview-container__popover",
      placement: "right-start",
      offset: 16,
      focusOnMount: false,
      animate: false,
      children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_previewPanel.default, {
        item: hoveredItem
      })
    })]
  });
}
const PrivateInserterMenu = exports.PrivateInserterMenu = (0, _element.forwardRef)(InserterMenu);
function PublicInserterMenu(props, ref) {
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(PrivateInserterMenu, {
    ...props,
    onPatternCategorySelection: NOOP,
    ref: ref
  });
}
var _default = exports.default = (0, _element.forwardRef)(PublicInserterMenu);
//# sourceMappingURL=menu.js.map