@wordpress/block-library
Version:
Block library for the WordPress editor.
50 lines (49 loc) • 2.17 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _wordpress_block_editor = require("@wordpress/block-editor");
let _wordpress_data = require("@wordpress/data");
let _wordpress_element = require("@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 } = (0, _wordpress_data.useSelect)((select) => {
const { getBlocks } = select(_wordpress_block_editor.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 } = (0, _wordpress_data.useDispatch)(_wordpress_block_editor.store);
const { getBlockAttributes } = (0, _wordpress_data.useSelect)(_wordpress_block_editor.store);
(0, _wordpress_element.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
]);
}
exports.default = useTabListItemsSync;
//# sourceMappingURL=use-tab-list-items-sync.cjs.map