// packages/block-library/src/tab-panel/add-tab-toolbar-control.js
import { __ } from "@wordpress/i18n";
import { createBlock } from "@wordpress/blocks";
import {
  BlockControls,
  store as blockEditorStore
} from "@wordpress/block-editor";
import { ToolbarGroup, ToolbarButton } from "@wordpress/components";
import { useDispatch, useSelect } from "@wordpress/data";
import { jsx } from "react/jsx-runtime";
function AddTabToolbarControl({ tabsClientId }) {
  const {
    insertBlock,
    updateBlockAttributes,
    selectBlock,
    __unstableMarkNextChangeAsNotPersistent
  } = useDispatch(blockEditorStore);
  const { tabPanelsClientId, tabCount, tabListClientId } = useSelect(
    (select) => {
      if (!tabsClientId) {
        return {
          tabPanelsClientId: null,
          tabCount: 0,
          tabListClientId: null
        };
      }
      const { getBlocks } = select(blockEditorStore);
      const innerBlocks = getBlocks(tabsClientId);
      const tabPanels = innerBlocks.find(
        (block) => block.name === "core/tab-panels"
      );
      const tabList = innerBlocks.find(
        (block) => block.name === "core/tab-list"
      );
      return {
        tabPanelsClientId: tabPanels?.clientId || null,
        tabCount: tabPanels?.innerBlocks?.length || 0,
        tabListClientId: tabList?.clientId || null
      };
    },
    [tabsClientId]
  );
  const addTab = () => {
    if (!tabPanelsClientId) {
      return;
    }
    const newTabPanelBlock = createBlock("core/tab-panel", {
      label: __("Tab")
    });
    insertBlock(newTabPanelBlock, void 0, tabPanelsClientId, false);
    const newIndex = tabCount;
    __unstableMarkNextChangeAsNotPersistent();
    updateBlockAttributes(tabsClientId, {
      editorActiveTabIndex: newIndex
    });
    if (tabListClientId) {
      selectBlock(tabListClientId);
    }
  };
  return /* @__PURE__ */ jsx(BlockControls, { group: "other", children: /* @__PURE__ */ jsx(ToolbarGroup, { children: /* @__PURE__ */ jsx(
    ToolbarButton,
    {
      className: "components-toolbar__control",
      onClick: addTab,
      text: __("Add tab")
    }
  ) }) });
}
export {
  AddTabToolbarControl as default
};
//# sourceMappingURL=add-tab-toolbar-control.mjs.map
