UNPKG

@wordpress/block-library

Version:
88 lines (87 loc) 2.83 kB
// packages/block-library/src/tabs/use-tab-actions.js import { createBlock } from "@wordpress/blocks"; import { store as blockEditorStore } from "@wordpress/block-editor"; import { useDispatch, useRegistry } from "@wordpress/data"; function useTabActions(tabsClientId) { const registry = useRegistry(); const { insertBlock, removeBlock, moveBlocksToPosition, updateBlockAttributes, __unstableMarkNextChangeAsNotPersistent } = useDispatch(blockEditorStore); const getTabsState = () => { const { getBlocks, getBlockAttributes } = registry.select(blockEditorStore); const tabsAttributes = tabsClientId ? getBlockAttributes(tabsClientId) : void 0; const tabPanels = tabsClientId ? getBlocks(tabsClientId).find( (block) => block.name === "core/tab-panels" ) : void 0; return { tabPanelsClientId: tabPanels?.clientId ?? null, tabPanelBlocks: tabPanels?.innerBlocks ?? [], activeIndex: tabsAttributes?.editorActiveTabIndex ?? tabsAttributes?.activeTabIndex ?? 0 }; }; const insertTab = (atIndex) => { const { tabPanelsClientId, tabPanelBlocks } = getTabsState(); if (!tabPanelsClientId) { return; } const newIndex = atIndex ?? tabPanelBlocks.length; insertBlock( createBlock("core/tab-panel"), newIndex, tabPanelsClientId, false ); __unstableMarkNextChangeAsNotPersistent(); updateBlockAttributes(tabsClientId, { editorActiveTabIndex: newIndex }); }; const removeTab = (atIndex) => { const { tabPanelBlocks, activeIndex } = getTabsState(); const tabCount = tabPanelBlocks.length; if (tabCount <= 1) { return; } const removeIndex = atIndex ?? activeIndex; const target = tabPanelBlocks[removeIndex]; if (!target) { return; } const newActiveIndex = removeIndex >= tabCount - 1 ? tabCount - 2 : removeIndex; __unstableMarkNextChangeAsNotPersistent(); updateBlockAttributes(tabsClientId, { editorActiveTabIndex: newActiveIndex }); removeBlock(target.clientId, false); }; const moveTab = (direction) => { const { tabPanelsClientId, tabPanelBlocks, activeIndex } = getTabsState(); if (!tabPanelsClientId) { return; } const toIndex = activeIndex + direction; const target = tabPanelBlocks[activeIndex]; if (!target || toIndex < 0 || toIndex >= tabPanelBlocks.length) { return; } __unstableMarkNextChangeAsNotPersistent(); updateBlockAttributes(tabsClientId, { editorActiveTabIndex: toIndex }); moveBlocksToPosition( [target.clientId], tabPanelsClientId, tabPanelsClientId, toIndex ); }; return { insertTab, removeTab, moveTab }; } export { useTabActions as default }; //# sourceMappingURL=use-tab-actions.mjs.map