@wordpress/block-library
Version:
Block library for the WordPress editor.
45 lines (44 loc) • 1.87 kB
JavaScript
import { store } from "@wordpress/block-editor";
import { useDispatch, useSelect } from "@wordpress/data";
import { useEffect } from "@wordpress/element";
// packages/block-library/src/tabs/use-tab-list-items-sync.js
const EMPTY_ARRAY = [];
/**
* Keep the tab-list block's `tabs` attribute in sync with the tab-panel blocks.
*
* Whenever the list of core/tab-panel blocks changes (add, remove, reorder, or
* label edit), this hook updates the `tabs` attribute on the core/tab-list
* block so that save.jsx can render the correct buttons.
*
* @param {string} tabsClientId Client ID of the core/tabs block.
*/
function useTabListItemsSync(tabsClientId) {
const { tabPanels, tabListClientId } = useSelect((select) => {
const { getBlocks } = select(store);
const innerBlocks = getBlocks(tabsClientId);
const tabPanelsBlock = innerBlocks.find((block) => block.name === "core/tab-panels");
const tabList = innerBlocks.find((block) => block.name === "core/tab-list");
return {
tabPanels: tabPanelsBlock?.innerBlocks ?? EMPTY_ARRAY,
tabListClientId: tabList?.clientId ?? null
};
}, [tabsClientId]);
const { updateBlockAttributes, __unstableMarkNextChangeAsNotPersistent } = useDispatch(store);
const { getBlockAttributes } = useSelect(store);
useEffect(() => {
if (!tabListClientId) return;
const newTabs = tabPanels.map((tab) => ({ label: tab.attributes.label || "" }));
const currentTabs = getBlockAttributes(tabListClientId)?.tabs ?? [];
if (JSON.stringify(newTabs) === JSON.stringify(currentTabs)) return;
__unstableMarkNextChangeAsNotPersistent();
updateBlockAttributes(tabListClientId, { tabs: newTabs });
}, [
tabPanels,
tabListClientId,
getBlockAttributes,
updateBlockAttributes,
__unstableMarkNextChangeAsNotPersistent
]);
}
export { useTabListItemsSync as default };
//# sourceMappingURL=use-tab-list-items-sync.mjs.map