"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// packages/block-editor/src/components/inserter/index.js
var inserter_exports = {};
__export(inserter_exports, {
  default: () => inserter_default
});
module.exports = __toCommonJS(inserter_exports);
var import_clsx = __toESM(require("clsx"));
var import_a11y = require("@wordpress/a11y");
var import_i18n = require("@wordpress/i18n");
var import_components = require("@wordpress/components");
var import_data = require("@wordpress/data");
var import_blocks = require("@wordpress/blocks");
var import_element = require("@wordpress/element");
var import_icons = require("@wordpress/icons");
var import_menu = __toESM(require("./menu.cjs"));
var import_quick_inserter = __toESM(require("./quick-inserter.cjs"));
var import_store = require("../../store/index.cjs");
var import_get_appender_label = require("./get-appender-label.cjs");
var import_jsx_runtime = require("react/jsx-runtime");
var UnforwardedInserterToggle = ({
  onToggle,
  disabled,
  isOpen,
  blockTitle,
  hasSingleBlockType,
  appenderLabel,
  toggleProps = {}
}, ref) => {
  const {
    as: Wrapper = import_components.Button,
    label: labelProp,
    onClick,
    ...rest
  } = toggleProps;
  let label = labelProp;
  if (!label && appenderLabel) {
    label = appenderLabel;
  } else if (!label && hasSingleBlockType) {
    label = (0, import_i18n.sprintf)(
      // translators: %s: the name of the block when there is only one
      (0, import_i18n._x)("Add %s", "directly add the only allowed block"),
      blockTitle.toLowerCase()
    );
  } else if (!label) {
    label = (0, import_i18n._x)("Add block", "Generic label for block inserter button");
  }
  function handleClick(event) {
    if (onToggle) {
      onToggle(event);
    }
    if (onClick) {
      onClick(event);
    }
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    Wrapper,
    {
      ref,
      __next40pxDefaultSize: toggleProps.as ? void 0 : true,
      icon: import_icons.plus,
      label,
      tooltipPosition: "bottom",
      onClick: handleClick,
      className: "block-editor-inserter__toggle",
      "aria-haspopup": !hasSingleBlockType ? "true" : false,
      "aria-expanded": !hasSingleBlockType ? isOpen : false,
      isPressed: !hasSingleBlockType && isOpen,
      disabled,
      ...rest
    }
  );
};
var InserterToggle = (0, import_element.forwardRef)(UnforwardedInserterToggle);
var UnforwardedInserter = ({
  clientId,
  rootClientId,
  disabled,
  isAppender,
  position,
  selectBlockOnInsert,
  shouldDirectInsert = true,
  showInserterHelpPanel,
  // This prop is experimental to give some time for the quick inserter to mature
  // Feel free to make them stable after a few releases.
  __experimentalIsQuick: isQuick,
  onSelectOrClose,
  onToggle,
  renderToggle: renderToggleProp,
  toggleProps
}, ref) => {
  const {
    hasItems,
    hasSingleBlockType,
    blockTitle,
    allowedBlockType,
    blockToInsert,
    appenderLabel,
    targetRootClientId
  } = (0, import_data.useSelect)(
    (select) => {
      const {
        getBlockRootClientId: getBlockRootClientId2,
        hasInserterItems,
        getAllowedBlocks,
        getDirectInsertBlock,
        getBlockListSettings
      } = select(import_store.store);
      const { getBlockVariations, getBlockType: getBlockType2 } = select(import_blocks.store);
      const _targetRootClientId = rootClientId || getBlockRootClientId2(clientId) || void 0;
      const allowedBlocks = getAllowedBlocks(_targetRootClientId);
      const directInsertBlock = shouldDirectInsert && getDirectInsertBlock(_targetRootClientId);
      const { defaultBlock } = getBlockListSettings(_targetRootClientId) ?? {};
      const _hasSingleBlockType = allowedBlocks?.length === 1 && getBlockVariations(allowedBlocks[0].name, "inserter")?.length === 0;
      const _allowedBlockType = _hasSingleBlockType ? allowedBlocks[0] : null;
      let _blockToInsert = directInsertBlock || null;
      if (!_blockToInsert && _hasSingleBlockType && defaultBlock?.name === _allowedBlockType.name) {
        _blockToInsert = defaultBlock;
      }
      const defaultBlockType = directInsertBlock ? getBlockType2(directInsertBlock.name) : null;
      return {
        hasItems: hasInserterItems(_targetRootClientId),
        hasSingleBlockType: _hasSingleBlockType,
        blockTitle: _allowedBlockType ? _allowedBlockType.title : "",
        allowedBlockType: _allowedBlockType,
        blockToInsert: _blockToInsert,
        appenderLabel: (0, import_get_appender_label.getAppenderLabel)(
          directInsertBlock,
          defaultBlockType
        ),
        targetRootClientId: _targetRootClientId
      };
    },
    [rootClientId, clientId, shouldDirectInsert]
  );
  const { insertBlock } = (0, import_data.useDispatch)(import_store.store);
  const {
    getBlock,
    getBlockIndex,
    getBlockOrder,
    getBlockRootClientId,
    getBlockSelectionEnd,
    getPreviousBlockClientId
  } = (0, import_data.useSelect)(import_store.store);
  const { getActiveBlockVariation, getBlockType } = (0, import_data.useSelect)(import_blocks.store);
  if (!hasItems && (isAppender || targetRootClientId || clientId)) {
    return null;
  }
  function insertOnlyAllowedBlock() {
    const blockName = blockToInsert?.name ?? allowedBlockType.name;
    function getAdjacentBlockAttributes(attributesToCopy) {
      if (!attributesToCopy?.length) {
        return {};
      }
      let adjacentAttributes;
      if (clientId) {
        const currentBlock = getBlock(clientId);
        const previousBlock = getBlock(
          getPreviousBlockClientId(clientId)
        );
        if (currentBlock?.name === previousBlock?.name) {
          adjacentAttributes = previousBlock?.attributes;
        }
      } else if (targetRootClientId) {
        const lastInnerBlock = getBlock(targetRootClientId)?.innerBlocks?.at(-1);
        if (lastInnerBlock?.name === blockName) {
          adjacentAttributes = lastInnerBlock.attributes;
        }
      }
      if (!adjacentAttributes) {
        return {};
      }
      return Object.fromEntries(
        attributesToCopy.filter((attr) => attr in adjacentAttributes).map((attr) => [attr, adjacentAttributes[attr]])
      );
    }
    function getInsertionIndex() {
      if (clientId) {
        return getBlockIndex(clientId);
      }
      const end = getBlockSelectionEnd();
      if (!isAppender && end && getBlockRootClientId(end) === targetRootClientId) {
        return getBlockIndex(end) + 1;
      }
      return getBlockOrder(targetRootClientId).length;
    }
    const newAttributes = getAdjacentBlockAttributes(
      blockToInsert?.attributesToCopy
    );
    const newBlock = (0, import_blocks.createBlock)(blockName, {
      ...blockToInsert?.attributes,
      ...newAttributes
    });
    insertBlock(
      newBlock,
      getInsertionIndex(),
      targetRootClientId,
      selectBlockOnInsert
    );
    onSelectOrClose?.(newBlock);
    const blockTypeToInsert = getBlockType(blockName);
    let blockLabelToInsert;
    if (blockTypeToInsert) {
      blockLabelToInsert = (0, import_blocks.__experimentalGetBlockLabel)(
        blockTypeToInsert,
        newBlock.attributes
      );
      if (blockLabelToInsert === blockTypeToInsert.title) {
        blockLabelToInsert = getActiveBlockVariation(blockName, newBlock.attributes)?.title || blockLabelToInsert;
      }
    }
    if (blockLabelToInsert) {
      const message = (0, import_i18n.sprintf)(
        // translators: %s: the name of the block that has been added
        (0, import_i18n.__)("%s block added"),
        blockLabelToInsert
      );
      (0, import_a11y.speak)(message);
    }
  }
  function renderToggle({ onToggle: dropdownOnToggle, isOpen }) {
    const toggleArgs = {
      onToggle: dropdownOnToggle,
      isOpen,
      disabled: disabled || !hasItems,
      blockTitle,
      hasSingleBlockType,
      appenderLabel,
      toggleProps
    };
    if (renderToggleProp) {
      return renderToggleProp(toggleArgs);
    }
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(InserterToggle, { ref, ...toggleArgs });
  }
  function renderContent({ onClose }) {
    if (isQuick) {
      return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
        import_quick_inserter.default,
        {
          onSelect: (blocks) => {
            const firstBlock = Array.isArray(blocks) && blocks?.length ? blocks[0] : blocks;
            if (onSelectOrClose && typeof onSelectOrClose === "function") {
              onSelectOrClose(firstBlock);
            }
            onClose();
          },
          rootClientId: targetRootClientId,
          clientId,
          isAppender,
          selectBlockOnInsert
        }
      );
    }
    return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
      import_menu.default,
      {
        onSelect: () => {
          onClose();
        },
        onClose,
        rootClientId: targetRootClientId,
        clientId,
        isAppender,
        showInserterHelpPanel
      }
    );
  }
  if (hasSingleBlockType || blockToInsert) {
    return renderToggle({ onToggle: insertOnlyAllowedBlock });
  }
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
    import_components.Dropdown,
    {
      className: "block-editor-inserter",
      contentClassName: (0, import_clsx.default)("block-editor-inserter__popover", {
        "is-quick": isQuick
      }),
      popoverProps: { position, shift: true },
      onToggle,
      expandOnMobile: true,
      headerTitle: (0, import_i18n.__)("Add a block"),
      renderToggle,
      renderContent,
      onClose: onSelectOrClose
    }
  );
};
var Inserter = (0, import_element.forwardRef)(UnforwardedInserter);
var inserter_default = Inserter;
//# sourceMappingURL=index.cjs.map
